maps: plan merge ranges from tile runs recorded at write (#perf)
- Commit
82ee6774dd0bc1241aaf203233fdbe16bd833847- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-11 05:36 UTC (25 days ago)
- Parents
5d314e8
What: ChunkSpill::write_chunk records each chunk's tile runs (tile, summed cost, offset in the chunk, entries before) from the map it is already encoding, and the merge planner (histogram + per-bound seek positions) reads those instead of skip-walking every chunk back off the spill. The tile-chunk scratch file is also created NOCOW. Why: merge-plan was 78 s of the Nov 10 planet build (z13 25 s, z14 47 s): two passes reading every tile chunk of the zoom from disk to learn what write_chunk had in hand when it wrote them. Two bugs found on the way, both fixed here: - An empty tile chunk (a map chunk whose features all clipped away; US West z14 has them) starts where the next chunk starts, so a run list keyed on the offset alone could be handed to the wrong chunk. The index is keyed (offset, length) and never indexes an empty chunk. Test empty_chunks_do_not_borrow_their_neighbours_runs fails on the offset-only key. - merge_range's skip-to-range-start loop handled a reader error with a bare `continue`, which re-ran that loop on the same failed reader forever, queueing an error and a reader slot per turn: a corrupt seek became unbounded memory (200 GB on US West) instead of a failed build. It now moves on to the next chunk (labelled continue). Test a_failing_range_reader_reports_and_stops corrupts a seek on purpose; on the old code it runs until its memory cap. Byte-identity: the recorded runs are the skip-walk's answers (same tiles, same costs, same first-entry offsets and counts). A chunk whose run fields would not fit u32 (never in practice) is not indexed and is walked as before. New test planning_from_recorded_runs_equals_walking_the_chunks compares the two plans field by field at z10/z14 and 2/5/13 ranges; the existing range-merge tests still pass. TileRun is 24 bytes so a planet z14 index stays ~1-2 GB. Measured: CA merge-plan 0.4 s -> under 0.1 s; US West 0.8-1.2 s -> 0.1 s.
Diff
scripts/maps/mamaps_build/src/tiler_part3.rs
diff --git a/scripts/maps/mamaps_build/src/tiler_part3.rs b/scripts/maps/mamaps_build/src/tiler_part3.rsindex 3c9c70ed7c..652066449a 100644--- a/scripts/maps/mamaps_build/src/tiler_part3.rs+++ b/scripts/maps/mamaps_build/src/tiler_part3.rs@@ -325,6 +325,8 @@ struct Histogram { chunk_total: Vec<u64>, hot_tile: u64, hot_cost: u64,+ /// The spill's recorded tile runs, per chunk start offset (see `ChunkSpill::take_runs`).+ runs: HashMap<(u64, u64), Vec<crate::tilespill::TileRun>>, } /// Skip-walk every chunk once, **in parallel** (chunks are independent; each is read with its own@@ -339,10 +341,28 @@ fn histogram(chunks: &[ChunkRef], spill: &ChunkSpill) -> Result<Histogram> { consumed: u64, hot: (u64, u64), }+ // Chunks `write_chunk` indexed need no reading at all: their runs are the skip-walk's answer,+ // recorded when the chunk was encoded (same tiles, same summed costs). Anything else is+ // walked as before.+ let indexed = spill.take_runs(); let scans: Vec<Result<ChunkScan>> = par::install(|| { chunks .par_iter() .map(|chunk| -> Result<ChunkScan> {+ if let Some(runs) = indexed.get(&(chunk.at, chunk.len)) {+ let mut hot = (0u64, 0u64);+ for r in runs {+ if r.cost as u64 > hot.1 {+ hot = (r.tile, r.cost as u64);+ }+ }+ return Ok(ChunkScan {+ runs: runs.iter().map(|r| (r.tile, r.cost as u64)).collect(),+ max_tile: runs.last().map_or(0, |r| r.tile),+ consumed: chunk.entries,+ hot,+ });+ } let mut reader = spill.reader(chunk, 64 << 10); let mut runs = Vec::new(); let (mut consumed, mut max_tile) = (0u64, 0u64);@@ -398,7 +418,7 @@ fn histogram(chunks: &[ChunkRef], spill: &ChunkSpill) -> Result<Histogram> { } } let total = tiles.iter().map(|t| t.1).sum();- Ok(Histogram { tiles, total, chunk_max, chunk_total, hot_tile, hot_cost })+ Ok(Histogram { tiles, total, chunk_max, chunk_total, hot_tile, hot_cost, runs: indexed }) } /// Cost-balanced range boundaries over one zoom's tile space, with seek positions, for exactly@@ -472,7 +492,7 @@ fn plan_ranges_from( "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 } = hist;+ 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@@ -525,12 +545,28 @@ fn plan_ranges_from( .par_iter() .enumerate() .map(|(ci, chunk)| -> Result<(Vec<u64>, Vec<u64>, Vec<bool>)> {- let mut reader = spill.reader(chunk, 64 << 10); 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 {@@ -619,7 +655,7 @@ fn merge_range( let ranges = plan.bounds.len() - 1; let start_tile = plan.bounds[range]; let mut readers: Vec<Option<ChunkReader<'_>>> = Vec::with_capacity(chunks.len());- for (ci, chunk) in chunks.iter().enumerate() {+ 'chunks: for (ci, chunk) in chunks.iter().enumerate() { let remaining = plan.remaining[ci][range]; if remaining == 0 { readers.push(None);@@ -642,9 +678,12 @@ fn merge_range( 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;+ continue 'chunks; } }; if !below {@@ -654,9 +693,12 @@ fn merge_range( 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;+ continue 'chunks; } } }@@ -1090,6 +1132,105 @@ mod tests_parallel { } } + /// 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.)
scripts/maps/mamaps_build/src/tilespill.rs
diff --git a/scripts/maps/mamaps_build/src/tilespill.rs b/scripts/maps/mamaps_build/src/tilespill.rsindex ac70b8f41a..e0ab8b0dc8 100644--- a/scripts/maps/mamaps_build/src/tilespill.rs+++ b/scripts/maps/mamaps_build/src/tilespill.rs@@ -191,6 +191,27 @@ pub struct ChunkSpill { written_entries: AtomicU64, read: AtomicU64, read_entries: AtomicU64,+ /// Per written chunk (keyed by its start offset and length -- an empty chunk shares its start+ /// with the next one): its tile runs, recorded by `write_chunk` from+ /// the map it encoded. What the merge planner reads instead of skip-walking every chunk back+ /// off disk (twice per zoom: 78 s of the Nov 10 planet build, z14 alone 47 s).+ runs: Mutex<Vec<((u64, u64), Vec<TileRun>)>>,+}++/// One tile's entries within one chunk, as `write_chunk` laid them down. Narrow on purpose: a+/// planet z14 records tens of millions of these, so offsets are relative to the chunk and counts+/// are `u32` (a chunk is a few MB); a chunk that would overflow one is simply not indexed and the+/// planner walks it.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct TileRun {+ pub tile: u64,+ /// Summed merge cost (features + coordinates) of the run's entries: what+ /// [`ChunkReader::skip_entry`] reports for each.+ pub cost: u32,+ /// Offset of the run's first entry from the chunk's start.+ pub rel_offset: u32,+ /// Entries in the chunk before this run.+ pub before: u32, } impl ChunkSpill {@@ -208,6 +229,9 @@ impl ChunkSpill { .truncate(true) .open(&path) .map_err(|e| Error(format!("cannot create {}: {e}", path.display())))?;+ // Uncompressed on a `compress-force` btrfs: every zoom's clipped geometry passes through+ // here (hundreds of GB over a planet build), written once, read back by the merge.+ osm_ingest::mem::mark_scratch_uncompressed(&file); Ok(ChunkSpill { file: Some(file), anon: None,@@ -218,6 +242,7 @@ impl ChunkSpill { written_entries: AtomicU64::new(0), read: AtomicU64::new(0), read_entries: AtomicU64::new(0),+ runs: Mutex::new(Vec::new()), }) } @@ -246,6 +271,7 @@ impl ChunkSpill { written_entries: AtomicU64::new(0), read: AtomicU64::new(0), read_entries: AtomicU64::new(0),+ runs: Mutex::new(Vec::new()), }), osm_ingest::mem::SpillPlan::File => Self::create(path), }@@ -275,7 +301,29 @@ impl ChunkSpill { pub fn write_chunk(&self, map: BTreeMap<(u64, u8), ChunkEntry>) -> Result<ChunkRef> { let entries = map.len() as u64; let mut len = 0u64;- for ((_, layer_id), entry) in &map {+ // The chunk's tile runs, offsets relative to the chunk start. `None` once a field would+ // not fit its `u32` (never in practice), which leaves the chunk unindexed.+ let mut runs: Option<Vec<TileRun>> = Some(Vec::new());+ for (n, ((tile, layer_id), entry)) in map.iter().enumerate() {+ let cost = entry.layer.features.len() as u64 + entry.layer.coords.len() as u64;+ if let Some(list) = runs.as_mut() {+ let fits = |v: u64| u32::try_from(v).ok();+ let ok = match list.last_mut() {+ Some(run) if run.tile == *tile => {+ fits(run.cost as u64 + cost).map(|c| run.cost = c).is_some()+ }+ _ => match (fits(cost), fits(len), fits(n as u64)) {+ (Some(cost), Some(rel_offset), Some(before)) => {+ list.push(TileRun { tile: *tile, cost, rel_offset, before });+ true+ }+ _ => false,+ },+ };+ if !ok {+ runs = None;+ }+ } if *layer_id != entry.layer.layer_id { // The merge keys its heap on the map key and reads `layer_id` off the layer it // yields, so the two disagreeing would mean the round trip had to preserve both. It@@ -317,6 +365,14 @@ impl ChunkSpill { } self.written.fetch_add(len, Ordering::Relaxed); self.written_entries.fetch_add(entries, Ordering::Relaxed);+ drop(_commit);+ // An empty chunk is never indexed: it has nothing to plan, and its start is the next+ // chunk's start, so a run list keyed on the offset alone could be handed to the wrong one+ // (which is what sent US West's z14 merge reading past chunk ends). The key carries the+ // length too, so even a zero-length key cannot meet a real chunk's.+ if let (Some(runs), true) = (runs, entries > 0) {+ self.runs.lock().expect("the tile chunk spill's run index").push(((at, len), runs));+ } Ok(ChunkRef { at, len, entries }) } @@ -344,6 +400,15 @@ impl ChunkSpill { Ok(n) } + /// The tile runs `write_chunk` recorded for every chunk, keyed by chunk start offset. Empty+ /// for a chunk written some other way (tests building chunks by hand), which the planner+ /// answers by skip-walking that chunk as it always did.+ pub fn take_runs(&self) -> std::collections::HashMap<(u64, u64), Vec<TileRun>> {+ std::mem::take(&mut *self.runs.lock().expect("the tile chunk spill's run index"))+ .into_iter()+ .collect()+ }+ /// A forward cursor over one chunk, buffering `window` bytes at a time. pub fn reader(&self, chunk: &ChunkRef, window: usize) -> ChunkReader<'_> { ChunkReader {