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

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

tiler_part1_s2.rs233 lines · 10.8 KiBRaw
1/// The map half of one zoom: every feature in the store, clipped into per-chunk tile maps and
2/// spilled to `spill` as each is finished.
3///
4/// Returns the chunks **in read order**, which is the only order the reduce may use them in.
5///
6/// The reader gets a thread of its own rather than a task on the pool, and that is not a
7/// preference. A producer that blocks on a full channel from inside the pool it feeds deadlocks when
8/// the pool has one thread: the single worker *is* the producer, so nothing can drain what it is
9/// waiting to write. Off the pool, one thread is merely slow — which matters, because one thread is
10/// a configuration this has to stay byte-identical at.
11fn map_zoom(
12 store: &Store,
13 settings: &Settings,
14 z: u8,
15 tolerance: f64,
16 buffer: f64,
17 spill: &ChunkSpill,
18) -> Result<(Vec<ChunkRef>, Tally)> {
19 // The full budget, **not** minus the reader's prefetch lanes. Subtracting them was tried, on the
20 // reasoning that 64 workers plus 16 lanes plus a reader is 81 runnable threads on 64 CPUs. It
21 // fixed us-west (151.9 s to 94.4 s) and cost north-america more than it saved (766.9 s to
22 // 900.4 s), because the premise is only true when the lanes are actually running: on
23 // north-america the workers are the ones blocked, waiting on a channel the reader cannot fill
24 // fast enough, so the lanes were competing with nothing and the subtraction just removed a
25 // quarter of the clipping. z14's map went 138.7 s to 170.0 s, almost exactly the ratio.
26 //
27 // Which of those two regimes a build is in is what `crate::store::PREFETCH_LANES` has to be set
28 // for, and it is not knowable from the thread count.
29 let workers = par::threads().max(1);
30 // Bounded, because this is the one place the parallel tiler holds features the sequential one
31 // did not: `2 * threads` chunks of about `chunk_vertices()` vertices, and no more however far
32 // ahead of the workers the reader gets.
33 let (send, receive) = std::sync::mpsc::sync_channel::<(usize, Vec<Vec<Feature>>)>(workers * 2);
34 let receive = Mutex::new(receive);
35 let done: Mutex<Vec<(usize, ChunkRef, Tally)>> = Mutex::new(Vec::new());
36 let failed = std::sync::atomic::AtomicBool::new(false);
37
38 std::thread::scope(|scope| -> Result<()> {
39 // TEMP-PROFILE: reader wall (feed rate). The reader thread returns
40 // its wall clock alongside its result; compared against the zoom's
41 // map wall it answers feed-bound vs worker-bound. Removed with the
42 // probes.
43 let reader_start = std::time::Instant::now();
44 let reader = std::thread::Builder::new()
45 .name("mamaps-read".to_string())
46 .spawn_scoped(scope, move || {
47 let r = read_chunks(store, z, send);
48 (r, reader_start.elapsed())
49 })
50 .map_err(|e| tile_build::proto::Error(format!("cannot start the store reader: {e}")))?;
51
52 // One worker runs on this thread whatever happens, so a machine that will not give us
53 // threads is slow rather than a build hung on a channel nobody is draining.
54 let mut spawned = Vec::new();
55 for i in 1..workers {
56 let worker = std::thread::Builder::new()
57 .name(format!("mamaps-tile-{i}"))
58 .stack_size(WORKER_STACK)
59 .spawn_scoped(scope, || {
60 tile_chunks(TileChunksCtx { receive: &receive, done: &done, failed: &failed, spill, z, tolerance, buffer, country_zooms: &settings.country_zooms })
61 });
62 match worker {
63 Ok(handle) => spawned.push(handle),
64 Err(e) => {
65 eprintln!("WARN: cannot start tiling thread {i} ({e}); continuing without");
66 break;
67 }
68 }
69 }
70 tile_chunks(TileChunksCtx { receive: &receive, done: &done, failed: &failed, spill, z, tolerance, buffer, country_zooms: &settings.country_zooms });
71 for handle in spawned {
72 handle.join().map_err(|_| {
73 tile_build::proto::Error("a tiling thread panicked".to_string())
74 })?;
75 }
76 let (reader_result, reader_wall) = reader.join().map_err(|_| {
77 tile_build::proto::Error("the store reader thread panicked".to_string())
78 })?;
79 // TEMP-PROFILE: stash the reader wall where the tally fold prints
80 // it. Removed with the probes.
81 crate::tiler::stash_reader_wall(z, reader_wall);
82 reader_result
83 })?;
84
85 if failed.load(Ordering::Relaxed) {
86 // Refused rather than published. A skipped chunk is a handful of features missing from a
87 // handful of tiles: no error on device, no visibly broken tile, just an archive that is
88 // quietly not the one the report describes.
89 return err(format!("a chunk of z{z} could not be tiled; see the message above"));
90 }
91
92 let mut chunks = done.into_inner().expect("the chunk list outlives its workers");
93 // **The reduce order.** By the index a chunk was read at, never by the order it finished in, and
94 // never by where in the scratch file it happened to land. This one line is what keeps the
95 // archive independent of the thread count.
96 chunks.sort_by_key(|(index, _, _)| *index);
97 let mut tally = Tally::default();
98 for (_, _, chunk_tally) in &chunks {
99 tally.add(*chunk_tally);
100 }
101 // TEMP-PROFILE: per-stage map walls, summed across chunks (CPU time, so
102 // the sum exceeds wall on 64 threads — ratios, not walls, are the read),
103 // plus the reader thread's own wall (feed rate) and the map wall implied
104 // by the caller. `reader_ms` vs the zoom's `map_ms` answers feed-bound
105 // vs worker-bound: a reader wall near the map wall means workers starved.
106 // Removed with the probes.
107 eprintln!(
108 " [mapprofile] z{z}: project={:.1}s annotate={:.1}s filter={:.1}s subdiv={:.1}s reader={:.1}s",
109 tally.profile.project.as_secs_f64(),
110 tally.profile.annotate.as_secs_f64(),
111 tally.profile.filter.as_secs_f64(),
112 tally.profile.subdiv.as_secs_f64(),
113 crate::tiler::take_reader_wall().as_secs_f64()
114 );
115 Ok((chunks.into_iter().map(|(_, at, _)| at).collect(), tally))
116}
117
118/// Cut the store into chunks of roughly [`chunk_vertices`] input vertices and send them on.
119///
120/// The cut is a function of the feature stream alone — not of the thread count, not of how fast the
121/// workers drain — so two runs chunk identically even before the merge makes the boundaries
122/// invisible.
123///
124/// A feature below the zoom's own floor never arrives: [`crate::store::ZoomReader`] drops it in one
125/// of its prefetch lanes. That filter used to be right here, and here it was one thread discarding
126/// most of a billion features — see the reader's own docs for what that cost.
127#[cfg(test)]
128mod tests_part1 {
129 use super::*;
130
131 fn empty_entry(id: u64) -> Encoded {
132 (id, None, crate::rings::Stats::default(), crate::coalesce::Stats::default())
133 }
134
135 fn stored_entry(id: u64) -> Encoded {
136 (
137 id,
138 Some((vec![7u8; 32], 32, tilecodec::mamaps::write::hash64(&[7u8; 32]))),
139 crate::rings::Stats::default(),
140 crate::coalesce::Stats::default(),
141 )
142 }
143
144 fn ids_of(done: &[Encoded]) -> Vec<u64> {
145 done.iter().map(|(id, _, _, _)| *id).collect()
146 }
147
148 /// **Phase B subtree pruning: four empty siblings end the tree at the parent.**
149 /// All four children of one z12 parent arrive `None` in one batch: all four are
150 /// dropped, so the reader stops at the z11 parent (overzoom) instead of fetching
151 /// four empty bodies.
152 #[test]
153 fn four_empty_siblings_are_pruned_to_the_parent() {
154 use tilecodec::pmtiles::tile_id;
155 let (px, py) = (1_200u64, 1_500u64);
156 let z = 12u8;
157 let mut done = vec![
158 empty_entry(tile_id(z, px * 2, py * 2)),
159 empty_entry(tile_id(z, px * 2 + 1, py * 2)),
160 empty_entry(tile_id(z, px * 2, py * 2 + 1)),
161 empty_entry(tile_id(z, px * 2 + 1, py * 2 + 1)),
162 ];
163 prune_barren_subtree(z, &mut done);
164 assert!(done.is_empty(), "all four empty siblings must go: {done:?}");
165 }
166
167 /// **A stored sibling vetoes the prune.** One child carries drawable content, so the
168 /// parent cannot cover the set — dropping the other three would delete the map's
169 /// answer for their ground (the reader would overzoom a parent that draws coarsely).
170 #[test]
171 fn a_stored_sibling_vetoes_the_prune() {
172 use tilecodec::pmtiles::tile_id;
173 let (px, py) = (1_200u64, 1_500u64);
174 let z = 12u8;
175 let mut done = vec![
176 empty_entry(tile_id(z, px * 2, py * 2)),
177 stored_entry(tile_id(z, px * 2 + 1, py * 2)),
178 empty_entry(tile_id(z, px * 2, py * 2 + 1)),
179 empty_entry(tile_id(z, px * 2 + 1, py * 2 + 1)),
180 ];
181 prune_barren_subtree(z, &mut done);
182 assert_eq!(done.len(), 4, "a stored child keeps the whole set");
183 }
184
185 /// **A partial set never prunes.** The parent split across a batch boundary keeps its
186 /// children: the archive must not depend on where the cost-batcher cut, and three
187 /// empties cannot prove the fourth is barren.
188 #[test]
189 fn a_partial_child_set_never_prunes() {
190 use tilecodec::pmtiles::tile_id;
191 let (px, py) = (1_200u64, 1_500u64);
192 let z = 12u8;
193 let mut done = vec![
194 empty_entry(tile_id(z, px * 2, py * 2)),
195 empty_entry(tile_id(z, px * 2 + 1, py * 2)),
196 empty_entry(tile_id(z, px * 2, py * 2 + 1)),
197 ];
198 prune_barren_subtree(z, &mut done);
199 assert_eq!(done.len(), 3, "a split parent keeps its children");
200 }
201
202 /// **z0 never prunes.** The world tile has no parent to overzoom to; dropping it
203 /// would delete the map's coarsest answer.
204 #[test]
205 fn the_world_tile_is_never_pruned() {
206 use tilecodec::pmtiles::tile_id;
207 let mut done = vec![
208 empty_entry(tile_id(0, 0, 0)),
209 empty_entry(tile_id(0, 1, 0)),
210 empty_entry(tile_id(0, 0, 1)),
211 empty_entry(tile_id(0, 1, 1)),
212 ];
213 let before = ids_of(&done);
214 prune_barren_subtree(0, &mut done);
215 assert_eq!(ids_of(&done), before, "z0 keeps everything");
216 }
217
218 /// **Unrelated tiles are untouched.** A batch of four empties from different parents
219 /// prunes nothing — the check is per-parent, not per-batch.
220 #[test]
221 fn empties_from_different_parents_do_not_prune() {
222 use tilecodec::pmtiles::tile_id;
223 let z = 12u8;
224 let mut done = vec![
225 empty_entry(tile_id(z, 0, 0)),
226 empty_entry(tile_id(z, 100, 100)),
227 empty_entry(tile_id(z, 200, 200)),
228 empty_entry(tile_id(z, 300, 300)),
229 ];
230 prune_barren_subtree(z, &mut done);
231 assert_eq!(done.len(), 4, "no parent has its full set here");
232 }
233}