/// K-way merge one zoom's chunks into ascending tiles, each carrying its layers in id order. /// /// This is the reduce, and its ordering is the whole correctness argument. Keying the heap on /// `(tile, layer, chunk index)` makes the entries for one tile arrive layer-major and, within a /// layer, in **chunk order** — so appending them as they arrive lays a layer's features down in the /// order the store yielded them. That is not merely *a* deterministic order; it is the order the /// single-threaded tiler produced, which is why the archive did not move. /// /// `chunks` is in read order and the index into it is the chunk index, exactly as when the chunks /// were `BTreeMap`s in memory. Disk is inserted *inside* one partition element, order-preservingly: /// a chunk's bytes are written in `BTreeMap::into_iter` order and read back in file order, so a /// [`ChunkReader`] yields the identical key sequence its map did. The heap, `front` and the /// `layers.last_mut()` adjacency shortcut below are untouched. /// /// Streamed rather than merged into one map first, so a chunk's bytes are decoded as they are /// consumed instead of every chunk and a merged copy of it being live at once. fn merge<'a>(chunks: &[ChunkRef], spill: &'a ChunkSpill) -> Merged<'a> { let window = tilespill::read_window_bytes(chunks.len()); let mut chunks: Vec> = chunks.iter().map(|at| spill.reader(at, window)).collect(); let mut front: Vec = Vec::with_capacity(chunks.len()); let mut next = BinaryHeap::with_capacity(chunks.len()); for (index, chunk) in chunks.iter_mut().enumerate() { let head = chunk.next().transpose(); match &head { // A stream that fails on its first read still has to enter the heap, or its error would // be silently dropped and the archive would come out short. Some(Ok(((tile, layer), _))) => next.push(Reverse((*tile, *layer, index))), Some(Err(_)) => next.push(Reverse((0, 0, index))), None => {} } front.push(head); } Merged { chunks, front, next } } /// One stream's held entry: `None` past the end of its chunk, `Err` when its bytes were not what /// the header claimed. type Held = Option>; /// A merge in progress: one held entry per chunk, and a heap over their keys. `Reverse`, because /// `BinaryHeap` is a max-heap and the writer wants ascending ids. struct Merged<'a> { chunks: Vec>, front: Vec, next: BinaryHeap>, } impl Iterator for Merged<'_> { /// Fallible, because a truncated scratch file must fail the build rather than quietly shorten /// the archive. type Item = Result<(u64, Vec)>; fn next(&mut self) -> Option)>> { let Reverse((tile, _, _)) = *self.next.peek()?; let mut layers: Vec = Vec::new(); while let Some(&Reverse((at, layer_id, index))) = self.next.peek() { if at != tile { break; } self.next.pop(); let held = self.front[index].take().expect("a heap key without its entry"); let (_, mut layer) = match held { Ok(entry) => entry, Err(e) => return Some(Err(e)), }; // Entries for one layer are adjacent, because the key sorts the layer before the chunk. // So the accumulator only ever has to look at the layer it started last. match layers.last_mut() { Some(last) if last.layer.layer_id == layer_id => { concatenate(last, &mut layer); // `layer`'s arenas are drained now; hand them back so the next decode on this // stream reuses them instead of allocating. Only the concatenated entries come // back — the one that starts a layer escapes into `layers` and is encoded. self.chunks[index].recycle(layer); } _ => layers.push(layer), } let head = self.chunks[index].next().transpose(); match &head { Some(Ok(((tile, layer_id), _))) => self.next.push(Reverse((*tile, *layer_id, index))), // Sorted first so the error surfaces on the next call rather than at the end of the // zoom, and before anything else is appended. Some(Err(_)) => self.next.push(Reverse((0, 0, index))), None => {} } self.front[index] = head; } Some(Ok((tile, layers))) } } /// Append one chunk's share of a layer onto another chunk's. /// /// Rebased, not rebuilt: a `BodyLayer` is three parallel arenas and a feature addresses its parts by /// index, so concatenating them means shifting `parts_offset` by the parts already there and /// `coord_start` by the coordinates. The result is byte for byte what [`push`] would have produced /// had both chunks' features gone into one layer in this order, which is the claim the whole design /// rests on and what `concatenating_two_chunks_of_a_layer_is_one_layer` holds it to. /// /// Names remap alongside: each chunk's `name_idx` addresses its own table, so every incoming /// feature's index is translated into the accumulator's (interning on first use, in merge order — /// which is chunk order, which is deterministic). fn concatenate(into: &mut ChunkEntry, from: &mut ChunkEntry) { let parts_base = into.layer.parts.len() as u32; let coords_base = into.layer.coords.len() as u32; // Names remap first, while both tables are still borrowed shared: each incoming index is // translated into the accumulator's (interning on first use, in merge order — which is chunk // order, which is deterministic). Only then do the arenas move. A probe-only `HashMap` keyed on // the accumulator's names turns what was a linear scan per incoming feature into a lookup, so a // dense tile stops being quadratic in its name table; the table itself is still grown in // first-use order, so the indices and bytes are byte for byte what a linear scan produced. let remap = remap_names(&mut into.names, from); // Drained rather than consumed by value: `from` is handed back to its reader afterwards so the // next decode can reuse these arenas. `drain(..)` empties the source while keeping its capacity, // which is exactly what a recycled buffer needs; the elements moved, and their order, are what // `into_iter` would have yielded, so `into` is byte for byte the same layer. into.layer.features.extend(from.layer.features.drain(..).zip(remap).map( |(mut feature, name_idx)| { feature.parts_offset += parts_base; feature.name_idx = name_idx; feature }, )); into.layer.parts.extend(from.layer.parts.drain(..).map(|mut part| { part.coord_start += coords_base; part })); into.layer.coords.extend_from_slice(&from.layer.coords); // Ids are values, not indices into a table, so they concatenate with no remap. Appended in // the same order the features were, which is what keeps the two parallel. into.ids.extend_from_slice(&from.ids); // The turn masks ride the same way: values parallel to features, concatenated in feature order. into.turn_lanes.append(&mut from.turn_lanes); // The building attrs ride the same way, dense-parallel to the buildings layer's features. into.buildings.append(&mut from.buildings); // And the carriageways, dense-parallel to the roads layer's. into.carriageways.append(&mut from.carriageways); } /// Translate `from`'s feature name indices into `into_names`, growing it in first-use order. /// /// A probe-only `HashMap` over the accumulator's table replaces the old linear `position` scan, so /// concatenating a dense tile is no longer quadratic in its name count. The map is never iterated: /// new names are appended to `into_names` in exactly the order they are first seen, so the resulting /// table — and every index into it — is byte for byte what a linear scan would have produced. fn remap_names(into_names: &mut Vec, from: &ChunkEntry) -> Vec { let mut new: Vec<&str> = Vec::new(); let remap: Vec = { let mut index: HashMap<&str, u16> = HashMap::with_capacity(into_names.len()); for (i, name) in into_names.iter().enumerate() { index.insert(name.as_str(), i as u16 + 1); } let base = into_names.len(); from.layer .features .iter() .map(|feature| { if feature.name_idx == tilecodec::mamaps::body::NAME_NONE { tilecodec::mamaps::body::NAME_NONE } else { let name = from.names[feature.name_idx as usize - 1].as_str(); match index.get(name) { Some(&at) => at, None => { let idx = (base + new.len()) as u16 + 1; index.insert(name, idx); new.push(name); idx } } } }) .collect() }; for name in new { into_names.push(name.to_string()); } remap } /// Stage C and body encoding for a batch of merged tiles, in parallel, results in tile order. /// /// Both halves are pure functions of a single tile, which is the only reason this can fan out at /// all: [`crate::rings::normalise`] rewrites one layer's own arenas and nothing else, and /// [`tilecodec::mamaps::body::serialize`] only reads. `map(..).collect()` preserves the input's /// order — rayon's collect is positional, not completion-ordered — so the caller appends in /// ascending tile id with no sort of its own. /// /// A tile whose layers all emptied out comes back as `None` rather than being dropped here, because /// its stage C counters still belong in the build report. #[allow(clippy::type_complexity)] /// Stage C, serialise and **compress** one batch of merged tiles, in parallel. /// /// Compression belongs here rather than in the writer's append. DEFLATE at level nine is the single /// most expensive step per tile and the one least able to be stolen: left in `append_encoded` it ran /// on the appending thread, downstream of this whole parallel phase, and on a California z14 it was /// ~900 MB through one core while sixty-three sat idle. That is why a 64-thread build was *slower* /// than the sequential one it replaced. /// /// returns the raw length alongside the compressed frame, because the per-zoom `bytes` column has /// always reported *uncompressed* body size and moving compression must not silently change what a /// build report means. /// /// The most features any one tile has carried in each layer. /// /// `body::serialize` caps a tile-layer at [`u16::MAX`] features, and that cap **has already fired**: /// `layer 4 has 79407 features` on north-america, fixed by [`crate::coalesce`]. Coalescing merges /// *lines* only -- polygons pass straight through -- and a planet build's dense cities are far past /// anything in a continent, so the question of whether the field has to widen to `u32` is a question /// about a number nobody has measured. This measures it. /// /// Sampled **after** coalescing and stage C, which is where the count that actually reaches the cap /// is. Always on, unlike the timing counters: this is one `fetch_max` per layer per tile against a /// cache line that is almost never written after the first few thousand tiles, where those are three /// unconditional adds per tile. static WIDEST_LAYER: [AtomicU64; 256] = [const { AtomicU64::new(0) }; 256]; /// The widest tile-layer seen per layer id, taken and reset. /// /// Only the layers that appeared, so a build that carried three layers reports three rows. pub fn widest_layers() -> Vec<(u8, u64)> { WIDEST_LAYER .iter() .enumerate() .filter_map(|(id, seen)| match seen.swap(0, Ordering::Relaxed) { 0 => None, n => Some((id as u8, n)), }) .collect() } /// One encoded tile on its way back from [`encode_batch`]: its id, the compressed body with its raw /// length and its FNV-1a dedup hash, and what stage C and coalescing did to it. /// /// The hash is computed in the encode worker (see [`encode_tile`]) so the serial append thread does /// not have to walk the whole body to derive the dedup key. /// /// Folded by the caller in `tile_id` order rather than accumulated across workers, so the counters /// need no atomics and a million tiles do not contend on three cache lines. type Encoded = (u64, Option<(Vec, usize, u64)>, crate::rings::Stats, crate::coalesce::Stats); /// Parallel range merge: the same k-way merge as [`merge`], partitioned by tile id. /// /// Serial `merge` is one heap over every chunk — at z14, ~27k streams and 240 M /// entries on one core. This splits the zoom's tile-id space into cost-balanced /// ranges; one worker k-way merges each range over the same chunks; a /// coordinator drains ranges in order into the unchanged downstream /// (`merge_batch` → encode → prune → append). /// /// Byte-identity rests on three facts, each pinned by test: /// 1. Every tile belongs to exactly one range, and ranges drain ascending, so /// the yielded tile sequence is the serial one. /// 2. Within a range, chunks are consumed in global chunk order through the /// same heap discipline, so each tile's fragments concatenate identically. /// 3. Range boundaries never alter batch cuts: the coordinator yields the same /// sequence `merge_batch` would pull from the serial iterator, so batches — /// and therefore `prune_barren_subtree` — are unchanged. /// /// Workers borrow the spill through `thread::scope` at the call site; nothing /// here is `'static`, and no chunk bytes are duplicated (each entry is decoded /// exactly once, by its range's worker). A corrupt spill fails the build with /// the lowest-indexed range's error — deterministic, matching serial's /// earliest-tile failure. const RANGE_BUCKETS: usize = 256; /// At or above this many tile-layer entries, the planning scan pays for /// itself; below it the serial [`merge`] runs (small zooms merge in /// milliseconds either way, and spawning buys nothing). const PARALLEL_MERGE_MIN_ENTRIES: u64 = 1_000_000; /// Worker cap. Workers claim ranges in order (see `plan_ranges_auto`), and each holds one cursor /// per chunk for its current range only, windowed to that chunk's share of the range, so live /// read buffers scale with the ranges in flight rather than with chunks x workers. Was 8 with /// one range per worker: the Nov 10 planet rerun spent 896 s in z12-z14 merges that way. const PARALLEL_MERGE_MAX_WORKERS: usize = 48; /// Output queue bound for the range being drained: backpressure without unbounded buffering. /// Counts tiles, handed over [`SEND_BATCH`] at a time; ranges further ahead are bounded by /// [`RANGE_AHEAD_BYTES`] instead. const RANGE_QUEUE_BOUND: usize = 4 * SEND_BATCH; /// Whether the range-parallel merge supports zoom `z`. /// /// The bucket table inverts exactly only when the zoom's tile span divides by /// [`RANGE_BUCKETS`] (z4 and up: spans 256, 1024, …). On z0–z3 (spans 1–64) /// an edge lands mid-bucket, the inversion floors a bucket low, and the /// `remaining` difference undercounts the range's tail — which drops entries. /// Those zooms stay serial: they merge in milliseconds either way, so planning /// buys nothing there anyway. The caller gates on this; `plan_ranges` asserts /// it in debug. fn parallel_merge_supported(z: u8) -> bool { use tilecodec::pmtiles::zoom_base; (zoom_base(z + 1) - zoom_base(z)) % RANGE_BUCKETS as u64 == 0 } /// Phase-A plan: cost-balanced tile ranges plus per-chunk seek positions. struct RangePlan { /// Range starts in tile ids, ascending, length workers+1 (last is the /// zoom's end sentinel, exclusive). bounds: Vec, /// Per-range merge cost (entry-cost units from the planning scan), for the /// balance report. The coordinator drains ranges in order, so the slowest /// range sets the merge wall; a range holding most of the cost means the /// greedy cut failed and workers idle. range_cost: Vec, /// Hottest single tile and its cost: no range split can beat this tile, /// so it is the structural floor under the merge wall. See `plan_ranges`. hot_tile: u64, hot_cost: u64, /// Per chunk: file offset of the first entry at-or-after each range start /// (chunk end when the range starts past the chunk). offsets: Vec>, /// Per chunk: entries remaining from each range start (0 when the range /// starts past the chunk). remaining: Vec>, /// Per chunk: whether each range reaches the chunk's last byte (gates the /// no-trailing-bytes check in `next`). exact_end: Vec>, } /// Pass 1 of [`plan_ranges`]: the per-tile cost histogram, sorted by tile, plus per-chunk facts. struct Histogram { /// `(tile, summed cost)`, ascending by tile, one row per tile that carries entries. tiles: Vec<(u64, u64)>, total: u64, chunk_max: Vec, chunk_total: Vec, 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>, } /// Skip-walk every chunk once, **in parallel** (chunks are independent; each is read with its own /// cursor), collecting per-tile cost runs; then sort-and-sum the runs into one ascending tile /// histogram. Sums are order-independent and the result is sorted by tile, so it is exactly the /// `HashMap` + sorted-key walk this replaced. The hottest single run is the first run (in chunk /// order, then position) of the largest cost, as the serial walk found it -- reporting only. fn histogram(chunks: &[ChunkRef], spill: &ChunkSpill) -> Result { struct ChunkScan { runs: Vec<(u64, u64)>, max_tile: u64, 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> = par::install(|| { chunks .par_iter() .map(|chunk| -> Result { 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); let (mut hot_tile, mut hot_cost) = (0u64, 0u64); // Chunks store entries tile-major ((tile, layer) order), so a run of equal tile // ids is the whole tile. let (mut run_tile, mut run_cost) = (u64::MAX, 0u64); let mut flush = |tile: u64, cost: u64, runs: &mut Vec<(u64, u64)>| { runs.push((tile, cost)); if cost > hot_cost { hot_tile = tile; hot_cost = cost; } }; while let Some(((tile, _), cost)) = reader.skip_entry()? { if tile != run_tile { if run_tile != u64::MAX { flush(run_tile, run_cost, &mut runs); } run_tile = tile; run_cost = 0; } run_cost += cost; consumed += 1; max_tile = max_tile.max(tile); } if run_tile != u64::MAX { flush(run_tile, run_cost, &mut runs); } Ok(ChunkScan { runs, max_tile, consumed, hot: (hot_tile, hot_cost) }) }) .collect() }); let mut chunk_max = Vec::with_capacity(chunks.len()); let mut chunk_total = Vec::with_capacity(chunks.len()); let (mut hot_tile, mut hot_cost) = (0u64, 0u64); let mut runs: Vec<(u64, u64)> = Vec::new(); for scan in scans { let scan = scan?; chunk_max.push(scan.max_tile); chunk_total.push(scan.consumed); if scan.hot.1 > hot_cost { (hot_tile, hot_cost) = scan.hot; } runs.extend(scan.runs); } par::install(|| runs.par_sort_unstable_by_key(|r| r.0)); let mut tiles: Vec<(u64, u64)> = Vec::new(); for (tile, cost) in runs { match tiles.last_mut() { Some(last) if last.0 == tile => last.1 += cost, _ => tiles.push((tile, cost)), } } let total = tiles.iter().map(|t| t.1).sum(); Ok(Histogram { tiles, total, chunk_max, chunk_total, hot_tile, hot_cost, runs: indexed }) } include!("tiler_part3_s1.rs"); include!("tiler_part3_s2.rs"); include!("tiler_part3_s3.rs");