/// Cost-balanced range boundaries over one zoom's tile space, with seek positions, for exactly /// `workers` ranges. See [`plan_ranges_from`]. #[cfg(test)] fn plan_ranges( chunks: &[ChunkRef], spill: &ChunkSpill, z: u8, workers: usize, ) -> Result { let hist = histogram(chunks, spill)?; plan_ranges_from(chunks, spill, z, workers, hist) } /// Merged-tile bytes per planning cost unit (features + coordinates), for sizing ranges against /// [`RANGE_AHEAD_BYTES`]: coordinates dominate at 8 bytes each. An estimate; never observable. const BYTES_PER_COST: u64 = 12; /// Most ranges one zoom is cut into. Bounds the plan's per-chunk seek tables /// (`chunks x ranges` rows). const MAX_MERGE_RANGES: usize = 4096; /// [`plan_ranges`] with the range count chosen from the zoom's own size: enough ranges that /// `merge_workers` of them in flight fit the run-ahead allowance about twice over, so the merge /// keeps every worker busy rather than parking all but the one being drained. Never fewer than /// `merge_workers`. The count is a scheduling choice: ranges concatenate to the serial sequence /// however many there are. fn plan_ranges_auto( chunks: &[ChunkRef], spill: &ChunkSpill, z: u8, merge_workers: usize, ) -> Result { let hist = histogram(chunks, spill)?; let per_range = (RANGE_AHEAD_BYTES / (2 * merge_workers.max(1) as u64)).max(1); let wanted = (hist.total.saturating_mul(BYTES_PER_COST)).div_ceil(per_range) as usize; let ranges = wanted.clamp(merge_workers.max(1), MAX_MERGE_RANGES); plan_ranges_from(chunks, spill, z, ranges, hist) } /// Cost-balanced range boundaries over one zoom's tile space, with seek /// positions. /// /// Two skip-walks over every chunk — header parses and length walks only, no allocation, no /// UTF-8, no struct builds, roughly a tenth of a full decode each — both run across the pool, /// one chunk per task (they were serial: 231 s of the Nov 10 planet build). Pass 1 ([`histogram`]) /// accumulates per-tile cost and cuts tile-granular ranges from it; pass 2 records each chunk's /// cursor at every range bound, so seeks are exact and ranges never overlap. /// /// Exactness is load-bearing, not decorative: the spill's `check_books` gate /// requires every entry decoded exactly once, so a range that re-reads /// another's entries fails the build. An earlier revision sought /// bucket-granular cursors with a skip loop absorbing the difference — the /// loop walked entries the neighbouring range also walked, the books showed /// ~196 KB read past written on a California z14, and the build rightly /// refused. Two walks cost one extra scan; overlapping seeks cost the build. /// /// Cuts are tile-granular because bucket edges proved too coarse: z14's cost /// concentrates inside single buckets (one bucket held 97% of a California /// z14), so no bucket-edge cut could balance and seven of eight workers /// idled. fn plan_ranges_from( chunks: &[ChunkRef], spill: &ChunkSpill, z: u8, workers: usize, hist: Histogram, ) -> Result { use tilecodec::pmtiles::zoom_base; debug_assert!( parallel_merge_supported(z), "plan_ranges needs an exact span/256 split (z4+); z{z} must stay serial" ); let base = zoom_base(z); let Histogram { tiles, total, chunk_max, chunk_total, hot_tile, hot_cost, runs } = hist; // Greedy cost balance over TILES, not buckets: cut when crossing each // multiple of total/workers, with the cut falling between the tiles that // straddle the mark. Fixed rule on scanned data — deterministic across // runs and machines. let mut bounds = vec![base]; let mut acc = 0u64; let mut cuts = 1usize; for &(tile, cost) in &tiles { // Commit the cut BEFORE adding this tile's cost when the mark was // already reached: the cut then falls between the previous tile and // this one, and this tile opens the next range. Cutting after would // hand the straddling tile's whole cost to the range that already // crossed its mark — which is how one range ends up owning nearly the // whole zoom. while cuts < workers && acc as u128 * workers as u128 >= total as u128 * cuts as u128 { if tile > *bounds.last().expect("bounds") { bounds.push(tile); } cuts += 1; } acc += cost; } // The trailing range owns through the last tile: no cut is committed // after the loop (the zoom end sentinel below closes it). bounds.push(zoom_base(z + 1)); bounds.dedup(); // Padding: fewer distinct cut positions than workers (tiny zoom, or one // tile holding everything). Pad with the zoom end — never with a tile // strictly inside the span, which would hand two ranges the same tile. while bounds.len() < workers + 1 { bounds.push(zoom_base(z + 1)); } // Per-range cost from the same tile histogram the cuts came from. let range_cost: Vec = (0..workers) .map(|r| { let lo = tiles.partition_point(|t| t.0 < bounds[r]); let hi = tiles.partition_point(|t| t.0 < bounds[r + 1]); tiles[lo..hi].iter().map(|t| t.1).sum() }) .collect(); drop(tiles); // Pass 2: each chunk's cursor at every range bound, one chunk per task. Bounds ascend and the // walk is tile-ordered, so one pointer walks the bounds while the entries stream past: bound // `r` records the cursor (and consumed count) of the first entry with tile >= bounds[r] — // exactly the first entry the range can own. Ranges partition tiles, so seeks partition // entries: nothing is read twice, and the books balance by construction. #[allow(clippy::type_complexity)] let rows: Vec, Vec, Vec)>> = par::install(|| { chunks .par_iter() .enumerate() .map(|(ci, chunk)| -> Result<(Vec, Vec, Vec)> { let mut at_bound = 0usize; let mut bound_off = vec![0u64; workers + 1]; let mut bound_con = vec![0u64; workers + 1]; bound_off[0] = chunk.at; let mut consumed = 0u64; if let Some(chunk_runs) = runs.get(&(chunk.at, chunk.len)) { // From the recorded runs: the first entry at-or-after a bound is the first // entry of the first run whose tile reaches it -- the same cursor and count // the walk below arrives at, without reading the chunk. for run in chunk_runs { while at_bound < workers && run.tile >= bounds[at_bound] { bound_off[at_bound] = chunk.at + run.rel_offset as u64; bound_con[at_bound] = run.before as u64; at_bound += 1; } } consumed = chunk.entries; } let mut reader = spill.reader(chunk, 64 << 10); if runs.contains_key(&(chunk.at, chunk.len)) { reader.seek_to(chunk.at + chunk.len, 0, false); } loop { let off = reader.position(); let Some(((tile, _), _)) = reader.skip_entry()? else { break; }; while at_bound < workers && tile >= bounds[at_bound] { bound_off[at_bound] = off; bound_con[at_bound] = consumed; at_bound += 1; } consumed += 1; } // Bounds past the chunk's last tile: chunk end, everything consumed. The range // then seeks to chunk end with nothing remaining — it owns nothing here. while at_bound <= workers { bound_off[at_bound] = chunk.at + chunk.len; bound_con[at_bound] = consumed; at_bound += 1; } debug_assert_eq!( consumed, chunk_total[ci], "the two planning walks must agree on chunk {ci}'s entry count" ); let mut orow = Vec::with_capacity(workers); let mut rrow = Vec::with_capacity(workers); let mut erow = Vec::with_capacity(workers); for r in 0..workers { orow.push(bound_off[r]); // Owned entries: everything from this bound to the next. rrow.push(bound_con[r + 1].saturating_sub(bound_con[r])); // Exact end iff the chunk's max tile sits inside this range. erow.push(chunk_max[ci] < bounds[r + 1] && chunk_max[ci] >= bounds[r]); } Ok((orow, rrow, erow)) }) .collect() }); let mut offsets = Vec::with_capacity(chunks.len()); let mut remaining = Vec::with_capacity(chunks.len()); let mut exact_end = Vec::with_capacity(chunks.len()); for row in rows { let (o, r, e) = row?; offsets.push(o); remaining.push(r); exact_end.push(e); } Ok(RangePlan { bounds, range_cost, hot_tile, hot_cost, offsets, remaining, exact_end }) } /// One range worker's output: tiles in ascending order, or the first error. /// /// The error carries its range index so the coordinator reports the /// lowest-indexed failure — deterministic, matching serial's earliest-tile /// failure. Workers exit when their range is drained or the coordinator drops /// the receiver (abort on an earlier range's failure): a failed `send` ends /// the worker rather than blocking it forever. type RangeOut = Result<(u64, Vec)>; /// Merge one tile range over all chunks, streaming results in order. /// /// Same heap discipline as [`Merged`]: chunks consumed in global chunk order, /// entries for one tile arriving layer-major, concatenated as they arrive. A /// range is exactly the serial merge restricted to its tile span, so its /// output is the serial output's subsequence — concatenating ranges in order /// reproduces the serial tile sequence byte for byte. /// /// `end_tile` bounds the range (exclusive); entries at-or-after it stay /// unread for the next range. Chunks not touching the range are skipped /// without opening a reader. fn merge_range( chunks: &[ChunkRef], spill: &ChunkSpill, plan: &RangePlan, range: usize, end_tile: u64, out: &RangeTx, ) { use std::cmp::Reverse; use std::collections::BinaryHeap; // Padded trailing ranges ([zoom end, zoom end)) own nothing: yield // nothing rather than decoding bucket 255 a second time. if plan.bounds[range] >= end_tile { return; } let window = crate::tilespill::read_window_bytes(chunks.len()); let ranges = plan.bounds.len() - 1; let start_tile = plan.bounds[range]; let mut readers: Vec>> = Vec::with_capacity(chunks.len()); 'chunks: for (ci, chunk) in chunks.iter().enumerate() { let remaining = plan.remaining[ci][range]; if remaining == 0 { readers.push(None); continue; } // The window never larger than this chunk's share of the range: with many small ranges // that share is often a few KB, and a full window per chunk per range would be both the // memory and the I/O. A window size is unobservable in the output (pinned by test). let start = plan.offsets[ci][range]; let end = if range + 1 < ranges { plan.offsets[ci][range + 1] } else { chunk.at + chunk.len }; let span = (end.saturating_sub(start) as usize).max(1); let mut reader = spill.reader(chunk, window.min(span)); reader.seek_to(start, remaining, plan.exact_end[ci][range]); // Bucket edges are coarser than range bounds: advance past entries // below the bound (skip-walked, uncounted, `left` adjusted by the // skips themselves so it still exhausts exactly at range end). A // corrupt entry reports through the channel like a decode error. loop { let below = match reader.peek_tile() { Ok(Some(t)) => t < start_tile, Ok(None) => false, Err(e) => { // On to the next chunk. (A bare `continue` here re-ran this skip loop on the // same failed reader forever, queueing an error and a reader slot per turn: // unbounded memory instead of a failed build.) let _ = out.send(Err(e)); readers.push(None); continue 'chunks; } }; if !below { break; } match reader.skip_entry() { Ok(Some(_)) => {} Ok(None) => break, Err(e) => { // On to the next chunk. (A bare `continue` here re-ran this skip loop on the // same failed reader forever, queueing an error and a reader slot per turn: // unbounded memory instead of a failed build.) let _ = out.send(Err(e)); readers.push(None); continue 'chunks; } } } readers.push(Some(reader)); } let mut heap: BinaryHeap> = BinaryHeap::new(); let mut front: Vec = Vec::with_capacity(chunks.len()); for (index, reader) in readers.iter_mut().enumerate() { let head = match reader { Some(r) => r.next().transpose(), None => None, }; match &head { Some(Ok(((tile, layer), _))) => heap.push(Reverse((*tile, *layer, index))), Some(Err(_)) => heap.push(Reverse((0, 0, index))), None => {} } front.push(head); } // Mirrors `Merged::next`: the heap top names the tile, the inner loop // drains it, entries concatenate layer-major in chunk order. while let Some(&Reverse((tile, _, _))) = heap.peek() { if tile >= end_tile { break; } let mut layers: Vec = Vec::new(); while let Some(&Reverse((at, layer_id, index))) = heap.peek() { if at != tile { break; } heap.pop(); let held = front[index].take().expect("a heap key without its entry"); let (_, mut layer) = match held { Ok(entry) => entry, Err(e) => { let _ = out.send(Err(e)); return; } }; match layers.last_mut() { Some(last) if last.layer.layer_id == layer_id => { concatenate(last, &mut layer); if let Some(r) = readers[index].as_mut() { r.recycle(layer); } } _ => layers.push(layer), } let head = match &mut readers[index] { Some(r) => r.next().transpose(), None => None, }; match &head { Some(Ok(((t, l), _))) => heap.push(Reverse((*t, *l, index))), Some(Err(_)) => heap.push(Reverse((0, 0, index))), None => {} } front[index] = head; } if out.send(Ok((tile, layers))).is_err() { return; } } } /// Range-worker entry point for `thread::scope` spawning: merges range `r` /// and streams it, converting panics-by-Result into channel values. /// /// Never returns `Err` itself (there is nowhere for it to go — the /// coordinator owns failure reporting): fallible setup is unreachable here /// because planning already validated every seek position, so the body is /// infallible by construction and any `Err` produced mid-merge travels as a /// value. fn merge_range_into( chunks: &[ChunkRef], spill: &ChunkSpill, plan: &RangePlan, r: usize, tx: RangeTx, ) { let end_tile = plan.bounds[r + 1]; merge_range(chunks, spill, plan, r, end_tile, &tx); } /// Run-ahead allowance for range workers other than the one being drained, in estimated bytes of /// merged tile (see [`tile_bytes`]), shared by all of them. /// /// Ranges drain strictly in order, and each worker used to stop after `RANGE_QUEUE_BOUND` tiles: /// so while range 0 drained, ranges 1..7 sat parked after 32 tiles each and the "parallel" merge /// was one k-way merge at a time (California z13: merge 4.5 s however many ranges; the Nov 10 /// planet's z10-z12 merge+encode ran at 6-13 cores). Now the later ranges keep merging into /// their queues until this much is buffered between them. The range being drained keeps the old /// count bound -- it is consumed as it is produced -- and is never held by this budget, which is /// what keeps the drain deadlock-free: the coordinator only ever waits on the current range, and /// the current range only ever waits on the coordinator. const RANGE_AHEAD_BYTES: u64 = 4 << 30; /// A merged tile's rough size in memory, for [`RANGE_AHEAD_BYTES`]: its feature records and its /// coordinates. An estimate for a budget, never observable in the output. fn tile_bytes(layers: &[ChunkEntry]) -> u64 { layers .iter() .map(|entry| entry.layer.features.len() as u64 * 32 + entry.layer.coords.len() as u64 * 8) .sum::() + 64 } /// The range workers' output queues, drained in range order by [`ParallelMerge`]. struct RangeQueues { state: Mutex, cv: std::sync::Condvar, } struct RangeState { /// Per range: queued tiles (with their byte estimate) and whether its worker is done. queues: Vec>, finished: Vec, /// The range the coordinator is draining. current: usize, /// Bytes queued in ranges past `current`. ahead: u64, /// The coordinator went away (finished early on an error): workers stop. abandoned: bool, /// Who is parked on the condvar, so the hot paths notify only when someone is: a wake per /// tile was the merge's whole cost on a zoom of millions of small tiles. coordinator_waiting: bool, workers_waiting: usize, }