#[cfg(test)] mod tests_parallel { use super::*; use crate::tiler::tests::*; use crate::tilespill::{ChunkRef, ChunkSpill}; /// Drive a merge iterator to a vec, failing the test on the first error /// rather than publishing a short sequence. fn collect(merged: &mut I) -> Vec<(u64, Vec)> where I: Iterator)>>, { merged .by_ref() .collect::>>() .expect("merge the chunks") } /// Map a fixture into spill chunks at `z`, returning refs plus the spill. /// The spill outlives the refs: callers keep both alive together. Forces /// small vertex chunks so the fixture spans several chunks even at test /// scale (a single-chunk merge exercises nothing). fn map_chunks( features: &[crate::extract::Feature], z: u8, ) -> (Vec, ChunkSpill) { let _guard = budget(); crate::tiler::set_chunk_vertices(64); let store = spilled(features); let spill = ChunkSpill::create(scratch()).expect("spill"); let tolerance = tile_build::simplify::tolerance_for(z, crate::DEFAULT_MAX_ZOOM, 1.0); let buffer = tile_build::geom::buffer_for(crate::tiler::EXTENT); let settings = settings(0, 14); let _ = &settings; let (chunks, _) = crate::tiler::map_zoom(&store, &settings, z, tolerance, buffer, &spill) .expect("map the fixture"); crate::tiler::set_chunk_vertices(0); (chunks, spill) } /// The gate this work stands on: range-parallel output is the serial /// output, tile for tile, layer for layer, byte for byte — over a /// multi-chunk fixture with lakes, buildings and cross-tile rivers, at a /// zoom where the wash gate fires (z14) and one where it does not (z10). /// Both zooms are above z3, where the bucket table inverts exactly (see /// `parallel_merge_supported`) — the identity below rests on that. #[test] fn parallel_merge_is_the_serial_merge() { for z in [10u8, 14] { let (chunks, spill) = map_chunks(&a_crowd(), z); assert!(chunks.len() > 1, "the fixture must span chunks at z{z}"); let mut serial = super::merge(&chunks, &spill); let want = collect(&mut serial); assert!(!want.is_empty(), "the fixture must yield tiles at z{z}"); for workers in [2usize, 3, 7] { let plan = super::plan_ranges(&chunks, &spill, z, workers).expect("plan the ranges"); let got = std::thread::scope(|s| { let queues = super::RangeQueues::new(workers); let chunks_ref = &chunks; let spill_ref = &spill; let plan_ref = &plan; for r in 0..workers { let tx = queues.sender(r); s.spawn(move || { super::merge_range_into(chunks_ref, spill_ref, plan_ref, r, tx); }); } let mut coord = super::ParallelMerge::new(queues); collect(&mut coord) }); assert_eq!(got, want, "worker count {workers} moved z{z}"); } } } /// The planner answers the same from `write_chunk`'s recorded tile runs as from skip-walking /// the chunks back off the spill: same cuts, seeks, counts and ends. (The first plan takes the /// runs; the second finds them gone and walks.) #[test] fn planning_from_recorded_runs_equals_walking_the_chunks() { for z in [10u8, 14] { for workers in [2usize, 5, 13] { let (chunks, spill) = map_chunks(&a_crowd(), z); let indexed = super::plan_ranges(&chunks, &spill, z, workers).expect("plan"); let walked = super::plan_ranges(&chunks, &spill, z, workers).expect("plan"); assert_eq!(indexed.bounds, walked.bounds, "z{z} x{workers}"); assert_eq!(indexed.range_cost, walked.range_cost, "z{z} x{workers}"); assert_eq!((indexed.hot_tile, indexed.hot_cost), (walked.hot_tile, walked.hot_cost)); assert_eq!(indexed.offsets, walked.offsets, "z{z} x{workers}"); assert_eq!(indexed.remaining, walked.remaining, "z{z} x{workers}"); assert_eq!(indexed.exact_end, walked.exact_end, "z{z} x{workers}"); } } } /// Empty chunks (a map chunk whose features all clipped away) start where the next chunk /// starts. The run index must not hand one chunk's runs to the other: re-spill a fixture with /// an empty chunk ahead of every real one and the indexed plan still equals the walked plan, /// and the parallel merge still equals the serial one. #[test] fn empty_chunks_do_not_borrow_their_neighbours_runs() { let z = 14u8; let (chunks, spill) = map_chunks(&a_crowd(), z); let respill = ChunkSpill::create(scratch()).expect("spill"); let mut rechunks = Vec::new(); for chunk in &chunks { let mut reader = spill.reader(chunk, 64 << 10); let mut map = std::collections::BTreeMap::new(); while let Some((key, entry)) = reader.next().expect("read back") { map.insert(key, entry); } rechunks.push(respill.write_chunk(std::collections::BTreeMap::new()).expect("empty")); rechunks.push(respill.write_chunk(map).expect("chunk")); } assert!(rechunks.windows(2).any(|w| w[0].len == 0 && w[0].at == w[1].at)); let want = collect(&mut super::merge(&rechunks, &respill)); for workers in [2usize, 5] { let indexed = super::plan_ranges(&rechunks, &respill, z, workers).expect("plan"); let walked = super::plan_ranges(&rechunks, &respill, z, workers).expect("plan"); assert_eq!(indexed.offsets, walked.offsets); assert_eq!(indexed.remaining, walked.remaining); assert_eq!(indexed.exact_end, walked.exact_end); assert_eq!(indexed.bounds, walked.bounds); // A fresh index for the merge itself. let respill2 = ChunkSpill::create(scratch()).expect("spill"); let mut again = Vec::new(); for c in &rechunks { let mut reader = respill.reader(c, 64 << 10); let mut map = std::collections::BTreeMap::new(); while let Some((key, entry)) = reader.next().expect("read back") { map.insert(key, entry); } again.push(respill2.write_chunk(map).expect("chunk")); } let plan = super::plan_ranges(&again, &respill2, z, workers).expect("plan"); let got = std::thread::scope(|s| { let queues = super::RangeQueues::new(workers); for r in 0..workers { let tx = queues.sender(r); let (c, sp, p) = (&again, &respill2, &plan); s.spawn(move || super::merge_range_into(c, sp, p, r, tx)); } collect(&mut super::ParallelMerge::new(queues)) }); assert_eq!(got, want, "x{workers}"); } } /// A range worker whose reader fails while skipping to the range start reports the error and /// finishes, rather than looping on the failed reader. Here the plan is corrupted on purpose /// (a seek one byte into an entry). #[test] fn a_failing_range_reader_reports_and_stops() { let z = 14u8; let (chunks, spill) = map_chunks(&a_crowd(), z); let workers = 3usize; let mut plan = super::plan_ranges(&chunks, &spill, z, workers).expect("plan"); let r = 1usize; let ci = (0..chunks.len()) .find(|&ci| plan.remaining[ci][r] > 0) .expect("a chunk with entries in the middle range"); plan.offsets[ci][r] += 1; let queues = super::RangeQueues::new(workers); std::thread::scope(|s| { for w in 0..workers { let tx = queues.sender(w); let (c, sp, p) = (&chunks, &spill, &plan); s.spawn(move || super::merge_range_into(c, sp, p, w, tx)); } }); let mut coord = super::ParallelMerge::new(queues); assert!(coord.by_ref().any(|item| item.is_err()), "the corrupt seek must surface"); } /// Ranges that hold nothing yield nothing: a single-tile fixture merged /// under more workers than tiles still produces exactly that tile. /// (A pool, not a lake: wash areas never reach z14 tiles under the cap.) #[test] fn empty_ranges_yield_nothing() { let pool = crate::extract::Feature { class: crate::schema::Class::area( tilecodec::mamaps::dict::LAYER_LANDTYPE, crate::schema::kind("swimming_pool"), 14, ), geometry: crate::tiler::tests::square(-122.0, 37.0, 0.005), name: None, id: tilecodec::mamaps::body::ID_NONE, transit_color: 0, transit_ordinal: 0, transit_lanes: 0, transit_taper: 0, lane_count: 0, turn_fwd: Vec::new(), turn_bwd: Vec::new(), building: None, carriageway: tilecodec::mamaps::body::Carriageway::default(), }; let (chunks, spill) = map_chunks(&[pool], 14); let mut serial = super::merge(&chunks, &spill); let want = collect(&mut serial); assert!(!want.is_empty()); let workers = 4usize; let plan = super::plan_ranges(&chunks, &spill, 14, workers).expect("plan"); let got = std::thread::scope(|s| { let queues = super::RangeQueues::new(workers); let chunks_ref = &chunks; let spill_ref = &spill; let plan_ref = &plan; for r in 0..workers { let tx = queues.sender(r); s.spawn(move || { super::merge_range_into(chunks_ref, spill_ref, plan_ref, r, tx); }); } let mut coord = super::ParallelMerge::new(queues); collect(&mut coord) }); assert_eq!(got, want, "empty ranges must not add or drop tiles"); } /// The seek/count half of the plan, pinned directly: per-chunk /// `remaining` summed over chunks must cover the range's tile-layer /// entries — every (tile, layer) pair the range owns must be walked, no /// fewer. The serial merge yields each tile with its layers; counting /// layer entries per tile over the serial output gives the per-tile /// histogram, and each range's share must be covered by the plan's rows. /// /// Coverage, not equality: the plan counts from the containing bucket's /// cursor, so it INCLUDES the below-bound prefix the skip loop walks AND /// the mid-bucket tail past the end bound that the `end_tile` stop /// discards. Planned >= wanted always; planned < wanted means a starved /// reader — the failure this test exists to catch. #[test] fn plan_seek_counts_match_the_tile_histogram() { for z in [10u8, 14] { let (chunks, spill) = map_chunks(&a_crowd(), z); assert!(chunks.len() > 1, "the fixture must span chunks at z{z}"); // Per-tile LAYER-entry counts from the serial output: one per // (tile, layer) pair, which is the unit the spill — and the // reader's `left` budget — counts in. let mut serial = super::merge(&chunks, &spill); let mut tile_entries: HashMap = HashMap::new(); for (tile, layers) in collect(&mut serial) { *tile_entries.entry(tile).or_insert(0) += layers.len() as u64; } for workers in [2usize, 3, 7] { let plan = super::plan_ranges(&chunks, &spill, z, workers).expect("plan the ranges"); // Bounds ascend and partition the zoom: first is the base, // last is the end sentinel, workers+1 entries. assert_eq!(plan.bounds.len(), workers + 1, "z{z} w{workers}"); for w in plan.bounds.windows(2) { assert!(w[0] <= w[1], "bounds ascend at z{z} w{workers}"); } for r in 0..workers { // Entries the plan says range r walks, summed over chunks. let planned: u64 = plan.remaining.iter().map(|row| row[r]).sum(); // Layer entries the histogram puts inside the range. let want: u64 = tile_entries .iter() .filter(|(&t, _)| t >= plan.bounds[r] && t < plan.bounds[r + 1]) .map(|(_, &n)| n) .sum(); assert!( planned >= want, "z{z} w{workers} range {r}: plan walks {planned}, histogram holds {want}" ); } } } } /// z0–z3 stay serial: their spans (1–64 tiles) don't divide the 256 cost /// buckets, so range edges can't invert exactly. The zoom loop gates on /// this — if the gate ever lets a low zoom through, planning must refuse. #[test] fn low_zooms_stay_serial() { for z in [0u8, 1, 2, 3] { assert!(!super::parallel_merge_supported(z), "z{z} must stay serial"); } for z in [4u8, 10, 14] { assert!(super::parallel_merge_supported(z), "z{z} must parallelise"); } } /// The full-archive version of the merge gate: the zoom loop's own /// selection (`merge_gate` → plan/workers vs serial) agrees with itself /// across thread counts. The unit tests above drive the planner and /// workers directly; this drives `build()` end to end — so a miswired /// gate can't hide behind correct components. One thread takes the /// serial path (single worker cap... no: `merge_workers > 1` fails, so /// serial), four threads take the range workers wherever the zoom is big /// enough; both must produce the same archive. #[test] fn gate_paths_agree_through_build() { use crate::tiler::tests::{budget, release_threads}; let _guard = budget(); crate::tiler::set_chunk_vertices(64); let store = spilled(&a_crowd()); tile_build::par::set_threads(1); let serial = crate::tiler::build(&store, &settings(0, 14)).expect("one thread").0; tile_build::par::set_threads(4); let parallel = crate::tiler::build(&store, &settings(0, 14)).expect("four threads").0; crate::tiler::set_chunk_vertices(0); release_threads(); assert_eq!(parallel, serial, "thread count moved the archive"); } }