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

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

tiler_part2.rs415 lines · 20.6 KiBRaw
1/// Decode threads for [`read_chunks`]: `MAPS_PREFETCH_LANES` when set, else a share of the box.
2///
3/// The old reader decoded through one `ZoomReader` (4 lanes) behind three more partitions it could
4/// not consume until the first was done, and moved every feature through one thread on the way to
5/// the workers; on a 192-thread box the clipping workers spent most of each small zoom blocked on
6/// it (California: ~190 of 192 workers parked on the chunk channel while the reader ran; the
7/// Nov 10 planet build's map phases ran at 3-5 cores with the reader's wall equal to the map's).
8/// Half the threads, at least 4 and at most 96: on the planet decode is most of a zoom's map (the
9/// Nov 10 rerun's z14 map clipped at ~28 of 192 cores with 64 decoders), and on California,
10/// where it is not, 32/64/96 decoders measured within noise of each other.
11fn decode_threads() -> usize {
12 match std::env::var("MAPS_PREFETCH_LANES").ok().and_then(|v| v.trim().parse::<usize>().ok()) {
13 Some(n) if n > 0 => n,
14 _ => (par::threads() / 2).clamp(4, 96),
15 }
16}
17
18/// Spill chunks (64 features each) per decode claim in [`read_chunks`].
19const DECODE_UNIT: usize = 16;
20
21/// Decoded blocks a decode thread may run ahead of the sequencer, per decode thread.
22const DECODE_AHEAD_PER_THREAD: usize = 8;
23
24/// One decoded spill chunk: the zoom's features from it and each one's vertex count.
25type DecodedBlock = osm_ingest::proto::Result<(Vec<Feature>, Vec<usize>)>;
26
27/// One slot of [`read_chunks`]'s reorder ring. Wanted-chunk `k` lives in slot `k % ring`; the slot
28/// expects `k` once the sequencer has taken `k - ring` out of it. A slot of its own per block --
29/// rather than one map behind one lock and two condvars -- because the shared version woke every
30/// parked decoder on every block taken and the sequencer on every block deposited, and that herd
31/// cost more than the decode it organised.
32struct RingSlot {
33 /// The wanted-chunk index this slot holds or waits for.
34 expect: usize,
35 block: Option<DecodedBlock>,
36}
37
38fn read_chunks(
39 store: &Store,
40 z: u8,
41 send: std::sync::mpsc::SyncSender<(usize, Vec<Vec<Feature>>)>,
42) -> Result<()> {
43 // Cut the zoom's feature stream into chunks of roughly [`chunk_vertices`] input vertices and
44 // send them on, in order. The stream is the wanted spill chunks in file order, each filtered to
45 // the zoom's window -- exactly what `Store::reader_for_zoom` yields -- and the cut is the same
46 // running vertex count, so the chunks (and their indices) are what they always were.
47 //
48 // Decode runs on dedicated threads (not the pool, which the clipping workers' own pool hand-offs
49 // use -- see `ZoomReader::spawn` for what queuing decode behind clipping cost), each claiming
50 // the next wanted chunk, so decode scales with the box instead of with four lanes. The
51 // sequencer (this thread) takes blocks back in wanted order and never touches a feature: it
52 // adds up the decoders' vertex counts and moves whole blocks, splitting one only where a cut
53 // falls inside it. A tiler chunk is therefore a list of blocks, walked in order by
54 // `tile_chunk`.
55 let wanted = store.wanted_chunks_for_zoom(z);
56 let total = wanted.len();
57 if total == 0 {
58 return Ok(());
59 }
60 let chunks = store.zoom_chunks().map_err(|e| tile_build::proto::Error(e.to_string()))?;
61 // Decoded in units of `DECODE_UNIT` consecutive spill chunks: one claim, one ring hand-off
62 // and one sequencer wake per unit rather than per 64-feature chunk. The planet's z14 is 21 M
63 // spill chunks, and per-chunk hand-offs (a lock and a futex wake each side) put the
64 // sequencer near saturation while ~28 of 192 cores clipped.
65 let units = total.div_ceil(DECODE_UNIT);
66 let decoders = decode_threads().min(units).max(1);
67 let ring = decoders * DECODE_AHEAD_PER_THREAD;
68 let claim = AtomicUsize::new(0);
69 let stop = std::sync::atomic::AtomicBool::new(false);
70 let slots: Vec<(Mutex<RingSlot>, std::sync::Condvar)> = (0..ring)
71 .map(|i| (Mutex::new(RingSlot { expect: i, block: None }), std::sync::Condvar::new()))
72 .collect();
73 let want = chunk_vertices();
74
75 std::thread::scope(|scope| -> Result<()> {
76 for lane in 0..decoders {
77 let (chunks, wanted, claim, stop, slots) = (&chunks, &wanted, &claim, &stop, &slots);
78 std::thread::Builder::new()
79 .name(format!("mamaps-decode-{lane}"))
80 .spawn_scoped(scope, move || {
81 let mut scratch = Vec::new();
82 let mut records = Vec::new();
83 loop {
84 let k = claim.fetch_add(1, Ordering::Relaxed);
85 if k >= units || stop.load(Ordering::Relaxed) {
86 return;
87 }
88 // The unit's chunks decoded in order and appended: the same features
89 // and counts, in the same order, as decoding them one by one.
90 let lo = k * DECODE_UNIT;
91 let hi = (lo + DECODE_UNIT).min(wanted.len());
92 let mut decoded: osm_ingest::proto::Result<(Vec<Feature>, Vec<usize>)> =
93 Ok((Vec::new(), Vec::new()));
94 for &chunk in &wanted[lo..hi] {
95 match chunks.decode(chunk, z, &mut scratch, &mut records) {
96 Ok((f, c)) => {
97 let acc = decoded.as_mut().expect("still Ok");
98 acc.0.extend(f);
99 acc.1.extend(c);
100 }
101 Err(e) => {
102 decoded = Err(e);
103 break;
104 }
105 }
106 }
107 let failed = decoded.is_err();
108 // Park until the sequencer has emptied this slot of `k - ring`. The thread
109 // holding the lowest outstanding claim always finds its slot free, so the
110 // ring cannot deadlock.
111 let (lock, cv) = &slots[k % ring];
112 let mut slot = lock.lock().expect("the map reader's ring");
113 while slot.expect != k && !stop.load(Ordering::Relaxed) {
114 slot = cv.wait(slot).expect("the map reader's ring");
115 }
116 if stop.load(Ordering::Relaxed) {
117 return;
118 }
119 slot.block = Some(decoded);
120 drop(slot);
121 cv.notify_all();
122 if failed {
123 return;
124 }
125 }
126 })
127 .map_err(|e| tile_build::proto::Error(format!("cannot start decode thread {lane}: {e}")))?;
128 }
129
130 let mut bar = Progress::new(format!("Map z{z}"), total, "chunk(s)", true);
131 let mut current: Vec<Vec<Feature>> = Vec::new();
132 let mut vertices = 0usize;
133 let mut index = 0usize;
134 let mut outcome: Result<()> = Ok(());
135 'blocks: for k in 0..units {
136 let decoded = {
137 let (lock, cv) = &slots[k % ring];
138 let mut slot = lock.lock().expect("the map reader's ring");
139 let block = loop {
140 if let Some(block) = slot.block.take() {
141 break block;
142 }
143 slot = cv.wait(slot).expect("the map reader's ring");
144 };
145 // Free the slot for `k + ring`, whose decoder may already be parked on it.
146 slot.expect = k + ring;
147 drop(slot);
148 cv.notify_all();
149 block
150 };
151 bar.tick_n((total - k * DECODE_UNIT).min(DECODE_UNIT), "chunk(s)");
152 let (mut features, counts) = match decoded {
153 Ok(block) => block,
154 Err(e) => {
155 outcome = Err(tile_build::proto::Error(e.to_string()));
156 break 'blocks;
157 }
158 };
159 // `taken`: how many of this block's features already went out with an earlier cut.
160 let mut taken = 0usize;
161 for (i, &n) in counts.iter().enumerate() {
162 vertices += n;
163 if vertices >= want {
164 let tail = features.split_off(i + 1 - taken);
165 current.push(std::mem::replace(&mut features, tail));
166 if send.send((index, std::mem::take(&mut current))).is_err() {
167 // The workers are gone (a failure they already recorded): stop reading.
168 break 'blocks;
169 }
170 index += 1;
171 vertices = 0;
172 taken = i + 1;
173 }
174 }
175 if !features.is_empty() {
176 current.push(features);
177 }
178 }
179 // Release any decoder parked on a slot, whatever ended the loop.
180 stop.store(true, Ordering::Relaxed);
181 for (lock, cv) in &slots {
182 drop(lock.lock().expect("the map reader's ring"));
183 cv.notify_all();
184 }
185 if outcome.is_ok() && !current.is_empty() {
186 let _ = send.send((index, current));
187 }
188 bar.finish("chunk(s)");
189 outcome
190 })
191}
192
193/// Take chunks until the reader is finished, tiling each into a map of its own and spilling it.
194///
195/// A panic inside one chunk is **caught and recorded** rather than allowed to unwind, and the loop
196/// keeps draining. That is not defensiveness about a bug that should not happen, it is about the
197/// shape of the failure: a worker that dies with a bounded channel full behind it leaves the reader
198/// blocked on a send nobody will ever take, and at one worker there is nobody else to drain it. So
199/// the bug's symptom would be a 64-core box sitting at 0% forever in the middle of a five-minute
200/// stage, instead of an error naming the zoom. `map_zoom` fails the build on the flag.
201///
202/// The spill write is deliberately **outside** the `catch_unwind`, which wraps [`tile_chunk`] alone.
203/// A failed write records the flag and keeps draining for exactly the same reason a panic does.
204/// The chunk queue one tiling worker drains.
205type ChunkReceiver = Mutex<std::sync::mpsc::Receiver<(usize, Vec<Vec<Feature>>)>>;
206
207/// Shared inputs for [`tile_chunks`], grouped so call sites name them.
208struct TileChunksCtx<'a> {
209 receive: &'a ChunkReceiver,
210 done: &'a Mutex<Vec<(usize, ChunkRef, Tally)>>,
211 failed: &'a std::sync::atomic::AtomicBool,
212 spill: &'a ChunkSpill,
213 z: u8,
214 tolerance: f64,
215 buffer: f64,
216 country_zooms: &'a std::collections::HashMap<u64, u8>,
217}
218
219fn tile_chunks(ctx: TileChunksCtx<'_>) {
220 let TileChunksCtx { receive, done, failed, spill, z, tolerance, buffer, country_zooms } = ctx;
221 loop {
222 // Held to take a chunk and never while tiling one: the lock covers a pointer move, and the
223 // work either side of it is milliseconds.
224 let next = receive.lock().expect("the chunk queue").recv();
225 let Ok((index, features)) = next else { return };
226 // `AssertUnwindSafe` because everything the closure touches is a local: the chunk map it
227 // builds is thrown away on a panic.
228 let tiled = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
229 tile_chunk(&features, z, tolerance, buffer, country_zooms)
230 }));
231 match tiled {
232 Ok((chunk, tally)) => match spill.write_chunk(chunk) {
233 Ok(at) => done.lock().expect("the chunk list").push((index, at, tally)),
234 Err(e) => {
235 eprintln!("ERROR: cannot spill chunk {index} of z{z}: {e}");
236 failed.store(true, Ordering::Relaxed);
237 }
238 },
239 Err(_) => {
240 eprintln!("ERROR: chunk {index} of z{z} panicked while being tiled");
241 failed.store(true, Ordering::Relaxed);
242 }
243 }
244 }
245}
246
247/// Project, simplify and clip one chunk of features into a tile map of its own.
248///
249/// Verbatim the loop this module used to run on the main thread over the whole store, with the
250/// destination private to the caller. Nothing here reads shared state, and that is why the chunk
251/// boundaries cannot change a result: a feature's fate depends on the feature, the zoom and the
252/// tolerance, and on nothing else in the chunk it happens to be in.
253///
254/// The tile loop is a quadtree descent ([`subdivide::subdivide`]), not a pass over every tile the
255/// feature touches. A boundary relation spanning three states used to be clipped in full against
256/// each of its hundreds of thousands of z13 tiles; now it is clipped once per zoom level. Filtering
257/// stays where it was, **before** the descent: significance is measured on the whole geometry, so a
258/// vertex's fate must not depend on which tile it lands in.
259///
260/// `country_zooms` (place id → label start zoom, probe-only) drops a `country` label
261/// below its start zoom before any geometry work: the label is a point, so nothing
262/// downstream would remove it, and carrying it would defeat the gating.
263/// Whether the z14 wash cap is active for this build.
264///
265/// Unconditional: the renderer overzooms wash from z13 (shipped together with
266/// this gate), so gated archives are always safe to publish. (Previously
267/// opt-in via `MAMAPS_WASH_CAP=1` during the renderer-first rollout; the flag
268/// is retired now that both halves ship.)
269///
270/// `pub(crate)` so tests asserting flag-dependent behavior (e.g. the rings
271/// lake test) can branch rather than baking one flag state in.
272pub(crate) fn wash_cap_enabled() -> bool {
273 true
274}
275
276/// Whether a feature is wash dropped at this zoom: z14 landtype areas whose
277/// class is carried at shallower zooms (`min_zoom != max`) are redundant with
278/// the z13 parent tile, which the renderer overzooms. Detail areas
279/// (`min_zoom == 14`: pools, pitches, playgrounds — kinds absent at z13 so
280/// overzoom cannot recover them) and all lines (cheap, high-salience relief
281/// and hydrography cues) survive.
282///
283/// Pure function of (kind, zoom, geometry-type): no geometry work, no shared
284/// state, so chunk/thread boundaries cannot change the answer — the property
285/// `tile_chunk`'s doc comment defends.
286fn is_wash_dropped(feature: &Feature, z: u8) -> bool {
287 wash_cap_enabled() && wash_drops_kind(feature.class.layer, feature.class.area, feature.class.min_zoom, z)
288}
289
290/// The wash-cap predicate without the env gate, so unit tests can pin the
291/// rule without touching process-global state (the `OnceLock` in
292/// `wash_cap_enabled` is set once per test process).
293fn wash_drops_kind(layer: u8, area: bool, min_zoom: u8, z: u8) -> bool {
294 use tilecodec::mamaps::dict;
295 z == crate::DEFAULT_MAX_ZOOM
296 && layer == dict::LAYER_LANDTYPE
297 && area
298 && min_zoom != crate::DEFAULT_MAX_ZOOM
299}
300
301/// Vertices at or above which one feature's quadtree descent runs on the pool
302/// ([`subdivide::subdivide_par`]). Below it a feature tiles in well under a millisecond and the
303/// hand-off would cost more than it saves.
304const PAR_SUBDIVIDE_MIN_VERTICES: usize = 20_000;
305
306fn tile_chunk(
307 features: &[Vec<Feature>],
308 z: u8,
309 tolerance: f64,
310 buffer: f64,
311 country_zooms: &std::collections::HashMap<u64, u8>,
312) -> (Chunk, Tally) {
313 let mut tiles: Chunk = BTreeMap::new();
314 let mut tally = Tally::default();
315 // TEMP-PROFILE: per-stage walls inside the map phase. Thread-local (each
316 // worker runs its own `tile_chunk`), summed into the process log at
317 // `map_zoom` end. Removed once the hotspot is measured (CA run).
318 let mut t_project = std::time::Duration::ZERO;
319 let mut t_annotate = std::time::Duration::ZERO;
320 let mut t_filter = std::time::Duration::ZERO;
321 let mut t_subdiv = std::time::Duration::ZERO;
322 // A chunk is the reader's blocks in stream order (see `read_chunks`); flattened, it is the
323 // feature run the chunk always was.
324 for feature in features.iter().flatten() {
325 // Country label gating: the score (footprint × headcount) decided in stage A
326 // (see `extract_fallback::country_zoom`); this is where it is enforced. A
327 // missing score keeps the schema floor — a missing map entry must never hide
328 // a country. Probe-only (`get`), never iterated, so the archive stays
329 // deterministic; counted as dropped so the report stays honest.
330 if feature.class.layer == tilecodec::mamaps::dict::LAYER_PLACES {
331 if let Some(&start) = country_zooms.get(&feature.id) {
332 if z < start {
333 tally.dropped += 1;
334 continue;
335 }
336 }
337 }
338 // z14 wash cap: wash areas are redundant with the z13 parent (see
339 // `is_wash_dropped`). Before any geometry work, like the gate above.
340 if is_wash_dropped(feature, z) {
341 tally.dropped += 1;
342 continue;
343 }
344 let t = std::time::Instant::now();
345 let mut projected = geom::project_geometry(&feature.geometry, z, EXTENT);
346 t_project += t.elapsed();
347 // Significance first, then filter: computed on the whole geometry so a vertex's fate
348 // does not depend on which tile it lands in.
349 let t = std::time::Instant::now();
350 simplify::annotate(&mut projected);
351 t_annotate += t.elapsed();
352 // Buildings live only at z14, where the policy tolerance is 0.0; the floor below
353 // keeps only collinear midpoints and sub-pixel jaggies — see `tolerance_for_layer`.
354 // Roads take the per-feature floor at z14 (washable classes only).
355 let layer_tolerance = tolerance_for_feature(feature, z, tolerance);
356 let t = std::time::Instant::now();
357 let thinned = simplify::filter(&projected, layer_tolerance);
358 t_filter += t.elapsed();
359 // Near-rectangles digitised by hand gain a cheap varint delta when their edges snap
360 // exactly axis-aligned — see `snap_building_rings`. Survivors only, so the measured
361 // significance above is never stale; a pure function of the feature, so the archive
362 // stays independent of thread count and chunk boundaries. Gated to the one layer that
363 // pays for it, so every other layer's filtered geometry moves without another copy.
364 let thinned = if feature.class.layer == tilecodec::mamaps::dict::LAYER_BUILDINGS {
365 snap_building_rings(&thinned, feature.class.layer)
366 } else {
367 thinned
368 };
369 if is_empty(&thinned) {
370 tally.dropped += 1;
371 continue;
372 }
373 let t = std::time::Instant::now();
374 let mut emit = |tx: u64, ty: u64, clipped: &Geometry<SigPt>| {
375 // The descent prunes on a part surviving at all; this is the stricter test that
376 // decides whether a tile is worth writing, and it stays exactly where it was.
377 if is_empty(clipped) {
378 return;
379 }
380 let local = geom::to_tile(clipped, tx, ty, EXTENT);
381 let q = size_opts().quant_step(z, feature.class.layer);
382 let local = if q > 1 { snap_grid(local, q) } else { local };
383 if is_empty_int(&local) {
384 return;
385 }
386 let layer = tiles
387 .entry((tile_id(z, tx, ty), feature.class.layer))
388 .or_insert_with(|| ChunkEntry::new(feature.class.layer));
389 let added = push(layer, feature, &local);
390 tally.features += added.0;
391 tally.points += added.1;
392 };
393 // A huge line or polygon (a state boundary, a national forest, a long coastline run)
394 // descends on the pool: alone it held z12-z14's map phase on one thread for seconds
395 // after every other chunk was done. `subdivide_par` returns the tiles in exactly the
396 // order `subdivide` emits them, so replaying them through the same `emit` is the same
397 // sequence of pushes.
398 if !matches!(thinned, Geometry::Points(_))
399 && subdivide::vertex_count(&thinned) >= PAR_SUBDIVIDE_MIN_VERTICES
400 {
401 for (tx, ty, clipped) in subdivide::subdivide_par(&thinned, z, EXTENT, buffer) {
402 emit(tx, ty, &clipped);
403 }
404 } else {
405 subdivide::subdivide(&thinned, z, EXTENT, buffer, &mut emit);
406 }
407 t_subdiv += t.elapsed();
408 }
409 // TEMP-PROFILE: summed per worker; see `map_zoom` for the fold.
410 // Removed with the probes.
411 tally.profile_add(t_project, t_annotate, t_filter, t_subdiv);
412 (tiles, tally)
413}
414
415include!("tiler_part2_s1.rs");