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

Modern-Apps.git / scripts / maps / tile_build / src / pyramid_part2.rs

pyramid_part2.rs325 lines · 12.4 KiBRaw
1/// Read serially, project and clip across the pool, push serially.
2///
3/// The fallback shape, for a source that is only a cursor. Everything between the read
4/// and the write -- projection, clipping, simplification, record encoding -- is
5/// per-feature pure and is where the time goes, so that part threads; the read does not.
6/// Live memory is one batch's records, which is what bounds the batch.
7#[allow(clippy::too_many_arguments)]
8fn bucket_serial(
9 src: &mut impl FeatureSource,
10 z: u8,
11 opts: &Options,
12 buffer: f64,
13 tolerance: f64,
14 set: &mut spill::BucketSet,
15 bar: &mut Progress,
16) -> Result<()> {
17 let mut rec = Vec::new();
18 let mut seq = 0u64;
19 let batch_len = par::batch_len();
20 let mut batch: Vec<Feature> = Vec::with_capacity(batch_len);
21 loop {
22 batch.clear();
23 while batch.len() < batch_len {
24 match src.next()? {
25 Some(f) => batch.push(f),
26 None => break,
27 }
28 }
29 if batch.is_empty() {
30 break;
31 }
32 let first = seq;
33 let encoded: Vec<Result<BucketedFeature>> = if batch.len() == 1 {
34 // One feature is not worth a pool round trip, and this is the path the
35 // single-threaded case and the tail of every stream take.
36 vec![bucket_feature(
37 &batch[0].geometry,
38 &batch[0].props,
39 first,
40 z,
41 opts,
42 buffer,
43 tolerance,
44 &mut rec,
45 )]
46 } else {
47 par::install(|| {
48 batch
49 .par_iter()
50 .enumerate()
51 .with_min_len(par::min_task_len(batch.len()))
52 .map_init(Vec::new, |rec, (i, f)| {
53 bucket_feature(
54 &f.geometry,
55 &f.props,
56 first + i as u64,
57 z,
58 opts,
59 buffer,
60 tolerance,
61 rec,
62 )
63 })
64 .collect()
65 })
66 };
67 for one in encoded {
68 let one = one?;
69 for &(id, at, len) in &one.spans {
70 set.push(id, &one.blob[at..at + len])?;
71 }
72 bar.tick(BUCKETED);
73 }
74 seq += batch.len() as u64;
75 }
76 Ok(())
77}
78
79/// Read, decode, project and clip across the pool; push serially.
80///
81/// The production shape. The serial path's remaining bottleneck was `src.next()`: it
82/// decodes a geometry and a property vector per feature, allocating both, and does so
83/// once per zoom on whichever single thread owns the cursor while the pool waits. Here a
84/// worker takes a whole chunk, reads its byte range positionally, and decodes it itself,
85/// so the decode scales with the pool and the pass no longer has a serial middle.
86///
87/// Chunk `c` starts at feature `c * NORM_CHUNK_FEATURES` by construction of the index,
88/// which is what lets this reproduce the sequential path's `seq` exactly rather than
89/// approximately.
90#[allow(clippy::too_many_arguments)]
91fn bucket_chunked(
92 chunks: &spill::NormalizedChunks,
93 z: u8,
94 opts: &Options,
95 buffer: f64,
96 tolerance: f64,
97 set: &mut spill::BucketSet,
98 bar: &mut Progress,
99) -> Result<()> {
100 // One chunk per task, and as many chunks per batch as the serial path holds
101 // features, so peak live memory is unchanged: a batch's encoded records bound it
102 // either way.
103 let per_batch = (par::batch_len() / spill::NORM_CHUNK_FEATURES as usize).max(1);
104 let total = chunks.chunk_count();
105 let mut ids: Vec<usize> = Vec::with_capacity(per_batch);
106 let mut at = 0usize;
107 while at < total {
108 let end = (at + per_batch).min(total);
109 ids.clear();
110 ids.extend(at..end);
111 let encoded: Vec<Result<Vec<BucketedFeature>>> = par::install(|| {
112 ids.par_iter()
113 .with_min_len(par::min_task_len(ids.len()))
114 .map_init(
115 || (Vec::new(), Vec::new(), Vec::new()),
116 |(scratch, feats, rec), &ci| {
117 chunks.read_into(ci, scratch, feats)?;
118 let first = ci as u64 * spill::NORM_CHUNK_FEATURES;
119 let mut out = Vec::with_capacity(feats.len());
120 for (j, f) in feats.iter().enumerate() {
121 out.push(bucket_feature(
122 &f.geometry,
123 &f.props,
124 first + j as u64,
125 z,
126 opts,
127 buffer,
128 tolerance,
129 rec,
130 )?);
131 }
132 Ok(out)
133 },
134 )
135 .collect()
136 });
137 for one in encoded {
138 for f in one? {
139 for &(id, o, len) in &f.spans {
140 set.push(id, &f.blob[o..o + len])?;
141 }
142 bar.tick(BUCKETED);
143 }
144 }
145 at = end;
146 }
147 Ok(())
148}
149
150/// Build the archive straight to `out`, with peak memory set by the tile count.
151///
152/// The same drop policy, the same encoder and the same [`ZoomStats`] as
153/// [`build_archive`] — which stays as the oracle the byte-identity tests pin this
154/// against — but nothing proportional to the input bytes is ever resident. Per zoom:
155///
156/// 1. **The bucket pass** rewinds `src`, projects each feature once, finds the tiles it
157/// touches, and for each of them clips, moves into the tile and simplifies, writing a
158/// [`crate::spill`] record. Empties are skipped exactly as [`build_archive`] skips
159/// them, so `placed` counts the same things.
160/// 2. **The encode pass** walks the buckets in ascending index, re-partitioning any that
161/// exceed the budget, and for each loaded bucket sorts by `(tile_id, importance)`,
162/// groups runs of equal `tile_id`, and calls the same [`fit_tile`].
163///
164/// The bucket set is dropped at the end of each zoom, so peak spill disk is the largest
165/// SINGLE zoom rather than the sum of them — `tile_id` is zoom-major, so every id at
166/// `z` precedes every id at `z+1` and a zoom can be finished before the next begins.
167///
168/// I/O, with `F` the source, `S_z` a zoom's spill, `T` the archive and `Z` zooms:
169/// `read(F) · Z + write(S_z) + read(S_z)` per zoom, plus `3·T` for the writer's scratch
170/// round trip. Disk peak is `F + max(S_z) + T`, plus one full copy of an over-budget
171/// bucket per level of re-partition below it — an ancestor set's files stay alive while
172/// its children are drained, so a heavily skewed metro range costs
173/// `depth × that bucket's bytes` on top.
174pub fn build_archive_to(
175 out: impl AsRef<Path>,
176 scratch_dir: impl AsRef<Path>,
177 opts: &Options,
178 src: &mut impl FeatureSource,
179 limits: &StreamLimits,
180) -> Result<Vec<ZoomStats>> {
181 if opts.min_zoom > opts.max_zoom {
182 return err("minzoom is above maxzoom");
183 }
184 if opts.extent == 0 {
185 return err("extent 0");
186 }
187 // This path needs `zoom_base(max_zoom + 1)` for the bucket range, which
188 // `build_archive` never computes and which overflows above z30. Refused rather than
189 // left to panic: the in-memory path merely produces nonsense that deep, and a
190 // message is a better failure than a shift overflow.
191 if opts.max_zoom > 30 {
192 return err(format!(
193 "maxzoom {} is above 30, the deepest zoom a PMTiles tile id is exact at",
194 opts.max_zoom
195 ));
196 }
197 let out = out.as_ref();
198 let scratch_dir = scratch_dir.as_ref();
199 std::fs::create_dir_all(scratch_dir)
200 .map_err(|e| Error(format!("cannot create {}: {e}", scratch_dir.display())))?;
201
202 let geom_type = geom_type_of(src.geom_kind());
203 let buffer = geom::buffer_for(opts.extent);
204
205 // Beside the OUTPUT, not in the spill directory: `finish` copies this section into
206 // the archive, and a cross-filesystem copy of 40 GB would be needlessly slow.
207 let tile_scratch = {
208 let mut p = out.as_os_str().to_owned();
209 p.push(".tiledata");
210 std::path::PathBuf::from(p)
211 };
212 let mut builder = pmtiles::StreamBuilder::new(tile_scratch)?;
213 builder.min_zoom = opts.min_zoom;
214 builder.max_zoom = opts.max_zoom;
215 builder.center_zoom = opts.min_zoom;
216 builder.metadata = metadata(&opts.layer, opts.min_zoom, opts.max_zoom).into_bytes();
217 match src.bounds() {
218 Some(b) => {
219 builder.min_lon_e7 = e7(b.min_x);
220 builder.min_lat_e7 = e7(b.min_y);
221 builder.max_lon_e7 = e7(b.max_x);
222 builder.max_lat_e7 = e7(b.max_y);
223 builder.center_lon_e7 = e7((b.min_x + b.max_x) / 2.0);
224 builder.center_lat_e7 = e7((b.min_y + b.max_y) / 2.0);
225 }
226 // `Builder::new` defaults latitude to +/-850_511_290 and `StreamBuilder::new` to
227 // +/-850_511_287. Three units, and on an input with no bounds nothing else
228 // overwrites them -- so leaving them alone would make the two producers disagree
229 // on an empty archive's header.
230 None => {
231 builder.min_lon_e7 = -1_800_000_000;
232 builder.min_lat_e7 = -850_511_290;
233 builder.max_lon_e7 = 1_800_000_000;
234 builder.max_lat_e7 = 850_511_290;
235 }
236 }
237
238 let mut report = Vec::new();
239 for z in opts.min_zoom..=opts.max_zoom {
240 let mut stats = ZoomStats { zoom: z, ..Default::default() };
241 let tolerance = simplify::tolerance_for(z, opts.max_zoom, opts.simplification);
242
243 // Named per zoom so a set cannot be mistaken for the previous zoom's, and
244 // scoped to the zoom so its files go before the next one allocates disk.
245 let mut set = spill::BucketSet::new(
246 scratch_dir,
247 &format!("z{z}"),
248 pmtiles::zoom_base(z),
249 pmtiles::zoom_base(z + 1),
250 limits.buckets,
251 )?;
252
253 src.rewind()?;
254 let mut bar = Progress::new(
255 format!("{} z{z} bucket", opts.layer),
256 src.len() as usize,
257 BUCKETED,
258 opts.progress,
259 );
260 let phase = std::time::Instant::now();
261 bucket_pass(src, z, opts, buffer, tolerance, &mut set, &mut bar)?;
262 bar.finish(BUCKETED);
263 let bucketed_in = phase.elapsed();
264 set.seal()?;
265 let phase = std::time::Instant::now();
266
267 let mut bar = Progress::new(
268 format!("{} z{z} encode", opts.layer),
269 set.total_records() as usize,
270 ENCODED,
271 opts.progress,
272 );
273 let mut prof = EncodeProfile::default();
274 encode_buckets(
275 &set,
276 scratch_dir,
277 z,
278 0,
279 opts,
280 geom_type,
281 limits,
282 &mut builder,
283 &mut stats,
284 &mut bar,
285 &mut prof,
286 )?;
287 bar.finish(ENCODED);
288 if opts.timing {
289 let (_, x, y) = pmtiles::tile_zxy(prof.max_group_id);
290 use std::sync::atomic::Ordering::Relaxed;
291 let mvt_s = MVT_NANOS.swap(0, Relaxed) as f64 / 1e9;
292 let gz_s = GZIP_NANOS.swap(0, Relaxed) as f64 / 1e9;
293 eprintln!(
294 " z{z}: bucket {:.1}s [{:.0}s CPU], encode {:.1}s [mvt {:.0}s + gzip \
295 {:.0}s of CPU across all workers] ({} record(s), {} tile(s), biggest \
296 z{z}/{x}/{y} with {} candidate(s) = {:.1}%)",
297 bucketed_in.as_secs_f64(),
298 BUCKET_NANOS.swap(0, Relaxed) as f64 / 1e9,
299 phase.elapsed().as_secs_f64(),
300 mvt_s,
301 gz_s,
302 set.total_records(),
303 prof.groups,
304 prof.max_group,
305 prof.max_group as f64 / set.total_records().max(1) as f64 * 100.0,
306 );
307 }
308 report.push(stats);
309 }
310
311 builder.finish(out)?;
312 Ok(report)
313}
314
315/// What the encode pass spent its time on, for `--timing`.
316///
317/// The interesting number is the LARGEST group: the encode pass parallelises across
318/// tiles, so one tile holding a large fraction of a zoom's records sets a floor no
319/// thread count can get under.
320#[derive(Default)]
321struct EncodeProfile {
322 groups: usize,
323 max_group: usize,
324 max_group_id: u64,
325}