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

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

tiler_part3_s1.rs408 lines · 18.2 KiBRaw
1/// Cost-balanced range boundaries over one zoom's tile space, with seek positions, for exactly
2/// `workers` ranges. See [`plan_ranges_from`].
3#[cfg(test)]
4fn plan_ranges(
5 chunks: &[ChunkRef],
6 spill: &ChunkSpill,
7 z: u8,
8 workers: usize,
9) -> Result<RangePlan> {
10 let hist = histogram(chunks, spill)?;
11 plan_ranges_from(chunks, spill, z, workers, hist)
12}
13
14/// Merged-tile bytes per planning cost unit (features + coordinates), for sizing ranges against
15/// [`RANGE_AHEAD_BYTES`]: coordinates dominate at 8 bytes each. An estimate; never observable.
16const BYTES_PER_COST: u64 = 12;
17/// Most ranges one zoom is cut into. Bounds the plan's per-chunk seek tables
18/// (`chunks x ranges` rows).
19const MAX_MERGE_RANGES: usize = 4096;
20
21/// [`plan_ranges`] with the range count chosen from the zoom's own size: enough ranges that
22/// `merge_workers` of them in flight fit the run-ahead allowance about twice over, so the merge
23/// keeps every worker busy rather than parking all but the one being drained. Never fewer than
24/// `merge_workers`. The count is a scheduling choice: ranges concatenate to the serial sequence
25/// however many there are.
26fn plan_ranges_auto(
27 chunks: &[ChunkRef],
28 spill: &ChunkSpill,
29 z: u8,
30 merge_workers: usize,
31) -> Result<RangePlan> {
32 let hist = histogram(chunks, spill)?;
33 let per_range = (RANGE_AHEAD_BYTES / (2 * merge_workers.max(1) as u64)).max(1);
34 let wanted = (hist.total.saturating_mul(BYTES_PER_COST)).div_ceil(per_range) as usize;
35 let ranges = wanted.clamp(merge_workers.max(1), MAX_MERGE_RANGES);
36 plan_ranges_from(chunks, spill, z, ranges, hist)
37}
38
39/// Cost-balanced range boundaries over one zoom's tile space, with seek
40/// positions.
41///
42/// Two skip-walks over every chunk — header parses and length walks only, no allocation, no
43/// UTF-8, no struct builds, roughly a tenth of a full decode each — both run across the pool,
44/// one chunk per task (they were serial: 231 s of the Nov 10 planet build). Pass 1 ([`histogram`])
45/// accumulates per-tile cost and cuts tile-granular ranges from it; pass 2 records each chunk's
46/// cursor at every range bound, so seeks are exact and ranges never overlap.
47///
48/// Exactness is load-bearing, not decorative: the spill's `check_books` gate
49/// requires every entry decoded exactly once, so a range that re-reads
50/// another's entries fails the build. An earlier revision sought
51/// bucket-granular cursors with a skip loop absorbing the difference — the
52/// loop walked entries the neighbouring range also walked, the books showed
53/// ~196 KB read past written on a California z14, and the build rightly
54/// refused. Two walks cost one extra scan; overlapping seeks cost the build.
55///
56/// Cuts are tile-granular because bucket edges proved too coarse: z14's cost
57/// concentrates inside single buckets (one bucket held 97% of a California
58/// z14), so no bucket-edge cut could balance and seven of eight workers
59/// idled.
60fn plan_ranges_from(
61 chunks: &[ChunkRef],
62 spill: &ChunkSpill,
63 z: u8,
64 workers: usize,
65 hist: Histogram,
66) -> Result<RangePlan> {
67 use tilecodec::pmtiles::zoom_base;
68 debug_assert!(
69 parallel_merge_supported(z),
70 "plan_ranges needs an exact span/256 split (z4+); z{z} must stay serial"
71 );
72 let base = zoom_base(z);
73 let Histogram { tiles, total, chunk_max, chunk_total, hot_tile, hot_cost, runs } = hist;
74 // Greedy cost balance over TILES, not buckets: cut when crossing each
75 // multiple of total/workers, with the cut falling between the tiles that
76 // straddle the mark. Fixed rule on scanned data — deterministic across
77 // runs and machines.
78 let mut bounds = vec![base];
79 let mut acc = 0u64;
80 let mut cuts = 1usize;
81 for &(tile, cost) in &tiles {
82 // Commit the cut BEFORE adding this tile's cost when the mark was
83 // already reached: the cut then falls between the previous tile and
84 // this one, and this tile opens the next range. Cutting after would
85 // hand the straddling tile's whole cost to the range that already
86 // crossed its mark — which is how one range ends up owning nearly the
87 // whole zoom.
88 while cuts < workers && acc as u128 * workers as u128 >= total as u128 * cuts as u128 {
89 if tile > *bounds.last().expect("bounds") {
90 bounds.push(tile);
91 }
92 cuts += 1;
93 }
94 acc += cost;
95 }
96 // The trailing range owns through the last tile: no cut is committed
97 // after the loop (the zoom end sentinel below closes it).
98 bounds.push(zoom_base(z + 1));
99 bounds.dedup();
100 // Padding: fewer distinct cut positions than workers (tiny zoom, or one
101 // tile holding everything). Pad with the zoom end — never with a tile
102 // strictly inside the span, which would hand two ranges the same tile.
103 while bounds.len() < workers + 1 {
104 bounds.push(zoom_base(z + 1));
105 }
106 // Per-range cost from the same tile histogram the cuts came from.
107 let range_cost: Vec<u64> = (0..workers)
108 .map(|r| {
109 let lo = tiles.partition_point(|t| t.0 < bounds[r]);
110 let hi = tiles.partition_point(|t| t.0 < bounds[r + 1]);
111 tiles[lo..hi].iter().map(|t| t.1).sum()
112 })
113 .collect();
114 drop(tiles);
115 // Pass 2: each chunk's cursor at every range bound, one chunk per task. Bounds ascend and the
116 // walk is tile-ordered, so one pointer walks the bounds while the entries stream past: bound
117 // `r` records the cursor (and consumed count) of the first entry with tile >= bounds[r] —
118 // exactly the first entry the range can own. Ranges partition tiles, so seeks partition
119 // entries: nothing is read twice, and the books balance by construction.
120 #[allow(clippy::type_complexity)]
121 let rows: Vec<Result<(Vec<u64>, Vec<u64>, Vec<bool>)>> = par::install(|| {
122 chunks
123 .par_iter()
124 .enumerate()
125 .map(|(ci, chunk)| -> Result<(Vec<u64>, Vec<u64>, Vec<bool>)> {
126 let mut at_bound = 0usize;
127 let mut bound_off = vec![0u64; workers + 1];
128 let mut bound_con = vec![0u64; workers + 1];
129 bound_off[0] = chunk.at;
130 let mut consumed = 0u64;
131 if let Some(chunk_runs) = runs.get(&(chunk.at, chunk.len)) {
132 // From the recorded runs: the first entry at-or-after a bound is the first
133 // entry of the first run whose tile reaches it -- the same cursor and count
134 // the walk below arrives at, without reading the chunk.
135 for run in chunk_runs {
136 while at_bound < workers && run.tile >= bounds[at_bound] {
137 bound_off[at_bound] = chunk.at + run.rel_offset as u64;
138 bound_con[at_bound] = run.before as u64;
139 at_bound += 1;
140 }
141 }
142 consumed = chunk.entries;
143 }
144 let mut reader = spill.reader(chunk, 64 << 10);
145 if runs.contains_key(&(chunk.at, chunk.len)) {
146 reader.seek_to(chunk.at + chunk.len, 0, false);
147 }
148 loop {
149 let off = reader.position();
150 let Some(((tile, _), _)) = reader.skip_entry()? else {
151 break;
152 };
153 while at_bound < workers && tile >= bounds[at_bound] {
154 bound_off[at_bound] = off;
155 bound_con[at_bound] = consumed;
156 at_bound += 1;
157 }
158 consumed += 1;
159 }
160 // Bounds past the chunk's last tile: chunk end, everything consumed. The range
161 // then seeks to chunk end with nothing remaining — it owns nothing here.
162 while at_bound <= workers {
163 bound_off[at_bound] = chunk.at + chunk.len;
164 bound_con[at_bound] = consumed;
165 at_bound += 1;
166 }
167 debug_assert_eq!(
168 consumed, chunk_total[ci],
169 "the two planning walks must agree on chunk {ci}'s entry count"
170 );
171 let mut orow = Vec::with_capacity(workers);
172 let mut rrow = Vec::with_capacity(workers);
173 let mut erow = Vec::with_capacity(workers);
174 for r in 0..workers {
175 orow.push(bound_off[r]);
176 // Owned entries: everything from this bound to the next.
177 rrow.push(bound_con[r + 1].saturating_sub(bound_con[r]));
178 // Exact end iff the chunk's max tile sits inside this range.
179 erow.push(chunk_max[ci] < bounds[r + 1] && chunk_max[ci] >= bounds[r]);
180 }
181 Ok((orow, rrow, erow))
182 })
183 .collect()
184 });
185 let mut offsets = Vec::with_capacity(chunks.len());
186 let mut remaining = Vec::with_capacity(chunks.len());
187 let mut exact_end = Vec::with_capacity(chunks.len());
188 for row in rows {
189 let (o, r, e) = row?;
190 offsets.push(o);
191 remaining.push(r);
192 exact_end.push(e);
193 }
194 Ok(RangePlan { bounds, range_cost, hot_tile, hot_cost, offsets, remaining, exact_end })
195}
196
197/// One range worker's output: tiles in ascending order, or the first error.
198///
199/// The error carries its range index so the coordinator reports the
200/// lowest-indexed failure — deterministic, matching serial's earliest-tile
201/// failure. Workers exit when their range is drained or the coordinator drops
202/// the receiver (abort on an earlier range's failure): a failed `send` ends
203/// the worker rather than blocking it forever.
204type RangeOut = Result<(u64, Vec<ChunkEntry>)>;
205
206/// Merge one tile range over all chunks, streaming results in order.
207///
208/// Same heap discipline as [`Merged`]: chunks consumed in global chunk order,
209/// entries for one tile arriving layer-major, concatenated as they arrive. A
210/// range is exactly the serial merge restricted to its tile span, so its
211/// output is the serial output's subsequence — concatenating ranges in order
212/// reproduces the serial tile sequence byte for byte.
213///
214/// `end_tile` bounds the range (exclusive); entries at-or-after it stay
215/// unread for the next range. Chunks not touching the range are skipped
216/// without opening a reader.
217fn merge_range(
218 chunks: &[ChunkRef],
219 spill: &ChunkSpill,
220 plan: &RangePlan,
221 range: usize,
222 end_tile: u64,
223 out: &RangeTx,
224) {
225 use std::cmp::Reverse;
226 use std::collections::BinaryHeap;
227 // Padded trailing ranges ([zoom end, zoom end)) own nothing: yield
228 // nothing rather than decoding bucket 255 a second time.
229 if plan.bounds[range] >= end_tile {
230 return;
231 }
232 let window = crate::tilespill::read_window_bytes(chunks.len());
233 let ranges = plan.bounds.len() - 1;
234 let start_tile = plan.bounds[range];
235 let mut readers: Vec<Option<ChunkReader<'_>>> = Vec::with_capacity(chunks.len());
236 'chunks: for (ci, chunk) in chunks.iter().enumerate() {
237 let remaining = plan.remaining[ci][range];
238 if remaining == 0 {
239 readers.push(None);
240 continue;
241 }
242 // The window never larger than this chunk's share of the range: with many small ranges
243 // that share is often a few KB, and a full window per chunk per range would be both the
244 // memory and the I/O. A window size is unobservable in the output (pinned by test).
245 let start = plan.offsets[ci][range];
246 let end = if range + 1 < ranges { plan.offsets[ci][range + 1] } else { chunk.at + chunk.len };
247 let span = (end.saturating_sub(start) as usize).max(1);
248 let mut reader = spill.reader(chunk, window.min(span));
249 reader.seek_to(start, remaining, plan.exact_end[ci][range]);
250 // Bucket edges are coarser than range bounds: advance past entries
251 // below the bound (skip-walked, uncounted, `left` adjusted by the
252 // skips themselves so it still exhausts exactly at range end). A
253 // corrupt entry reports through the channel like a decode error.
254 loop {
255 let below = match reader.peek_tile() {
256 Ok(Some(t)) => t < start_tile,
257 Ok(None) => false,
258 Err(e) => {
259 // On to the next chunk. (A bare `continue` here re-ran this skip loop on the
260 // same failed reader forever, queueing an error and a reader slot per turn:
261 // unbounded memory instead of a failed build.)
262 let _ = out.send(Err(e));
263 readers.push(None);
264 continue 'chunks;
265 }
266 };
267 if !below {
268 break;
269 }
270 match reader.skip_entry() {
271 Ok(Some(_)) => {}
272 Ok(None) => break,
273 Err(e) => {
274 // On to the next chunk. (A bare `continue` here re-ran this skip loop on the
275 // same failed reader forever, queueing an error and a reader slot per turn:
276 // unbounded memory instead of a failed build.)
277 let _ = out.send(Err(e));
278 readers.push(None);
279 continue 'chunks;
280 }
281 }
282 }
283 readers.push(Some(reader));
284 }
285 let mut heap: BinaryHeap<Reverse<(u64, u8, usize)>> = BinaryHeap::new();
286 let mut front: Vec<Held> = Vec::with_capacity(chunks.len());
287 for (index, reader) in readers.iter_mut().enumerate() {
288 let head = match reader {
289 Some(r) => r.next().transpose(),
290 None => None,
291 };
292 match &head {
293 Some(Ok(((tile, layer), _))) => heap.push(Reverse((*tile, *layer, index))),
294 Some(Err(_)) => heap.push(Reverse((0, 0, index))),
295 None => {}
296 }
297 front.push(head);
298 }
299 // Mirrors `Merged::next`: the heap top names the tile, the inner loop
300 // drains it, entries concatenate layer-major in chunk order.
301 while let Some(&Reverse((tile, _, _))) = heap.peek() {
302 if tile >= end_tile {
303 break;
304 }
305 let mut layers: Vec<ChunkEntry> = Vec::new();
306 while let Some(&Reverse((at, layer_id, index))) = heap.peek() {
307 if at != tile {
308 break;
309 }
310 heap.pop();
311 let held = front[index].take().expect("a heap key without its entry");
312 let (_, mut layer) = match held {
313 Ok(entry) => entry,
314 Err(e) => {
315 let _ = out.send(Err(e));
316 return;
317 }
318 };
319 match layers.last_mut() {
320 Some(last) if last.layer.layer_id == layer_id => {
321 concatenate(last, &mut layer);
322 if let Some(r) = readers[index].as_mut() {
323 r.recycle(layer);
324 }
325 }
326 _ => layers.push(layer),
327 }
328 let head = match &mut readers[index] {
329 Some(r) => r.next().transpose(),
330 None => None,
331 };
332 match &head {
333 Some(Ok(((t, l), _))) => heap.push(Reverse((*t, *l, index))),
334 Some(Err(_)) => heap.push(Reverse((0, 0, index))),
335 None => {}
336 }
337 front[index] = head;
338 }
339 if out.send(Ok((tile, layers))).is_err() {
340 return;
341 }
342 }
343}
344
345/// Range-worker entry point for `thread::scope` spawning: merges range `r`
346/// and streams it, converting panics-by-Result into channel values.
347///
348/// Never returns `Err` itself (there is nowhere for it to go — the
349/// coordinator owns failure reporting): fallible setup is unreachable here
350/// because planning already validated every seek position, so the body is
351/// infallible by construction and any `Err` produced mid-merge travels as a
352/// value.
353fn merge_range_into(
354 chunks: &[ChunkRef],
355 spill: &ChunkSpill,
356 plan: &RangePlan,
357 r: usize,
358 tx: RangeTx,
359) {
360 let end_tile = plan.bounds[r + 1];
361 merge_range(chunks, spill, plan, r, end_tile, &tx);
362}
363
364/// Run-ahead allowance for range workers other than the one being drained, in estimated bytes of
365/// merged tile (see [`tile_bytes`]), shared by all of them.
366///
367/// Ranges drain strictly in order, and each worker used to stop after `RANGE_QUEUE_BOUND` tiles:
368/// so while range 0 drained, ranges 1..7 sat parked after 32 tiles each and the "parallel" merge
369/// was one k-way merge at a time (California z13: merge 4.5 s however many ranges; the Nov 10
370/// planet's z10-z12 merge+encode ran at 6-13 cores). Now the later ranges keep merging into
371/// their queues until this much is buffered between them. The range being drained keeps the old
372/// count bound -- it is consumed as it is produced -- and is never held by this budget, which is
373/// what keeps the drain deadlock-free: the coordinator only ever waits on the current range, and
374/// the current range only ever waits on the coordinator.
375const RANGE_AHEAD_BYTES: u64 = 4 << 30;
376
377/// A merged tile's rough size in memory, for [`RANGE_AHEAD_BYTES`]: its feature records and its
378/// coordinates. An estimate for a budget, never observable in the output.
379fn tile_bytes(layers: &[ChunkEntry]) -> u64 {
380 layers
381 .iter()
382 .map(|entry| entry.layer.features.len() as u64 * 32 + entry.layer.coords.len() as u64 * 8)
383 .sum::<u64>()
384 + 64
385}
386
387/// The range workers' output queues, drained in range order by [`ParallelMerge`].
388struct RangeQueues {
389 state: Mutex<RangeState>,
390 cv: std::sync::Condvar,
391}
392
393struct RangeState {
394 /// Per range: queued tiles (with their byte estimate) and whether its worker is done.
395 queues: Vec<std::collections::VecDeque<(RangeOut, u64)>>,
396 finished: Vec<bool>,
397 /// The range the coordinator is draining.
398 current: usize,
399 /// Bytes queued in ranges past `current`.
400 ahead: u64,
401 /// The coordinator went away (finished early on an error): workers stop.
402 abandoned: bool,
403 /// Who is parked on the condvar, so the hot paths notify only when someone is: a wake per
404 /// tile was the merge's whole cost on a zoom of millions of small tiles.
405 coordinator_waiting: bool,
406 workers_waiting: usize,
407}
408