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

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

tiler_part1_s1.rs346 lines · 18.4 KiBRaw
1/// Merge → encode → prune → append for one zoom, over any tile-ordered merge
2/// iterator.
3///
4/// Extracted whole from the zoom loop so serial and range-parallel merges share
5/// it: batches are contiguous pulls in merge order, `encode_batch` preserves
6/// tile order, and prune/append see the identical sequence either way — which
7/// is why the archive does not move between the two paths.
8#[allow(clippy::too_many_arguments)]
9fn consume_merged(
10 merged: &mut (impl Iterator<Item = Result<(u64, Vec<ChunkEntry>)>> + Send),
11 stats: &mut ZoomStats,
12 z: u8,
13 timer: &mut crate::timing::PhaseTimer,
14 dem: &crate::dem::Dem,
15 conventions: &crate::schema::boundaries::Conventions,
16 region_links: &std::collections::HashMap<u64, u64>,
17 writer: &mut tilecodec::mamaps::write::StreamWriter,
18) -> Result<()> {
19 // Merge, encode and append have no total to count against -- the tile count is only known once
20 // the merge has produced it -- so the merge bar counts tiles merged and the encode line below
21 // counts tiles written.
22 let zoom_start = std::time::Instant::now();
23 let mut merged_tiles = 0usize;
24 let mut merge_shown = 0usize;
25 let mut written = 0usize;
26 let mut shown = 0usize;
27 // Pipelined by one batch: while batch `k` is appended (serial: the writer's dedup and its
28 // scratch writes), batch `k + 1` is pulled from the merge and encoded on the pool. The three
29 // used to take turns, so the pool sat idle through every append and the writer through
30 // every encode. Batches are the same contiguous pulls of the merge, encoded and pruned
31 // exactly as before (`prune_barren_subtree` never looks past its own batch), and appended in
32 // the same order, so the archive does not move. The per-zoom `merge`/`encode`/`append`
33 // columns still time each part on its own; the run's phase clock books the overlapped
34 // stretch as `merge`.
35 let mut pending: Option<Vec<Encoded>> = None;
36 // A third stage ahead of those two: a puller thread takes the merge batches (the k-way merge,
37 // or the parallel coordinator) for pass `k + 2` while pass `k + 1` encodes and pass `k`
38 // appends. The pulls are the same `merge_batch` calls in the same order with the same cuts,
39 // only on another thread; the hand-off is a one-deep channel, so at most one pulled pass
40 // waits beside the two in flight.
41 type Pulled = Result<Option<(Vec<(u64, Vec<ChunkEntry>)>, Vec<usize>, u64)>>;
42 std::thread::scope(|scope| -> Result<()> {
43 let (pull_tx, pull_rx) = std::sync::mpsc::sync_channel::<Pulled>(1);
44 let merged = &mut *merged;
45 scope.spawn(move || loop {
46 let merging = std::time::Instant::now();
47 // Several merge batches per encode pass, each cut exactly where `merge_batch`
48 // always cut it. One cost-capped batch is too little work to spread over 192 threads
49 // (California z13: ~8 encode tasks running, the rest of the pool spinning), but the
50 // cut points are what `prune_barren_subtree` is bounded by, so they are kept and each
51 // batch is pruned on its own. Encoding is per tile, so the bytes do not depend on how
52 // many batches share a pass.
53 let mut batch: Vec<(u64, Vec<ChunkEntry>)> = Vec::new();
54 let mut cuts: Vec<usize> = Vec::new();
55 let mut failed = None;
56 for _ in 0..BATCHES_PER_ENCODE {
57 // A truncated scratch file must fail the build rather than end the zoom early and
58 // publish a short archive.
59 match merge_batch(&mut *merged, par::batch_len()) {
60 Ok(pulled) if pulled.is_empty() => break,
61 Ok(pulled) => {
62 batch.extend(pulled);
63 cuts.push(batch.len());
64 }
65 Err(e) => {
66 failed = Some(e);
67 break;
68 }
69 }
70 }
71 let item: Pulled = match failed {
72 Some(e) => Err(e),
73 None if batch.is_empty() => Ok(None),
74 None => Ok(Some((batch, cuts, merging.elapsed().as_millis() as u64))),
75 };
76 let last = !matches!(item, Ok(Some(_)));
77 if pull_tx.send(item).is_err() || last {
78 return;
79 }
80 });
81 loop {
82 // Cost-batched rather than count-batched: z14 has tiles whose merged geometry is tens
83 // of MB (a dense city tile's whole layer set) beside rural tiles worth bytes. A
84 // fixed `batch_len()` of those holds ~GB of merged tiles plus their encoded copies
85 // before the writer takes them -- on top of the merge's own peak, on a box with
86 // ~50 GB of commit headroom, which is where `Map z14 [100%]` went followed by a
87 // 512 KiB allocation failure. Capped at `MERGE_BATCH_BYTES` of merged cost, so a
88 // heavy tile still gets its own batch (a minimum of one batch per pull) and common
89 // zooms -- whose batches never reach the cap -- take the same count they always
90 // did. Order is untouched: batches are contiguous pulls of the merge in order, and
91 // `encode_batch` preserves tile order, so the archive does not move.
92 timer.switch("merge");
93 let pulled = pull_rx
94 .recv()
95 .unwrap_or_else(|_| Err(tile_build::proto::Error("the merge puller stopped".into())));
96 let (appended, produced) = par::install(|| {
97 rayon::join(
98 || -> Result<u64> {
99 let Some(done) = pending.take() else { return Ok(0) };
100 let appending = std::time::Instant::now();
101 for (id, encoded, rings, lines) in done {
102 stats.rings.add(rings);
103 stats.lines.add(lines);
104 let Some((stored, raw_len, hash)) = encoded else { continue };
105 // Uncompressed, as this column has always meant.
106 stats.bytes += raw_len as u64;
107 stats.tiles += 1;
108 // Handed over whole: the writer's background thread copies and
109 // writes the body, this thread only does the dedup bookkeeping.
110 writer.append_stored_owned(id, stored, hash)?;
111 written += 1;
112 // Every 25k tiles: often enough to look alive on a continent, rare
113 // enough that the write itself is never the cost.
114 if written - shown >= 25_000 {
115 shown = written;
116 eprint!(
117 "\r{:<28} [{written:>10} tile(s)] {} elapsed ",
118 format!("Encode z{z}"),
119 tile_build::progress::hms(zoom_start.elapsed().as_secs_f64()),
120 );
121 let _ = std::io::Write::flush(&mut std::io::stderr());
122 }
123 }
124 Ok(appending.elapsed().as_millis() as u64)
125 },
126 || -> Result<Option<EncodedBatch>> {
127 let Some((batch, cuts, merge_ms)) = pulled? else { return Ok(None) };
128 let tiles = batch.len();
129 let encoding = std::time::Instant::now();
130 let encoded = encode_batch(batch, dem, conventions, region_links)?;
131 // Phase B: prune barren subtrees. A tile whose four children all came
132 // back empty (`None` — genuinely featureless, or full-bleed water
133 // background) is itself the end of the tree: drop the children and let
134 // the reader stop at the parent (overzoom). Only above z0 and only when
135 // all four children of a parent are present-and-empty in one merge
136 // batch — never across batch boundaries, so the archive stays
137 // independent of batching and thread count.
138 let mut done: Vec<Encoded> = Vec::with_capacity(encoded.len());
139 let mut encoded = encoded.into_iter();
140 let mut start = 0usize;
141 for &end in &cuts {
142 let mut piece: Vec<Encoded> = encoded.by_ref().take(end - start).collect();
143 prune_barren_subtree(z, &mut piece);
144 done.extend(piece);
145 start = end;
146 }
147 Ok(Some((done, tiles, merge_ms, encoding.elapsed().as_millis() as u64)))
148 },
149 )
150 });
151 // The append of the earlier batch reports first, as it did when it ran first.
152 stats.append_ms += appended?;
153 let Some((done, tiles, merge_ms, encode_ms)) = produced? else { break };
154 stats.merge_ms += merge_ms;
155 stats.encode_ms += encode_ms;
156 // Count the tiles as soon as the merge produced them, so the bar moves during the
157 // merge rather than only when the append drains.
158 merged_tiles += tiles;
159 if merged_tiles - merge_shown >= 25_000 {
160 merge_shown = merged_tiles;
161 eprint!(
162 "\r{:<28} [{merged_tiles:>10} tile(s)] {} elapsed ",
163 format!("Merge z{z}"),
164 tile_build::progress::hms(zoom_start.elapsed().as_secs_f64()),
165 );
166 let _ = std::io::Write::flush(&mut std::io::stderr());
167 }
168 pending = Some(done);
169 }
170 Ok(())
171 })?;
172 if merged_tiles > 0 {
173 eprintln!(
174 "\r{:<28} [{merged_tiles:>10} tile(s)] {} elapsed ",
175 format!("Merge z{z}"),
176 tile_build::progress::hms(zoom_start.elapsed().as_secs_f64()),
177 );
178 }
179 if written > 0 {
180 eprintln!(
181 "\r{:<28} [{written:>10} tile(s)] {} elapsed ",
182 format!("Encode z{z}"),
183 tile_build::progress::hms(zoom_start.elapsed().as_secs_f64()),
184 );
185 }
186 Ok(())
187}
188
189/// Merge batches gathered into one encode pass by [`consume_merged`]. Each keeps its own cut (and
190/// its own prune); this only decides how much work one pool hand-off carries.
191const BATCHES_PER_ENCODE: usize = 16;
192
193/// One merge pull, capped by merged-geometry cost rather than by tile count.
194///
195/// Pulls up to `max_tiles` from the merge, stopping early once the accumulated `tile_cost` --
196/// features plus coordinates, the same proxy the encode pass balances tasks by -- reaches
197/// [`MERGE_BATCH_BYTES`]. Always pulls at least one tile, so a tile heavier than the cap on its
198/// own still makes progress. The pulled prefix is contiguous merge order, so feeding it to
199/// `encode_batch` (which preserves tile order) keeps the archive byte-identical: the only
200/// change is how many tiles one batch holds.
201///
202/// Contiguity is also what [`prune_barren_subtree`] relies on: four siblings of one parent
203/// occupy consecutive tile ids, so a parent's whole child set is either inside one batch or
204/// split across a batch boundary — and only the first case prunes, which keeps the archive
205/// independent of where the batcher cut.
206fn merge_batch(
207 merged: &mut impl Iterator<Item = Result<(u64, Vec<ChunkEntry>)>>,
208 max_tiles: usize,
209) -> Result<Vec<(u64, Vec<ChunkEntry>)>> {
210 let mut batch: Vec<(u64, Vec<ChunkEntry>)> = Vec::new();
211 let mut cost: u64 = 0;
212 for tile in merged.by_ref().take(max_tiles) {
213 let (id, layers) = tile?;
214 cost += tile_cost(&layers);
215 batch.push((id, layers));
216 // Checked after pushing, so the batch is never empty and a heavy tile closes its own
217 // batch -- the same shape as `partition_by_cost`'s grouping, for the same reason.
218 if cost >= MERGE_BATCH_BYTES {
219 break;
220 }
221 }
222 Ok(batch)
223}
224
225/// Prune barren subtrees within one encoded batch: drop the four empty children of a
226/// tile whose whole child set came back `None`.
227///
228/// A `None` child is a tile with nothing drawable — genuinely featureless, or full-bleed
229/// water background (Phase B). The reader's miss path already overzooms: a missing tile
230/// falls back to its parent, whose background (or whose own body) shows through. So four
231/// empty siblings carry no information their parent does not, and storing them buys index
232/// entries, leaf span and fetches for zero pixels.
233///
234/// The conditions are deliberately strict, because a wrong prune deletes drawable map:
235///
236/// * `z == 0` never prunes: the world tile has no parent to overzoom to.
237/// * All four children of a parent must be present **in this batch** and all `None`.
238/// A parent split across a batch boundary keeps its children — the archive must not
239/// depend on where the cost-batcher cut, and a partial set cannot prove barrenness.
240/// * Only `None` children prune. A stored child (even a tiny one) means drawable content.
241/// * The parent itself is untouched: it was merged and encoded in its own zoom pass (zooms
242/// tile independently), so pruning children never orphans a stored parent.
243///
244/// Recursion across zooms falls out of the zoom loop: a z13 tile whose z14 children were
245/// all pruned is itself absent-or-water, so when z13 encodes, *its* parent sees four empty
246/// children and prunes again — the tree ends where the content does.
247///
248/// Runs on the serial append thread over the encoded batch (not in the parallel encode
249/// workers): it inspects batch adjacency, which only the ordered batch has. Pure function
250/// of the batch's `(id, Option)` pairs, so thread count and chunk boundaries cannot move it.
251fn prune_barren_subtree(z: u8, done: &mut Vec<Encoded>) {
252 if z == 0 || done.len() < 4 {
253 return;
254 }
255 // Index by tile id for sibling lookup. The batch is ascending by id (merge order
256 // through `encode_batch`'s positional collect), so positions are found by search
257 // rather than assumed adjacent: siblings are consecutive ids but not necessarily
258 // consecutive positions (a stored neighbour may sit between them — which itself
259 // vetoes the prune, correctly).
260 let mut drop_ids: std::collections::BTreeSet<u64> = std::collections::BTreeSet::new();
261 let mut at: std::collections::HashMap<u64, usize> = std::collections::HashMap::new();
262 for (index, (id, _, _, _)) in done.iter().enumerate() {
263 at.insert(*id, index);
264 }
265 for (index, (id, encoded, _, _)) in done.iter().enumerate() {
266 let _ = index;
267 if encoded.is_some() {
268 continue;
269 }
270 let (tz, tx, ty) = tilecodec::pmtiles::tile_zxy(*id);
271 if tz != z {
272 continue;
273 }
274 // Only the top-left child starts the check, so each parent is considered once.
275 if tx % 2 != 0 || ty % 2 != 0 {
276 continue;
277 }
278 let (px, py) = (tx / 2, ty / 2);
279 let mut siblings: Vec<u64> = Vec::with_capacity(4);
280 for (dx, dy) in [(0u64, 0u64), (1, 0), (0, 1), (1, 1)] {
281 siblings.push(tilecodec::pmtiles::tile_id(z, px * 2 + dx, py * 2 + dy));
282 }
283 // All four present in this batch and all empty: the parent covers them.
284 let all_empty = siblings.iter().all(|sib| {
285 at.get(sib).is_some_and(|&i| done[i].1.is_none())
286 });
287 if all_empty {
288 for sib in siblings {
289 drop_ids.insert(sib);
290 }
291 }
292 }
293 if !drop_ids.is_empty() {
294 done.retain(|(id, _, _, _)| !drop_ids.contains(id));
295 }
296}
297
298/// Cap on one merge pull's merged-geometry cost, in `tile_cost` units (features + coordinates).
299///
300/// 8 M units is ~64 MB of merged tile geometry per batch at typical z14 density -- small against
301/// the box, large against the pool (still hundreds of tiles per batch on common zooms, so the
302/// encode pass stays fed). The failure this bounds held ~GB: `batch_len()` tiles at 64 threads
303/// is 4096 tiles, and a planet z14 batch of those carries dense-city tiles tens of MB each.
304const MERGE_BATCH_BYTES: u64 = 8 << 20;
305
306/// Which backend one zoom's tile-chunk spill stages in.
307///
308/// The chunk spill holds clipped copies -- one record per (feature, tile) pair -- so its size
309/// scales with the store's feature count times the tiling fan-out, not with anything known
310/// exactly up front. The estimate is `features x 512 B`: a clipped copy carries the feature's
311/// packed body (tens of bytes) plus its share of parts/coords, and z14's fan-out dominates.
312/// Over-estimating files a zoom that would have fit anon; under-estimating pages it. Files are
313/// the safe side -- same chunks, removed on drop -- so the constant leans that way.
314///
315/// Unknown limits (or a small store under 1 M features): the historical anon path, no behaviour
316/// change.
317fn plan_chunk_spill(store: &Store, scratch: &std::path::Path) -> osm_ingest::mem::SpillPlan {
318 const CHUNK_BYTES_PER_FEATURE: u64 = 512;
319 const SMALL_STORE_FEATURES: u64 = 1_000_000;
320 if store.len() < SMALL_STORE_FEATURES {
321 return osm_ingest::mem::SpillPlan::Anon;
322 }
323 // Reuse the anon-commit field for the chunk estimate: it is the number `decide` compares
324 // against the commit allowance, and the chunk spill is the only anon charge this phase adds
325 // (the feature spill is already staged and counted separately).
326 let budget = osm_ingest::mem::StageBudget { ways_spill_bytes: store.len().saturating_mul(CHUNK_BYTES_PER_FEATURE), ..Default::default() };
327 match osm_ingest::mem::SpillPlan::decide(&budget, scratch, "tiler chunk spill") {
328 Ok(plan) => {
329 if plan != osm_ingest::mem::SpillPlan::Anon {
330 eprintln!(
331 " [tiler] chunk spill -> {} (file backend: commit budget)",
332 scratch.display(),
333 );
334 }
335 plan
336 }
337 Err(e) => {
338 // A zoom that fits neither backend is not a hard failure here: later zooms are
339 // smaller, and each zoom re-creates the spill. Warn and take files -- the operator
340 // sees the message and the build still has a chance.
341 eprintln!("WARN: {e}; continuing with file staging");
342 osm_ingest::mem::SpillPlan::File
343 }
344 }
345}
346