Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / scripts / maps / mamaps_build / src / tiler_part3.rs

tiler_part3.rs426 lines · 21.4 KiBRaw
1/// K-way merge one zoom's chunks into ascending tiles, each carrying its layers in id order.
2///
3/// This is the reduce, and its ordering is the whole correctness argument. Keying the heap on
4/// `(tile, layer, chunk index)` makes the entries for one tile arrive layer-major and, within a
5/// layer, in **chunk order** — so appending them as they arrive lays a layer's features down in the
6/// order the store yielded them. That is not merely *a* deterministic order; it is the order the
7/// single-threaded tiler produced, which is why the archive did not move.
8///
9/// `chunks` is in read order and the index into it is the chunk index, exactly as when the chunks
10/// were `BTreeMap`s in memory. Disk is inserted *inside* one partition element, order-preservingly:
11/// a chunk's bytes are written in `BTreeMap::into_iter` order and read back in file order, so a
12/// [`ChunkReader`] yields the identical key sequence its map did. The heap, `front` and the
13/// `layers.last_mut()` adjacency shortcut below are untouched.
14///
15/// Streamed rather than merged into one map first, so a chunk's bytes are decoded as they are
16/// consumed instead of every chunk and a merged copy of it being live at once.
17fn merge<'a>(chunks: &[ChunkRef], spill: &'a ChunkSpill) -> Merged<'a> {
18 let window = tilespill::read_window_bytes(chunks.len());
19 let mut chunks: Vec<ChunkReader<'a>> =
20 chunks.iter().map(|at| spill.reader(at, window)).collect();
21 let mut front: Vec<Held> = Vec::with_capacity(chunks.len());
22 let mut next = BinaryHeap::with_capacity(chunks.len());
23 for (index, chunk) in chunks.iter_mut().enumerate() {
24 let head = chunk.next().transpose();
25 match &head {
26 // A stream that fails on its first read still has to enter the heap, or its error would
27 // be silently dropped and the archive would come out short.
28 Some(Ok(((tile, layer), _))) => next.push(Reverse((*tile, *layer, index))),
29 Some(Err(_)) => next.push(Reverse((0, 0, index))),
30 None => {}
31 }
32 front.push(head);
33 }
34 Merged { chunks, front, next }
35}
36
37/// One stream's held entry: `None` past the end of its chunk, `Err` when its bytes were not what
38/// the header claimed.
39type Held = Option<Result<((u64, u8), ChunkEntry)>>;
40
41/// A merge in progress: one held entry per chunk, and a heap over their keys. `Reverse`, because
42/// `BinaryHeap` is a max-heap and the writer wants ascending ids.
43struct Merged<'a> {
44 chunks: Vec<ChunkReader<'a>>,
45 front: Vec<Held>,
46 next: BinaryHeap<Reverse<(u64, u8, usize)>>,
47}
48
49impl Iterator for Merged<'_> {
50 /// Fallible, because a truncated scratch file must fail the build rather than quietly shorten
51 /// the archive.
52 type Item = Result<(u64, Vec<ChunkEntry>)>;
53
54 fn next(&mut self) -> Option<Result<(u64, Vec<ChunkEntry>)>> {
55 let Reverse((tile, _, _)) = *self.next.peek()?;
56 let mut layers: Vec<ChunkEntry> = Vec::new();
57 while let Some(&Reverse((at, layer_id, index))) = self.next.peek() {
58 if at != tile {
59 break;
60 }
61 self.next.pop();
62 let held = self.front[index].take().expect("a heap key without its entry");
63 let (_, mut layer) = match held {
64 Ok(entry) => entry,
65 Err(e) => return Some(Err(e)),
66 };
67 // Entries for one layer are adjacent, because the key sorts the layer before the chunk.
68 // So the accumulator only ever has to look at the layer it started last.
69 match layers.last_mut() {
70 Some(last) if last.layer.layer_id == layer_id => {
71 concatenate(last, &mut layer);
72 // `layer`'s arenas are drained now; hand them back so the next decode on this
73 // stream reuses them instead of allocating. Only the concatenated entries come
74 // back — the one that starts a layer escapes into `layers` and is encoded.
75 self.chunks[index].recycle(layer);
76 }
77 _ => layers.push(layer),
78 }
79 let head = self.chunks[index].next().transpose();
80 match &head {
81 Some(Ok(((tile, layer_id), _))) => self.next.push(Reverse((*tile, *layer_id, index))),
82 // Sorted first so the error surfaces on the next call rather than at the end of the
83 // zoom, and before anything else is appended.
84 Some(Err(_)) => self.next.push(Reverse((0, 0, index))),
85 None => {}
86 }
87 self.front[index] = head;
88 }
89 Some(Ok((tile, layers)))
90 }
91}
92
93/// Append one chunk's share of a layer onto another chunk's.
94///
95/// Rebased, not rebuilt: a `BodyLayer` is three parallel arenas and a feature addresses its parts by
96/// index, so concatenating them means shifting `parts_offset` by the parts already there and
97/// `coord_start` by the coordinates. The result is byte for byte what [`push`] would have produced
98/// had both chunks' features gone into one layer in this order, which is the claim the whole design
99/// rests on and what `concatenating_two_chunks_of_a_layer_is_one_layer` holds it to.
100///
101/// Names remap alongside: each chunk's `name_idx` addresses its own table, so every incoming
102/// feature's index is translated into the accumulator's (interning on first use, in merge order —
103/// which is chunk order, which is deterministic).
104fn concatenate(into: &mut ChunkEntry, from: &mut ChunkEntry) {
105 let parts_base = into.layer.parts.len() as u32;
106 let coords_base = into.layer.coords.len() as u32;
107 // Names remap first, while both tables are still borrowed shared: each incoming index is
108 // translated into the accumulator's (interning on first use, in merge order — which is chunk
109 // order, which is deterministic). Only then do the arenas move. A probe-only `HashMap` keyed on
110 // the accumulator's names turns what was a linear scan per incoming feature into a lookup, so a
111 // dense tile stops being quadratic in its name table; the table itself is still grown in
112 // first-use order, so the indices and bytes are byte for byte what a linear scan produced.
113 let remap = remap_names(&mut into.names, from);
114 // Drained rather than consumed by value: `from` is handed back to its reader afterwards so the
115 // next decode can reuse these arenas. `drain(..)` empties the source while keeping its capacity,
116 // which is exactly what a recycled buffer needs; the elements moved, and their order, are what
117 // `into_iter` would have yielded, so `into` is byte for byte the same layer.
118 into.layer.features.extend(from.layer.features.drain(..).zip(remap).map(
119 |(mut feature, name_idx)| {
120 feature.parts_offset += parts_base;
121 feature.name_idx = name_idx;
122 feature
123 },
124 ));
125 into.layer.parts.extend(from.layer.parts.drain(..).map(|mut part| {
126 part.coord_start += coords_base;
127 part
128 }));
129 into.layer.coords.extend_from_slice(&from.layer.coords);
130 // Ids are values, not indices into a table, so they concatenate with no remap. Appended in
131 // the same order the features were, which is what keeps the two parallel.
132 into.ids.extend_from_slice(&from.ids);
133 // The turn masks ride the same way: values parallel to features, concatenated in feature order.
134 into.turn_lanes.append(&mut from.turn_lanes);
135 // The building attrs ride the same way, dense-parallel to the buildings layer's features.
136 into.buildings.append(&mut from.buildings);
137 // And the carriageways, dense-parallel to the roads layer's.
138 into.carriageways.append(&mut from.carriageways);
139}
140
141/// Translate `from`'s feature name indices into `into_names`, growing it in first-use order.
142///
143/// A probe-only `HashMap` over the accumulator's table replaces the old linear `position` scan, so
144/// concatenating a dense tile is no longer quadratic in its name count. The map is never iterated:
145/// new names are appended to `into_names` in exactly the order they are first seen, so the resulting
146/// table — and every index into it — is byte for byte what a linear scan would have produced.
147fn remap_names(into_names: &mut Vec<String>, from: &ChunkEntry) -> Vec<u16> {
148 let mut new: Vec<&str> = Vec::new();
149 let remap: Vec<u16> = {
150 let mut index: HashMap<&str, u16> = HashMap::with_capacity(into_names.len());
151 for (i, name) in into_names.iter().enumerate() {
152 index.insert(name.as_str(), i as u16 + 1);
153 }
154 let base = into_names.len();
155 from.layer
156 .features
157 .iter()
158 .map(|feature| {
159 if feature.name_idx == tilecodec::mamaps::body::NAME_NONE {
160 tilecodec::mamaps::body::NAME_NONE
161 } else {
162 let name = from.names[feature.name_idx as usize - 1].as_str();
163 match index.get(name) {
164 Some(&at) => at,
165 None => {
166 let idx = (base + new.len()) as u16 + 1;
167 index.insert(name, idx);
168 new.push(name);
169 idx
170 }
171 }
172 }
173 })
174 .collect()
175 };
176 for name in new {
177 into_names.push(name.to_string());
178 }
179 remap
180}
181
182/// Stage C and body encoding for a batch of merged tiles, in parallel, results in tile order.
183///
184/// Both halves are pure functions of a single tile, which is the only reason this can fan out at
185/// all: [`crate::rings::normalise`] rewrites one layer's own arenas and nothing else, and
186/// [`tilecodec::mamaps::body::serialize`] only reads. `map(..).collect()` preserves the input's
187/// order — rayon's collect is positional, not completion-ordered — so the caller appends in
188/// ascending tile id with no sort of its own.
189///
190/// A tile whose layers all emptied out comes back as `None` rather than being dropped here, because
191/// its stage C counters still belong in the build report.
192#[allow(clippy::type_complexity)]
193/// Stage C, serialise and **compress** one batch of merged tiles, in parallel.
194///
195/// Compression belongs here rather than in the writer's append. DEFLATE at level nine is the single
196/// most expensive step per tile and the one least able to be stolen: left in `append_encoded` it ran
197/// on the appending thread, downstream of this whole parallel phase, and on a California z14 it was
198/// ~900 MB through one core while sixty-three sat idle. That is why a 64-thread build was *slower*
199/// than the sequential one it replaced.
200///
201/// returns the raw length alongside the compressed frame, because the per-zoom `bytes` column has
202/// always reported *uncompressed* body size and moving compression must not silently change what a
203/// build report means.
204///
205/// The most features any one tile has carried in each layer.
206///
207/// `body::serialize` caps a tile-layer at [`u16::MAX`] features, and that cap **has already fired**:
208/// `layer 4 has 79407 features` on north-america, fixed by [`crate::coalesce`]. Coalescing merges
209/// *lines* only -- polygons pass straight through -- and a planet build's dense cities are far past
210/// anything in a continent, so the question of whether the field has to widen to `u32` is a question
211/// about a number nobody has measured. This measures it.
212///
213/// Sampled **after** coalescing and stage C, which is where the count that actually reaches the cap
214/// is. Always on, unlike the timing counters: this is one `fetch_max` per layer per tile against a
215/// cache line that is almost never written after the first few thousand tiles, where those are three
216/// unconditional adds per tile.
217static WIDEST_LAYER: [AtomicU64; 256] = [const { AtomicU64::new(0) }; 256];
218
219/// The widest tile-layer seen per layer id, taken and reset.
220///
221/// Only the layers that appeared, so a build that carried three layers reports three rows.
222pub fn widest_layers() -> Vec<(u8, u64)> {
223 WIDEST_LAYER
224 .iter()
225 .enumerate()
226 .filter_map(|(id, seen)| match seen.swap(0, Ordering::Relaxed) {
227 0 => None,
228 n => Some((id as u8, n)),
229 })
230 .collect()
231}
232
233/// One encoded tile on its way back from [`encode_batch`]: its id, the compressed body with its raw
234/// length and its FNV-1a dedup hash, and what stage C and coalescing did to it.
235///
236/// The hash is computed in the encode worker (see [`encode_tile`]) so the serial append thread does
237/// not have to walk the whole body to derive the dedup key.
238///
239/// Folded by the caller in `tile_id` order rather than accumulated across workers, so the counters
240/// need no atomics and a million tiles do not contend on three cache lines.
241type Encoded = (u64, Option<(Vec<u8>, usize, u64)>, crate::rings::Stats, crate::coalesce::Stats);
242
243/// Parallel range merge: the same k-way merge as [`merge`], partitioned by tile id.
244///
245/// Serial `merge` is one heap over every chunk — at z14, ~27k streams and 240 M
246/// entries on one core. This splits the zoom's tile-id space into cost-balanced
247/// ranges; one worker k-way merges each range over the same chunks; a
248/// coordinator drains ranges in order into the unchanged downstream
249/// (`merge_batch` → encode → prune → append).
250///
251/// Byte-identity rests on three facts, each pinned by test:
252/// 1. Every tile belongs to exactly one range, and ranges drain ascending, so
253/// the yielded tile sequence is the serial one.
254/// 2. Within a range, chunks are consumed in global chunk order through the
255/// same heap discipline, so each tile's fragments concatenate identically.
256/// 3. Range boundaries never alter batch cuts: the coordinator yields the same
257/// sequence `merge_batch` would pull from the serial iterator, so batches —
258/// and therefore `prune_barren_subtree` — are unchanged.
259///
260/// Workers borrow the spill through `thread::scope` at the call site; nothing
261/// here is `'static`, and no chunk bytes are duplicated (each entry is decoded
262/// exactly once, by its range's worker). A corrupt spill fails the build with
263/// the lowest-indexed range's error — deterministic, matching serial's
264/// earliest-tile failure.
265const RANGE_BUCKETS: usize = 256;
266/// At or above this many tile-layer entries, the planning scan pays for
267/// itself; below it the serial [`merge`] runs (small zooms merge in
268/// milliseconds either way, and spawning buys nothing).
269const PARALLEL_MERGE_MIN_ENTRIES: u64 = 1_000_000;
270/// Worker cap. Workers claim ranges in order (see `plan_ranges_auto`), and each holds one cursor
271/// per chunk for its current range only, windowed to that chunk's share of the range, so live
272/// read buffers scale with the ranges in flight rather than with chunks x workers. Was 8 with
273/// one range per worker: the Nov 10 planet rerun spent 896 s in z12-z14 merges that way.
274const PARALLEL_MERGE_MAX_WORKERS: usize = 48;
275/// Output queue bound for the range being drained: backpressure without unbounded buffering.
276/// Counts tiles, handed over [`SEND_BATCH`] at a time; ranges further ahead are bounded by
277/// [`RANGE_AHEAD_BYTES`] instead.
278const RANGE_QUEUE_BOUND: usize = 4 * SEND_BATCH;
279
280/// Whether the range-parallel merge supports zoom `z`.
281///
282/// The bucket table inverts exactly only when the zoom's tile span divides by
283/// [`RANGE_BUCKETS`] (z4 and up: spans 256, 1024, …). On z0–z3 (spans 1–64)
284/// an edge lands mid-bucket, the inversion floors a bucket low, and the
285/// `remaining` difference undercounts the range's tail — which drops entries.
286/// Those zooms stay serial: they merge in milliseconds either way, so planning
287/// buys nothing there anyway. The caller gates on this; `plan_ranges` asserts
288/// it in debug.
289fn parallel_merge_supported(z: u8) -> bool {
290 use tilecodec::pmtiles::zoom_base;
291 (zoom_base(z + 1) - zoom_base(z)) % RANGE_BUCKETS as u64 == 0
292}
293
294/// Phase-A plan: cost-balanced tile ranges plus per-chunk seek positions.
295struct RangePlan {
296 /// Range starts in tile ids, ascending, length workers+1 (last is the
297 /// zoom's end sentinel, exclusive).
298 bounds: Vec<u64>,
299 /// Per-range merge cost (entry-cost units from the planning scan), for the
300 /// balance report. The coordinator drains ranges in order, so the slowest
301 /// range sets the merge wall; a range holding most of the cost means the
302 /// greedy cut failed and workers idle.
303 range_cost: Vec<u64>,
304 /// Hottest single tile and its cost: no range split can beat this tile,
305 /// so it is the structural floor under the merge wall. See `plan_ranges`.
306 hot_tile: u64,
307 hot_cost: u64,
308 /// Per chunk: file offset of the first entry at-or-after each range start
309 /// (chunk end when the range starts past the chunk).
310 offsets: Vec<Vec<u64>>,
311 /// Per chunk: entries remaining from each range start (0 when the range
312 /// starts past the chunk).
313 remaining: Vec<Vec<u64>>,
314 /// Per chunk: whether each range reaches the chunk's last byte (gates the
315 /// no-trailing-bytes check in `next`).
316 exact_end: Vec<Vec<bool>>,
317}
318
319/// Pass 1 of [`plan_ranges`]: the per-tile cost histogram, sorted by tile, plus per-chunk facts.
320struct Histogram {
321 /// `(tile, summed cost)`, ascending by tile, one row per tile that carries entries.
322 tiles: Vec<(u64, u64)>,
323 total: u64,
324 chunk_max: Vec<u64>,
325 chunk_total: Vec<u64>,
326 hot_tile: u64,
327 hot_cost: u64,
328 /// The spill's recorded tile runs, per chunk start offset (see `ChunkSpill::take_runs`).
329 runs: HashMap<(u64, u64), Vec<crate::tilespill::TileRun>>,
330}
331
332/// Skip-walk every chunk once, **in parallel** (chunks are independent; each is read with its own
333/// cursor), collecting per-tile cost runs; then sort-and-sum the runs into one ascending tile
334/// histogram. Sums are order-independent and the result is sorted by tile, so it is exactly the
335/// `HashMap` + sorted-key walk this replaced. The hottest single run is the first run (in chunk
336/// order, then position) of the largest cost, as the serial walk found it -- reporting only.
337fn histogram(chunks: &[ChunkRef], spill: &ChunkSpill) -> Result<Histogram> {
338 struct ChunkScan {
339 runs: Vec<(u64, u64)>,
340 max_tile: u64,
341 consumed: u64,
342 hot: (u64, u64),
343 }
344 // Chunks `write_chunk` indexed need no reading at all: their runs are the skip-walk's answer,
345 // recorded when the chunk was encoded (same tiles, same summed costs). Anything else is
346 // walked as before.
347 let indexed = spill.take_runs();
348 let scans: Vec<Result<ChunkScan>> = par::install(|| {
349 chunks
350 .par_iter()
351 .map(|chunk| -> Result<ChunkScan> {
352 if let Some(runs) = indexed.get(&(chunk.at, chunk.len)) {
353 let mut hot = (0u64, 0u64);
354 for r in runs {
355 if r.cost as u64 > hot.1 {
356 hot = (r.tile, r.cost as u64);
357 }
358 }
359 return Ok(ChunkScan {
360 runs: runs.iter().map(|r| (r.tile, r.cost as u64)).collect(),
361 max_tile: runs.last().map_or(0, |r| r.tile),
362 consumed: chunk.entries,
363 hot,
364 });
365 }
366 let mut reader = spill.reader(chunk, 64 << 10);
367 let mut runs = Vec::new();
368 let (mut consumed, mut max_tile) = (0u64, 0u64);
369 let (mut hot_tile, mut hot_cost) = (0u64, 0u64);
370 // Chunks store entries tile-major ((tile, layer) order), so a run of equal tile
371 // ids is the whole tile.
372 let (mut run_tile, mut run_cost) = (u64::MAX, 0u64);
373 let mut flush = |tile: u64, cost: u64, runs: &mut Vec<(u64, u64)>| {
374 runs.push((tile, cost));
375 if cost > hot_cost {
376 hot_tile = tile;
377 hot_cost = cost;
378 }
379 };
380 while let Some(((tile, _), cost)) = reader.skip_entry()? {
381 if tile != run_tile {
382 if run_tile != u64::MAX {
383 flush(run_tile, run_cost, &mut runs);
384 }
385 run_tile = tile;
386 run_cost = 0;
387 }
388 run_cost += cost;
389 consumed += 1;
390 max_tile = max_tile.max(tile);
391 }
392 if run_tile != u64::MAX {
393 flush(run_tile, run_cost, &mut runs);
394 }
395 Ok(ChunkScan { runs, max_tile, consumed, hot: (hot_tile, hot_cost) })
396 })
397 .collect()
398 });
399 let mut chunk_max = Vec::with_capacity(chunks.len());
400 let mut chunk_total = Vec::with_capacity(chunks.len());
401 let (mut hot_tile, mut hot_cost) = (0u64, 0u64);
402 let mut runs: Vec<(u64, u64)> = Vec::new();
403 for scan in scans {
404 let scan = scan?;
405 chunk_max.push(scan.max_tile);
406 chunk_total.push(scan.consumed);
407 if scan.hot.1 > hot_cost {
408 (hot_tile, hot_cost) = scan.hot;
409 }
410 runs.extend(scan.runs);
411 }
412 par::install(|| runs.par_sort_unstable_by_key(|r| r.0));
413 let mut tiles: Vec<(u64, u64)> = Vec::new();
414 for (tile, cost) in runs {
415 match tiles.last_mut() {
416 Some(last) if last.0 == tile => last.1 += cost,
417 _ => tiles.push((tile, cost)),
418 }
419 }
420 let total = tiles.iter().map(|t| t.1).sum();
421 Ok(Histogram { tiles, total, chunk_max, chunk_total, hot_tile, hot_cost, runs: indexed })
422}
423
424include!("tiler_part3_s1.rs");
425include!("tiler_part3_s2.rs");
426include!("tiler_part3_s3.rs");