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

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

tiler_part3.rs969 lines · 44.8 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.extend(from.turn_lanes.drain(..));
135 // The building attrs ride the same way, dense-parallel to the buildings layer's features.
136 into.buildings.extend(from.buildings.drain(..));
137 // And the carriageways, dense-parallel to the roads layer's.
138 into.carriageways.extend(from.carriageways.drain(..));
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: each worker holds one cursor per chunk, so live readers scale
271/// as chunks × workers. More workers also duplicate more skip-walk; 8 is the
272/// shape until a bigger box says otherwise.
273const PARALLEL_MERGE_MAX_WORKERS: usize = 8;
274/// Per-worker output queue bound: backpressure without unbounded buffering.
275/// Tiles vary wildly in cost (city vs ocean), so this counts entries, not
276/// bytes; the coordinator drains continuously, so queues only ever hold a
277/// scheduling bubble, not a range.
278const RANGE_QUEUE_BOUND: usize = 32;
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/// Cost-balanced range boundaries over one zoom's tile space, with seek
320/// positions.
321///
322/// Two serial skip-walks over every chunk — header parses and length walks
323/// only, no allocation, no UTF-8, no struct builds, roughly a tenth of a full
324/// decode each. Pass 1 accumulates per-tile cost into a histogram and cuts
325/// tile-granular ranges from it; pass 2 records each chunk's cursor at every
326/// range bound, so seeks are exact and ranges never overlap.
327///
328/// Exactness is load-bearing, not decorative: the spill's `check_books` gate
329/// requires every entry decoded exactly once, so a range that re-reads
330/// another's entries fails the build. An earlier revision sought
331/// bucket-granular cursors with a skip loop absorbing the difference — the
332/// loop walked entries the neighbouring range also walked, the books showed
333/// ~196 KB read past written on a California z14, and the build rightly
334/// refused. Two walks cost one extra scan; overlapping seeks cost the build.
335///
336/// Cuts are tile-granular because bucket edges proved too coarse: z14's cost
337/// concentrates inside single buckets (one bucket held 97% of a California
338/// z14), so no bucket-edge cut could balance and seven of eight workers
339/// idled. The sorted key walk (never the map's own order) is what keeps the
340/// cuts independent of hashing.
341fn plan_ranges(
342 chunks: &[ChunkRef],
343 spill: &ChunkSpill,
344 z: u8,
345 workers: usize,
346) -> Result<RangePlan> {
347 use tilecodec::pmtiles::zoom_base;
348 debug_assert!(
349 parallel_merge_supported(z),
350 "plan_ranges needs an exact span/256 split (z4+); z{z} must stay serial"
351 );
352 let base = zoom_base(z);
353 // Pass 1: per-tile cost across all chunks, plus per-chunk max tile.
354 // A HashMap, not a Vec over the span: z14's span is 268 M tiles but only
355 // ~7.5 M carry entries, so the dense form would be ~2 GB of mostly
356 // zeroes. Never iterated — cuts traverse a sorted key vec, so the map's
357 // own order (and its hasher) is unobservable in the output.
358 let mut tile_cost: HashMap<u64, u64> = HashMap::new();
359 let mut chunk_max: Vec<u64> = Vec::with_capacity(chunks.len());
360 let mut chunk_total: Vec<u64> = Vec::with_capacity(chunks.len());
361 // Hottest single tile and its cost, across all chunks: the merge assigns
362 // whole tiles to one range worker (a tile's layers concatenate in chunk
363 // order), so no range split can beat this tile. Reported alongside the
364 // per-range costs — when it approaches the largest range, the ceiling is
365 // structural, not a balancer bug.
366 let mut hot_tile = 0u64;
367 let mut hot_cost = 0u64;
368 for chunk in chunks {
369 let mut reader = spill.reader(chunk, 8192);
370 let mut consumed = 0u64;
371 let mut max_tile = 0u64;
372 // Current tile's accumulated cost, flushed when the tile id changes:
373 // chunks store entries tile-major ((tile, layer) order), so a run of
374 // equal tile ids is the whole tile.
375 let mut run_tile = u64::MAX;
376 let mut run_cost = 0u64;
377 loop {
378 let Some(((tile, _), cost)) = reader.skip_entry()? else {
379 break;
380 };
381 if tile != run_tile {
382 if run_tile != u64::MAX {
383 *tile_cost.entry(run_tile).or_insert(0) += run_cost;
384 if run_cost > hot_cost {
385 hot_tile = run_tile;
386 hot_cost = run_cost;
387 }
388 }
389 run_tile = tile;
390 run_cost = 0;
391 }
392 run_cost += cost;
393 consumed += 1;
394 max_tile = max_tile.max(tile);
395 }
396 // Flush the trailing tile run — the loop only flushes on a tile
397 // change, so the chunk's last tile would otherwise never count.
398 if run_tile != u64::MAX {
399 *tile_cost.entry(run_tile).or_insert(0) += run_cost;
400 if run_cost > hot_cost {
401 hot_tile = run_tile;
402 hot_cost = run_cost;
403 }
404 }
405 chunk_max.push(max_tile);
406 chunk_total.push(consumed);
407 }
408 // Greedy cost balance over TILES, not buckets: cut when crossing each
409 // multiple of total/workers, with the cut falling between the tiles that
410 // straddle the mark. Fixed rule on scanned data — deterministic across
411 // runs and machines. Tile-granular because bucket edges proved too coarse:
412 // cost concentrates inside single buckets, and only tile steps can split
413 // that mass. The sorted key walk (never the map's own order) is what keeps
414 // the cuts independent of hashing.
415 let total: u64 = tile_cost.values().sum();
416 let mut tiles: Vec<u64> = tile_cost.keys().copied().collect();
417 tiles.sort_unstable();
418 let mut bounds = vec![base];
419 let mut acc = 0u64;
420 let mut cuts = 1usize;
421 for tile in &tiles {
422 // Commit the cut BEFORE adding this tile's cost when the mark was
423 // already reached: the cut then falls between the previous tile and
424 // this one, and this tile opens the next range. Cutting after would
425 // hand the straddling tile's whole cost to the range that already
426 // crossed its mark — which is how one range ends up owning nearly the
427 // whole zoom.
428 while cuts < workers && acc * workers as u64 >= total * cuts as u64 {
429 let edge = *tile;
430 if edge > *bounds.last().expect("bounds") {
431 bounds.push(edge);
432 }
433 cuts += 1;
434 }
435 acc += tile_cost[tile];
436 }
437 // The trailing range owns through the last tile: no cut is committed
438 // after the loop (the zoom end sentinel below closes it). A mark crossed
439 // only by the final tile still leaves that tile in the last range rather
440 // than stranding it past every cut.
441 bounds.push(zoom_base(z + 1));
442 bounds.dedup();
443 // Padding: fewer distinct cut positions than workers (tiny zoom, or one
444 // tile holding everything). Pad with the zoom end — never with a tile
445 // strictly inside the span, which would hand two ranges the same tile.
446 while bounds.len() < workers + 1 {
447 bounds.push(zoom_base(z + 1));
448 }
449 // Per-range cost from the same tile histogram the cuts came from: exact,
450 // not bucket-approximated. Reported by the caller (one line per zoom on
451 // the parallel path).
452 let range_cost = {
453 let mut costs = Vec::with_capacity(workers);
454 for r in 0..workers {
455 // Binary search: tiles are sorted, bounds ascending.
456 let lo = tiles.partition_point(|&t| t < bounds[r]);
457 let hi = tiles.partition_point(|&t| t < bounds[r + 1]);
458 costs.push(tiles[lo..hi].iter().map(|t| tile_cost[t]).sum());
459 }
460 costs
461 };
462 // Pass 2: each chunk's cursor at every range bound. Bounds ascend and the
463 // walk is tile-ordered, so one pointer walks the bounds while the entries
464 // stream past: bound `r` records the cursor (and consumed count) of the
465 // first entry with tile >= bounds[r] — exactly the first entry the range
466 // can own. No bucket machinery: the cursor IS the range start, so the
467 // pre-bound skip loop is a provable no-op and `remaining` is the exact
468 // owned-entry difference. Ranges partition tiles, so seeks partition
469 // entries: nothing is read twice, and the books balance by construction.
470 let mut offsets = Vec::with_capacity(chunks.len());
471 let mut remaining = Vec::with_capacity(chunks.len());
472 let mut exact_end = Vec::with_capacity(chunks.len());
473 for (ci, chunk) in chunks.iter().enumerate() {
474 let mut reader = spill.reader(chunk, 8192);
475 // Bound cursors in walk order: bound 0 is always `base` (every entry
476 // qualifies), so it records the chunk start with nothing consumed.
477 let mut at_bound = 0usize;
478 let mut bound_off = vec![0u64; workers + 1];
479 let mut bound_con = vec![0u64; workers + 1];
480 bound_off[0] = chunk.at;
481 let mut consumed = 0u64;
482 loop {
483 let off = reader.position();
484 let Some(((tile, _), _)) = reader.skip_entry()? else {
485 break;
486 };
487 // Record every bound this entry is the first at-or-after: bounds
488 // ascend, entries ascend, so one forward pointer suffices and gap
489 // bounds (past this tile but unmet by later ones) are filled by
490 // the chunk-end fill below.
491 while at_bound < workers && tile >= bounds[at_bound] {
492 bound_off[at_bound] = off;
493 bound_con[at_bound] = consumed;
494 at_bound += 1;
495 }
496 consumed += 1;
497 }
498 // Bounds past the chunk's last tile (or past every tile, for a chunk
499 // entirely below the bound): chunk end, everything consumed. The
500 // range then seeks to chunk end with nothing remaining — it owns
501 // nothing here.
502 while at_bound <= workers {
503 bound_off[at_bound] = chunk.at + chunk.len;
504 bound_con[at_bound] = consumed;
505 at_bound += 1;
506 }
507 debug_assert_eq!(
508 consumed, chunk_total[ci],
509 "the two planning walks must agree on chunk {ci}'s entry count"
510 );
511 let mut orow = Vec::with_capacity(workers);
512 let mut rrow = Vec::with_capacity(workers);
513 let mut erow = Vec::with_capacity(workers);
514 for r in 0..workers {
515 orow.push(bound_off[r]);
516 // Owned entries: everything from this bound to the next. Exact —
517 // no prefix, no tail — because the cursors are the bounds.
518 rrow.push(bound_con[r + 1].saturating_sub(bound_con[r]));
519 // Exact end iff the chunk's max tile sits inside this range.
520 erow.push(chunk_max[ci] < bounds[r + 1] && chunk_max[ci] >= bounds[r]);
521 }
522 offsets.push(orow);
523 remaining.push(rrow);
524 exact_end.push(erow);
525 }
526 Ok(RangePlan { bounds, range_cost, hot_tile, hot_cost, offsets, remaining, exact_end })
527}
528
529/// One range worker's output: tiles in ascending order, or the first error.
530///
531/// The error carries its range index so the coordinator reports the
532/// lowest-indexed failure — deterministic, matching serial's earliest-tile
533/// failure. Workers exit when their range is drained or the coordinator drops
534/// the receiver (abort on an earlier range's failure): a failed `send` ends
535/// the worker rather than blocking it forever.
536type RangeOut = Result<(u64, Vec<ChunkEntry>)>;
537
538/// Merge one tile range over all chunks, streaming results in order.
539///
540/// Same heap discipline as [`Merged`]: chunks consumed in global chunk order,
541/// entries for one tile arriving layer-major, concatenated as they arrive. A
542/// range is exactly the serial merge restricted to its tile span, so its
543/// output is the serial output's subsequence — concatenating ranges in order
544/// reproduces the serial tile sequence byte for byte.
545///
546/// `end_tile` bounds the range (exclusive); entries at-or-after it stay
547/// unread for the next range. Chunks not touching the range are skipped
548/// without opening a reader.
549fn merge_range(
550 chunks: &[ChunkRef],
551 spill: &ChunkSpill,
552 plan: &RangePlan,
553 range: usize,
554 end_tile: u64,
555 out: &std::sync::mpsc::SyncSender<RangeOut>,
556) {
557 use std::cmp::Reverse;
558 use std::collections::BinaryHeap;
559 // Padded trailing ranges ([zoom end, zoom end)) own nothing: yield
560 // nothing rather than decoding bucket 255 a second time.
561 if plan.bounds[range] >= end_tile {
562 return;
563 }
564 let window = crate::tilespill::read_window_bytes(chunks.len());
565 let start_tile = plan.bounds[range];
566 let mut readers: Vec<Option<ChunkReader<'_>>> = Vec::with_capacity(chunks.len());
567 for (ci, chunk) in chunks.iter().enumerate() {
568 let remaining = plan.remaining[ci][range];
569 if remaining == 0 {
570 readers.push(None);
571 continue;
572 }
573 let mut reader = spill.reader(chunk, window);
574 reader.seek_to(plan.offsets[ci][range], remaining, plan.exact_end[ci][range]);
575 // Bucket edges are coarser than range bounds: advance past entries
576 // below the bound (skip-walked, uncounted, `left` adjusted by the
577 // skips themselves so it still exhausts exactly at range end). A
578 // corrupt entry reports through the channel like a decode error.
579 loop {
580 let below = match reader.peek_tile() {
581 Ok(Some(t)) => t < start_tile,
582 Ok(None) => false,
583 Err(e) => {
584 let _ = out.send(Err(e));
585 readers.push(None);
586 continue;
587 }
588 };
589 if !below {
590 break;
591 }
592 match reader.skip_entry() {
593 Ok(Some(_)) => {}
594 Ok(None) => break,
595 Err(e) => {
596 let _ = out.send(Err(e));
597 readers.push(None);
598 continue;
599 }
600 }
601 }
602 readers.push(Some(reader));
603 }
604 let mut heap: BinaryHeap<Reverse<(u64, u8, usize)>> = BinaryHeap::new();
605 let mut front: Vec<Held> = Vec::with_capacity(chunks.len());
606 for (index, reader) in readers.iter_mut().enumerate() {
607 let head = match reader {
608 Some(r) => r.next().transpose(),
609 None => None,
610 };
611 match &head {
612 Some(Ok(((tile, layer), _))) => heap.push(Reverse((*tile, *layer, index))),
613 Some(Err(_)) => heap.push(Reverse((0, 0, index))),
614 None => {}
615 }
616 front.push(head);
617 }
618 // Mirrors `Merged::next`: the heap top names the tile, the inner loop
619 // drains it, entries concatenate layer-major in chunk order.
620 while let Some(&Reverse((tile, _, _))) = heap.peek() {
621 if tile >= end_tile {
622 break;
623 }
624 let mut layers: Vec<ChunkEntry> = Vec::new();
625 while let Some(&Reverse((at, layer_id, index))) = heap.peek() {
626 if at != tile {
627 break;
628 }
629 heap.pop();
630 let held = front[index].take().expect("a heap key without its entry");
631 let (_, mut layer) = match held {
632 Ok(entry) => entry,
633 Err(e) => {
634 let _ = out.send(Err(e));
635 return;
636 }
637 };
638 match layers.last_mut() {
639 Some(last) if last.layer.layer_id == layer_id => {
640 concatenate(last, &mut layer);
641 if let Some(r) = readers[index].as_mut() {
642 r.recycle(layer);
643 }
644 }
645 _ => layers.push(layer),
646 }
647 let head = match &mut readers[index] {
648 Some(r) => r.next().transpose(),
649 None => None,
650 };
651 match &head {
652 Some(Ok(((t, l), _))) => heap.push(Reverse((*t, *l, index))),
653 Some(Err(_)) => heap.push(Reverse((0, 0, index))),
654 None => {}
655 }
656 front[index] = head;
657 }
658 if out.send(Ok((tile, layers))).is_err() {
659 return;
660 }
661 }
662}
663
664/// Range-worker entry point for `thread::scope` spawning: merges range `r`
665/// and streams it, converting panics-by-Result into channel values.
666///
667/// Never returns `Err` itself (there is nowhere for it to go — the
668/// coordinator owns failure reporting): fallible setup is unreachable here
669/// because planning already validated every seek position, so the body is
670/// infallible by construction and any `Err` produced mid-merge travels as a
671/// value.
672fn merge_range_into(
673 chunks: &[ChunkRef],
674 spill: &ChunkSpill,
675 plan: &RangePlan,
676 r: usize,
677 tx: std::sync::mpsc::SyncSender<RangeOut>,
678) {
679 let end_tile = plan.bounds[r + 1];
680 merge_range(chunks, spill, plan, r, end_tile, &tx);
681}
682
683/// Ordered coordinator over range workers: an iterator yielding the serial
684/// tile sequence.
685///
686/// Ranges drain strictly in order (range 0 to exhaustion, then range 1, ...),
687/// so the yielded sequence is tile-ascending regardless of completion order.
688/// A range's error aborts the drain with the lowest-indexed failure: ranges
689/// before it drained cleanly, so it is the earliest tile-ordered failure —
690/// deterministic, like serial.
691struct ParallelMerge {
692 receivers: Vec<std::sync::mpsc::Receiver<RangeOut>>,
693 at: usize,
694 failed: Option<tilecodec::proto::Error>,
695}
696
697impl ParallelMerge {
698 fn new(receivers: Vec<std::sync::mpsc::Receiver<RangeOut>>) -> ParallelMerge {
699 ParallelMerge { receivers, at: 0, failed: None }
700 }
701}
702
703impl Iterator for ParallelMerge {
704 type Item = Result<(u64, Vec<ChunkEntry>)>;
705
706 fn next(&mut self) -> Option<Result<(u64, Vec<ChunkEntry>)>> {
707 loop {
708 if self.at >= self.receivers.len() {
709 return None;
710 }
711 if let Some(e) = self.failed.take() {
712 // Drain nothing further: receivers drop here, workers exit on
713 // send failure, scope joins them. Lowest-indexed failure wins
714 // because lower ranges already drained clean.
715 self.at = self.receivers.len();
716 self.receivers.clear();
717 return Some(Err(e));
718 }
719 match self.receivers[self.at].recv() {
720 Ok(Ok(tile)) => return Some(Ok(tile)),
721 Ok(Err(e)) => {
722 self.failed = Some(e);
723 }
724 Err(_) => {
725 // Sender dropped = range drained cleanly. Advance.
726 self.at += 1;
727 }
728 }
729 }
730 }
731}
732
733/// Merge one zoom's chunks with `workers` range workers, or serially when the
734/// zoom is too small to repay planning.
735///
736/// Returns the tile sequence as an iterator (serial [`Merged`] or parallel
737/// coordinator — both yield `(tile, layers)` ascending), plus a flag the
738/// caller uses only for reporting. Errors surface identically either way.
739enum MergeStream<'a> {
740 Serial(Merged<'a>),
741 Parallel(ParallelMerge),
742}
743
744impl Iterator for MergeStream<'_> {
745 type Item = Result<(u64, Vec<ChunkEntry>)>;
746
747 fn next(&mut self) -> Option<Result<(u64, Vec<ChunkEntry>)>> {
748 match self {
749 MergeStream::Serial(m) => m.next(),
750 MergeStream::Parallel(m) => m.next(),
751 }
752 }
753}
754
755#[cfg(test)]
756mod tests_parallel {
757 use super::*;
758 use crate::tiler::tests::*;
759 use crate::tilespill::{ChunkRef, ChunkSpill};
760
761 /// Drive a merge iterator to a vec, failing the test on the first error
762 /// rather than publishing a short sequence.
763 fn collect<I>(merged: &mut I) -> Vec<(u64, Vec<ChunkEntry>)>
764 where
765 I: Iterator<Item = Result<(u64, Vec<ChunkEntry>)>>,
766 {
767 merged
768 .by_ref()
769 .collect::<Result<Vec<_>>>()
770 .expect("merge the chunks")
771 }
772
773 /// Map a fixture into spill chunks at `z`, returning refs plus the spill.
774 /// The spill outlives the refs: callers keep both alive together. Forces
775 /// small vertex chunks so the fixture spans several chunks even at test
776 /// scale (a single-chunk merge exercises nothing).
777 fn map_chunks(
778 features: &[crate::extract::Feature],
779 z: u8,
780 ) -> (Vec<ChunkRef>, ChunkSpill) {
781 let _guard = budget();
782 crate::tiler::set_chunk_vertices(64);
783 let store = spilled(features);
784 let spill = ChunkSpill::create(scratch()).expect("spill");
785 let tolerance = tile_build::simplify::tolerance_for(z, crate::DEFAULT_MAX_ZOOM, 1.0);
786 let buffer = tile_build::geom::buffer_for(crate::tiler::EXTENT);
787 let settings = settings(0, 14);
788 let _ = &settings;
789 let (chunks, _) =
790 crate::tiler::map_zoom(&store, &settings, z, tolerance, buffer, &spill)
791 .expect("map the fixture");
792 crate::tiler::set_chunk_vertices(0);
793 (chunks, spill)
794 }
795
796 /// The gate this work stands on: range-parallel output is the serial
797 /// output, tile for tile, layer for layer, byte for byte — over a
798 /// multi-chunk fixture with lakes, buildings and cross-tile rivers, at a
799 /// zoom where the wash gate fires (z14) and one where it does not (z10).
800 /// Both zooms are above z3, where the bucket table inverts exactly (see
801 /// `parallel_merge_supported`) — the identity below rests on that.
802 #[test]
803 fn parallel_merge_is_the_serial_merge() {
804 for z in [10u8, 14] {
805 let (chunks, spill) = map_chunks(&a_crowd(), z);
806 assert!(chunks.len() > 1, "the fixture must span chunks at z{z}");
807 let mut serial = super::merge(&chunks, &spill);
808 let want = collect(&mut serial);
809 assert!(!want.is_empty(), "the fixture must yield tiles at z{z}");
810 for workers in [2usize, 3, 7] {
811 let plan =
812 super::plan_ranges(&chunks, &spill, z, workers).expect("plan the ranges");
813 let got = std::thread::scope(|s| {
814 let mut receivers = Vec::with_capacity(workers);
815 let chunks_ref = &chunks;
816 let spill_ref = &spill;
817 let plan_ref = &plan;
818 for r in 0..workers {
819 let (tx, rx) = std::sync::mpsc::sync_channel(super::RANGE_QUEUE_BOUND);
820 receivers.push(rx);
821 s.spawn(move || {
822 super::merge_range_into(chunks_ref, spill_ref, plan_ref, r, tx);
823 });
824 }
825 let mut coord = super::ParallelMerge::new(receivers);
826 collect(&mut coord)
827 });
828 assert_eq!(got, want, "worker count {workers} moved z{z}");
829 }
830 }
831 }
832
833 /// Ranges that hold nothing yield nothing: a single-tile fixture merged
834 /// under more workers than tiles still produces exactly that tile.
835 /// (A pool, not a lake: wash areas never reach z14 tiles under the cap.)
836 #[test]
837 fn empty_ranges_yield_nothing() {
838 let pool = crate::extract::Feature {
839 class: crate::schema::Class::area(
840 tilecodec::mamaps::dict::LAYER_LANDTYPE,
841 crate::schema::kind("swimming_pool"),
842 14,
843 ),
844 geometry: crate::tiler::tests::square(-122.0, 37.0, 0.005),
845 name: None,
846 id: tilecodec::mamaps::body::ID_NONE,
847 transit_color: 0,
848 transit_ordinal: 0,
849 transit_lanes: 0,
850 transit_taper: 0,
851 lane_count: 0,
852 turn_fwd: Vec::new(),
853 turn_bwd: Vec::new(),
854 building: None,
855 carriageway: tilecodec::mamaps::body::Carriageway::default(),
856 };
857 let (chunks, spill) = map_chunks(&[pool], 14);
858 let mut serial = super::merge(&chunks, &spill);
859 let want = collect(&mut serial);
860 assert!(!want.is_empty());
861 let workers = 4usize;
862 let plan = super::plan_ranges(&chunks, &spill, 14, workers).expect("plan");
863 let got = std::thread::scope(|s| {
864 let mut receivers = Vec::with_capacity(workers);
865 let chunks_ref = &chunks;
866 let spill_ref = &spill;
867 let plan_ref = &plan;
868 for r in 0..workers {
869 let (tx, rx) = std::sync::mpsc::sync_channel(super::RANGE_QUEUE_BOUND);
870 receivers.push(rx);
871 s.spawn(move || {
872 super::merge_range_into(chunks_ref, spill_ref, plan_ref, r, tx);
873 });
874 }
875 let mut coord = super::ParallelMerge::new(receivers);
876 collect(&mut coord)
877 });
878 assert_eq!(got, want, "empty ranges must not add or drop tiles");
879 }
880
881 /// The seek/count half of the plan, pinned directly: per-chunk
882 /// `remaining` summed over chunks must cover the range's tile-layer
883 /// entries — every (tile, layer) pair the range owns must be walked, no
884 /// fewer. The serial merge yields each tile with its layers; counting
885 /// layer entries per tile over the serial output gives the per-tile
886 /// histogram, and each range's share must be covered by the plan's rows.
887 ///
888 /// Coverage, not equality: the plan counts from the containing bucket's
889 /// cursor, so it INCLUDES the below-bound prefix the skip loop walks AND
890 /// the mid-bucket tail past the end bound that the `end_tile` stop
891 /// discards. Planned >= wanted always; planned < wanted means a starved
892 /// reader — the failure this test exists to catch.
893 #[test]
894 fn plan_seek_counts_match_the_tile_histogram() {
895 for z in [10u8, 14] {
896 let (chunks, spill) = map_chunks(&a_crowd(), z);
897 assert!(chunks.len() > 1, "the fixture must span chunks at z{z}");
898 // Per-tile LAYER-entry counts from the serial output: one per
899 // (tile, layer) pair, which is the unit the spill — and the
900 // reader's `left` budget — counts in.
901 let mut serial = super::merge(&chunks, &spill);
902 let mut tile_entries: HashMap<u64, u64> = HashMap::new();
903 for (tile, layers) in collect(&mut serial) {
904 *tile_entries.entry(tile).or_insert(0) += layers.len() as u64;
905 }
906 for workers in [2usize, 3, 7] {
907 let plan =
908 super::plan_ranges(&chunks, &spill, z, workers).expect("plan the ranges");
909 // Bounds ascend and partition the zoom: first is the base,
910 // last is the end sentinel, workers+1 entries.
911 assert_eq!(plan.bounds.len(), workers + 1, "z{z} w{workers}");
912 for w in plan.bounds.windows(2) {
913 assert!(w[0] <= w[1], "bounds ascend at z{z} w{workers}");
914 }
915 for r in 0..workers {
916 // Entries the plan says range r walks, summed over chunks.
917 let planned: u64 =
918 plan.remaining.iter().map(|row| row[r]).sum();
919 // Layer entries the histogram puts inside the range.
920 let want: u64 = tile_entries
921 .iter()
922 .filter(|(&t, _)| t >= plan.bounds[r] && t < plan.bounds[r + 1])
923 .map(|(_, &n)| n)
924 .sum();
925 assert!(
926 planned >= want,
927 "z{z} w{workers} range {r}: plan walks {planned}, histogram holds {want}"
928 );
929 }
930 }
931 }
932 }
933
934 /// z0–z3 stay serial: their spans (1–64 tiles) don't divide the 256 cost
935 /// buckets, so range edges can't invert exactly. The zoom loop gates on
936 /// this — if the gate ever lets a low zoom through, planning must refuse.
937 #[test]
938 fn low_zooms_stay_serial() {
939 for z in [0u8, 1, 2, 3] {
940 assert!(!super::parallel_merge_supported(z), "z{z} must stay serial");
941 }
942 for z in [4u8, 10, 14] {
943 assert!(super::parallel_merge_supported(z), "z{z} must parallelise");
944 }
945 }
946
947 /// The full-archive version of the merge gate: the zoom loop's own
948 /// selection (`merge_gate` → plan/workers vs serial) agrees with itself
949 /// across thread counts. The unit tests above drive the planner and
950 /// workers directly; this drives `build()` end to end — so a miswired
951 /// gate can't hide behind correct components. One thread takes the
952 /// serial path (single worker cap... no: `merge_workers > 1` fails, so
953 /// serial), four threads take the range workers wherever the zoom is big
954 /// enough; both must produce the same archive.
955 #[test]
956 fn gate_paths_agree_through_build() {
957 use crate::tiler::tests::{budget, release_threads};
958 let _guard = budget();
959 crate::tiler::set_chunk_vertices(64);
960 let store = spilled(&a_crowd());
961 tile_build::par::set_threads(1);
962 let serial = crate::tiler::build(&store, &settings(0, 14)).expect("one thread").0;
963 tile_build::par::set_threads(4);
964 let parallel = crate::tiler::build(&store, &settings(0, 14)).expect("four threads").0;
965 crate::tiler::set_chunk_vertices(0);
966 release_threads();
967 assert_eq!(parallel, serial, "thread count moved the archive");
968 }
969}