/// Merge → encode → prune → append for one zoom, over any tile-ordered merge /// iterator. /// /// Extracted whole from the zoom loop so serial and range-parallel merges share /// it: batches are contiguous pulls in merge order, `encode_batch` preserves /// tile order, and prune/append see the identical sequence either way — which /// is why the archive does not move between the two paths. #[allow(clippy::too_many_arguments)] fn consume_merged( merged: &mut (impl Iterator)>> + Send), stats: &mut ZoomStats, z: u8, timer: &mut crate::timing::PhaseTimer, dem: &crate::dem::Dem, conventions: &crate::schema::boundaries::Conventions, region_links: &std::collections::HashMap, writer: &mut tilecodec::mamaps::write::StreamWriter, ) -> Result<()> { // Merge, encode and append have no total to count against -- the tile count is only known once // the merge has produced it -- so the merge bar counts tiles merged and the encode line below // counts tiles written. let zoom_start = std::time::Instant::now(); let mut merged_tiles = 0usize; let mut merge_shown = 0usize; let mut written = 0usize; let mut shown = 0usize; // Pipelined by one batch: while batch `k` is appended (serial: the writer's dedup and its // scratch writes), batch `k + 1` is pulled from the merge and encoded on the pool. The three // used to take turns, so the pool sat idle through every append and the writer through // every encode. Batches are the same contiguous pulls of the merge, encoded and pruned // exactly as before (`prune_barren_subtree` never looks past its own batch), and appended in // the same order, so the archive does not move. The per-zoom `merge`/`encode`/`append` // columns still time each part on its own; the run's phase clock books the overlapped // stretch as `merge`. let mut pending: Option> = None; // A third stage ahead of those two: a puller thread takes the merge batches (the k-way merge, // or the parallel coordinator) for pass `k + 2` while pass `k + 1` encodes and pass `k` // appends. The pulls are the same `merge_batch` calls in the same order with the same cuts, // only on another thread; the hand-off is a one-deep channel, so at most one pulled pass // waits beside the two in flight. type Pulled = Result)>, Vec, u64)>>; std::thread::scope(|scope| -> Result<()> { let (pull_tx, pull_rx) = std::sync::mpsc::sync_channel::(1); let merged = &mut *merged; scope.spawn(move || loop { let merging = std::time::Instant::now(); // Several merge batches per encode pass, each cut exactly where `merge_batch` // always cut it. One cost-capped batch is too little work to spread over 192 threads // (California z13: ~8 encode tasks running, the rest of the pool spinning), but the // cut points are what `prune_barren_subtree` is bounded by, so they are kept and each // batch is pruned on its own. Encoding is per tile, so the bytes do not depend on how // many batches share a pass. let mut batch: Vec<(u64, Vec)> = Vec::new(); let mut cuts: Vec = Vec::new(); let mut failed = None; for _ in 0..BATCHES_PER_ENCODE { // A truncated scratch file must fail the build rather than end the zoom early and // publish a short archive. match merge_batch(&mut *merged, par::batch_len()) { Ok(pulled) if pulled.is_empty() => break, Ok(pulled) => { batch.extend(pulled); cuts.push(batch.len()); } Err(e) => { failed = Some(e); break; } } } let item: Pulled = match failed { Some(e) => Err(e), None if batch.is_empty() => Ok(None), None => Ok(Some((batch, cuts, merging.elapsed().as_millis() as u64))), }; let last = !matches!(item, Ok(Some(_))); if pull_tx.send(item).is_err() || last { return; } }); loop { // Cost-batched rather than count-batched: z14 has tiles whose merged geometry is tens // of MB (a dense city tile's whole layer set) beside rural tiles worth bytes. A // fixed `batch_len()` of those holds ~GB of merged tiles plus their encoded copies // before the writer takes them -- on top of the merge's own peak, on a box with // ~50 GB of commit headroom, which is where `Map z14 [100%]` went followed by a // 512 KiB allocation failure. Capped at `MERGE_BATCH_BYTES` of merged cost, so a // heavy tile still gets its own batch (a minimum of one batch per pull) and common // zooms -- whose batches never reach the cap -- take the same count they always // did. Order is untouched: batches are contiguous pulls of the merge in order, and // `encode_batch` preserves tile order, so the archive does not move. timer.switch("merge"); let pulled = pull_rx .recv() .unwrap_or_else(|_| Err(tile_build::proto::Error("the merge puller stopped".into()))); let (appended, produced) = par::install(|| { rayon::join( || -> Result { let Some(done) = pending.take() else { return Ok(0) }; let appending = std::time::Instant::now(); for (id, encoded, rings, lines) in done { stats.rings.add(rings); stats.lines.add(lines); let Some((stored, raw_len, hash)) = encoded else { continue }; // Uncompressed, as this column has always meant. stats.bytes += raw_len as u64; stats.tiles += 1; // Handed over whole: the writer's background thread copies and // writes the body, this thread only does the dedup bookkeeping. writer.append_stored_owned(id, stored, hash)?; written += 1; // Every 25k tiles: often enough to look alive on a continent, rare // enough that the write itself is never the cost. if written - shown >= 25_000 { shown = written; eprint!( "\r{:<28} [{written:>10} tile(s)] {} elapsed ", format!("Encode z{z}"), tile_build::progress::hms(zoom_start.elapsed().as_secs_f64()), ); let _ = std::io::Write::flush(&mut std::io::stderr()); } } Ok(appending.elapsed().as_millis() as u64) }, || -> Result> { let Some((batch, cuts, merge_ms)) = pulled? else { return Ok(None) }; let tiles = batch.len(); let encoding = std::time::Instant::now(); let encoded = encode_batch(batch, dem, conventions, region_links)?; // Phase B: prune barren subtrees. A tile whose four children all came // back empty (`None` — genuinely featureless, or full-bleed water // background) is itself the end of the tree: drop the children and let // the reader stop at the parent (overzoom). Only above z0 and only when // all four children of a parent are present-and-empty in one merge // batch — never across batch boundaries, so the archive stays // independent of batching and thread count. let mut done: Vec = Vec::with_capacity(encoded.len()); let mut encoded = encoded.into_iter(); let mut start = 0usize; for &end in &cuts { let mut piece: Vec = encoded.by_ref().take(end - start).collect(); prune_barren_subtree(z, &mut piece); done.extend(piece); start = end; } Ok(Some((done, tiles, merge_ms, encoding.elapsed().as_millis() as u64))) }, ) }); // The append of the earlier batch reports first, as it did when it ran first. stats.append_ms += appended?; let Some((done, tiles, merge_ms, encode_ms)) = produced? else { break }; stats.merge_ms += merge_ms; stats.encode_ms += encode_ms; // Count the tiles as soon as the merge produced them, so the bar moves during the // merge rather than only when the append drains. merged_tiles += tiles; if merged_tiles - merge_shown >= 25_000 { merge_shown = merged_tiles; eprint!( "\r{:<28} [{merged_tiles:>10} tile(s)] {} elapsed ", format!("Merge z{z}"), tile_build::progress::hms(zoom_start.elapsed().as_secs_f64()), ); let _ = std::io::Write::flush(&mut std::io::stderr()); } pending = Some(done); } Ok(()) })?; if merged_tiles > 0 { eprintln!( "\r{:<28} [{merged_tiles:>10} tile(s)] {} elapsed ", format!("Merge z{z}"), tile_build::progress::hms(zoom_start.elapsed().as_secs_f64()), ); } if written > 0 { eprintln!( "\r{:<28} [{written:>10} tile(s)] {} elapsed ", format!("Encode z{z}"), tile_build::progress::hms(zoom_start.elapsed().as_secs_f64()), ); } Ok(()) } /// Merge batches gathered into one encode pass by [`consume_merged`]. Each keeps its own cut (and /// its own prune); this only decides how much work one pool hand-off carries. const BATCHES_PER_ENCODE: usize = 16; /// One merge pull, capped by merged-geometry cost rather than by tile count. /// /// Pulls up to `max_tiles` from the merge, stopping early once the accumulated `tile_cost` -- /// features plus coordinates, the same proxy the encode pass balances tasks by -- reaches /// [`MERGE_BATCH_BYTES`]. Always pulls at least one tile, so a tile heavier than the cap on its /// own still makes progress. The pulled prefix is contiguous merge order, so feeding it to /// `encode_batch` (which preserves tile order) keeps the archive byte-identical: the only /// change is how many tiles one batch holds. /// /// Contiguity is also what [`prune_barren_subtree`] relies on: four siblings of one parent /// occupy consecutive tile ids, so a parent's whole child set is either inside one batch or /// split across a batch boundary — and only the first case prunes, which keeps the archive /// independent of where the batcher cut. fn merge_batch( merged: &mut impl Iterator)>>, max_tiles: usize, ) -> Result)>> { let mut batch: Vec<(u64, Vec)> = Vec::new(); let mut cost: u64 = 0; for tile in merged.by_ref().take(max_tiles) { let (id, layers) = tile?; cost += tile_cost(&layers); batch.push((id, layers)); // Checked after pushing, so the batch is never empty and a heavy tile closes its own // batch -- the same shape as `partition_by_cost`'s grouping, for the same reason. if cost >= MERGE_BATCH_BYTES { break; } } Ok(batch) } /// Prune barren subtrees within one encoded batch: drop the four empty children of a /// tile whose whole child set came back `None`. /// /// A `None` child is a tile with nothing drawable — genuinely featureless, or full-bleed /// water background (Phase B). The reader's miss path already overzooms: a missing tile /// falls back to its parent, whose background (or whose own body) shows through. So four /// empty siblings carry no information their parent does not, and storing them buys index /// entries, leaf span and fetches for zero pixels. /// /// The conditions are deliberately strict, because a wrong prune deletes drawable map: /// /// * `z == 0` never prunes: the world tile has no parent to overzoom to. /// * All four children of a parent must be present **in this batch** and all `None`. /// A parent split across a batch boundary keeps its children — the archive must not /// depend on where the cost-batcher cut, and a partial set cannot prove barrenness. /// * Only `None` children prune. A stored child (even a tiny one) means drawable content. /// * The parent itself is untouched: it was merged and encoded in its own zoom pass (zooms /// tile independently), so pruning children never orphans a stored parent. /// /// Recursion across zooms falls out of the zoom loop: a z13 tile whose z14 children were /// all pruned is itself absent-or-water, so when z13 encodes, *its* parent sees four empty /// children and prunes again — the tree ends where the content does. /// /// Runs on the serial append thread over the encoded batch (not in the parallel encode /// workers): it inspects batch adjacency, which only the ordered batch has. Pure function /// of the batch's `(id, Option)` pairs, so thread count and chunk boundaries cannot move it. fn prune_barren_subtree(z: u8, done: &mut Vec) { if z == 0 || done.len() < 4 { return; } // Index by tile id for sibling lookup. The batch is ascending by id (merge order // through `encode_batch`'s positional collect), so positions are found by search // rather than assumed adjacent: siblings are consecutive ids but not necessarily // consecutive positions (a stored neighbour may sit between them — which itself // vetoes the prune, correctly). let mut drop_ids: std::collections::BTreeSet = std::collections::BTreeSet::new(); let mut at: std::collections::HashMap = std::collections::HashMap::new(); for (index, (id, _, _, _)) in done.iter().enumerate() { at.insert(*id, index); } for (index, (id, encoded, _, _)) in done.iter().enumerate() { let _ = index; if encoded.is_some() { continue; } let (tz, tx, ty) = tilecodec::pmtiles::tile_zxy(*id); if tz != z { continue; } // Only the top-left child starts the check, so each parent is considered once. if tx % 2 != 0 || ty % 2 != 0 { continue; } let (px, py) = (tx / 2, ty / 2); let mut siblings: Vec = Vec::with_capacity(4); for (dx, dy) in [(0u64, 0u64), (1, 0), (0, 1), (1, 1)] { siblings.push(tilecodec::pmtiles::tile_id(z, px * 2 + dx, py * 2 + dy)); } // All four present in this batch and all empty: the parent covers them. let all_empty = siblings.iter().all(|sib| { at.get(sib).is_some_and(|&i| done[i].1.is_none()) }); if all_empty { for sib in siblings { drop_ids.insert(sib); } } } if !drop_ids.is_empty() { done.retain(|(id, _, _, _)| !drop_ids.contains(id)); } } /// Cap on one merge pull's merged-geometry cost, in `tile_cost` units (features + coordinates). /// /// 8 M units is ~64 MB of merged tile geometry per batch at typical z14 density -- small against /// the box, large against the pool (still hundreds of tiles per batch on common zooms, so the /// encode pass stays fed). The failure this bounds held ~GB: `batch_len()` tiles at 64 threads /// is 4096 tiles, and a planet z14 batch of those carries dense-city tiles tens of MB each. const MERGE_BATCH_BYTES: u64 = 8 << 20; /// Which backend one zoom's tile-chunk spill stages in. /// /// The chunk spill holds clipped copies -- one record per (feature, tile) pair -- so its size /// scales with the store's feature count times the tiling fan-out, not with anything known /// exactly up front. The estimate is `features x 512 B`: a clipped copy carries the feature's /// packed body (tens of bytes) plus its share of parts/coords, and z14's fan-out dominates. /// Over-estimating files a zoom that would have fit anon; under-estimating pages it. Files are /// the safe side -- same chunks, removed on drop -- so the constant leans that way. /// /// Unknown limits (or a small store under 1 M features): the historical anon path, no behaviour /// change. fn plan_chunk_spill(store: &Store, scratch: &std::path::Path) -> osm_ingest::mem::SpillPlan { const CHUNK_BYTES_PER_FEATURE: u64 = 512; const SMALL_STORE_FEATURES: u64 = 1_000_000; if store.len() < SMALL_STORE_FEATURES { return osm_ingest::mem::SpillPlan::Anon; } // Reuse the anon-commit field for the chunk estimate: it is the number `decide` compares // against the commit allowance, and the chunk spill is the only anon charge this phase adds // (the feature spill is already staged and counted separately). let budget = osm_ingest::mem::StageBudget { ways_spill_bytes: store.len().saturating_mul(CHUNK_BYTES_PER_FEATURE), ..Default::default() }; match osm_ingest::mem::SpillPlan::decide(&budget, scratch, "tiler chunk spill") { Ok(plan) => { if plan != osm_ingest::mem::SpillPlan::Anon { eprintln!( " [tiler] chunk spill -> {} (file backend: commit budget)", scratch.display(), ); } plan } Err(e) => { // A zoom that fits neither backend is not a hard failure here: later zooms are // smaller, and each zoom re-creates the spill. Warn and take files -- the operator // sees the message and the build still has a chance. eprintln!("WARN: {e}; continuing with file staging"); osm_ingest::mem::SpillPlan::File } } }