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

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

pyramid_part6.rs443 lines · 17.9 KiBRaw
1
2 #[test]
3 fn one_feature_too_big_for_the_budget_is_kept_and_reported() {
4 // An empty tile is a hole in the map; an oversized one is merely slow.
5 let long: Vec<(f64, f64)> = (0..4000)
6 .map(|i| (-122.42 + (i % 97) as f64 * 0.0001, 37.77 + (i % 89) as f64 * 0.0001))
7 .collect();
8 let features = vec![line(&long, vec![("name", Value::String("wiggly".into()))])];
9 let mut opts = Options::new("l", 14, 14);
10 opts.max_tile_bytes = 50;
11 let (bytes, report) = build_archive(&features, &opts).unwrap();
12 assert!(report[0].over_budget > 0, "{:?}", report[0]);
13 assert!(report[0].kept > 0, "the tile must not be empty");
14 let a = Archive::parse(&bytes).unwrap();
15 assert!(a.header.addressed_tiles > 0);
16 }
17
18 #[test]
19 fn the_drop_policy_is_deterministic_under_a_tight_budget() {
20 let features: Vec<Feature> = (0..300)
21 .map(|i| {
22 let d = i as f64 * 0.00003;
23 line(
24 &[(-122.40 + d, 37.80), (-122.3995 + d, 37.8005)],
25 vec![("name", Value::String(format!("f{i}")))],
26 )
27 })
28 .collect();
29 let mut opts = Options::new("l", 11, 11);
30 opts.max_tile_bytes = 700;
31 let (a, ra) = build_archive(&features, &opts).unwrap();
32 let (b, rb) = build_archive(&features, &opts).unwrap();
33 assert_eq!(a, b);
34 assert_eq!(ra, rb);
35 assert!(ra[0].dropped > 0, "the test is only meaningful if it dropped");
36 }
37
38 #[test]
39 fn simplification_thins_the_shallow_zooms_and_spares_the_deepest() {
40 // A wiggly line: at maxzoom the tolerance is zero, so every vertex the clip
41 // left must still be there; below it, fewer.
42 let coords: Vec<(f64, f64)> = (0..300)
43 .map(|i| (-122.45 + i as f64 * 0.0002, 37.80 + (i % 2) as f64 * 0.00005))
44 .collect();
45 let (bytes, _) = build_archive(&[line(&coords, vec![])], &Options::new("l", 8, 12)).unwrap();
46 let a = Archive::parse(&bytes).unwrap();
47 let vertices_at = |z: u8| -> usize {
48 let mut n = 0;
49 for (id, raw) in a.iter_tiles().unwrap() {
50 if pmtiles::tile_zxy(id).0 != z {
51 continue;
52 }
53 let tile = Tile::decode(&crate::gz::decompress(raw).unwrap()).unwrap();
54 for f in &tile.layer("l").unwrap().features {
55 n += mvt::decode_lines(&f.geometry)
56 .map(|ls| ls.iter().map(|l| l.len()).sum::<usize>())
57 .unwrap_or(0);
58 }
59 }
60 n
61 };
62 let deep = vertices_at(12);
63 let shallow = vertices_at(8);
64 assert!(deep > 0 && shallow > 0);
65 assert!(
66 shallow < deep,
67 "z8 kept {shallow} vertices and z12 kept {deep}; simplification did nothing"
68 );
69 }
70
71 #[test]
72 fn features_that_clip_away_entirely_are_not_counted_as_drops() {
73 // Two features far apart: each tile sees one of them, and the other's
74 // absence is a clip, not a budget decision.
75 let features = vec![
76 line(&[(-122.42, 37.77), (-122.41, 37.78)], vec![]),
77 line(&[(-74.01, 40.71), (-74.00, 40.72)], vec![]),
78 ];
79 let (_, report) = build_archive(&features, &Options::new("l", 12, 12)).unwrap();
80 assert_eq!(report[0].dropped, 0, "{:?}", report[0]);
81 assert_eq!(report[0].kept, report[0].placed);
82 }
83
84 #[test]
85 fn an_empty_input_produces_an_empty_but_valid_archive() {
86 let (bytes, report) = build_archive(&[], &Options::new("l", 10, 12)).unwrap();
87 let a = Archive::parse(&bytes).unwrap();
88 assert_eq!(a.header.addressed_tiles, 0);
89 assert!(report.iter().all(|s| s.tiles == 0));
90 }
91
92 #[test]
93 fn bad_options_are_refused() {
94 let features = vec![line(&[(0.0, 0.0), (1.0, 1.0)], vec![])];
95 let mut opts = Options::new("l", 12, 10);
96 assert!(build_archive(&features, &opts).is_err(), "minzoom above maxzoom");
97 opts = Options::new("l", 10, 12);
98 opts.extent = 0;
99 assert!(build_archive(&features, &opts).is_err(), "extent 0");
100 }
101
102 #[test]
103 fn the_report_prints_one_row_per_zoom() {
104 let (_, report) = build_archive(
105 &[line(&[(-122.42, 37.77), (-122.41, 37.78)], vec![])],
106 &Options::new("l", 10, 11),
107 )
108 .unwrap();
109 let mut out = Vec::new();
110 print_report(&report, &mut out).unwrap();
111 let text = String::from_utf8(out).unwrap();
112 assert!(text.contains("z10"), "{text}");
113 assert!(text.contains("z11"), "{text}");
114 }
115
116 // --- the streaming producer --------------------------------------------
117 //
118 // `build_archive` is covered by every test above, so pinning the streaming producer
119 // against it byte for byte inherits all of it -- the drop policy, the importance
120 // order, the simplification, the header, the deduplication, the run coalescing and
121 // without restating any of it.
122
123 struct Scratch(std::path::PathBuf);
124
125 impl Scratch {
126 fn new(name: &str) -> Scratch {
127 let d = std::env::temp_dir().join(format!(
128 "tb_pyr_{}_{name}_{:?}",
129 std::process::id(),
130 std::thread::current().id()
131 ));
132 let _ = std::fs::remove_dir_all(&d);
133 std::fs::create_dir_all(&d).unwrap();
134 Scratch(d)
135 }
136 }
137
138 impl Drop for Scratch {
139 fn drop(&mut self) {
140 let _ = std::fs::remove_dir_all(&self.0);
141 }
142 }
143
144 /// Drive both producers from one `Vec<Feature>` and return the streamed bytes.
145 ///
146 /// Asserts the archive bytes AND the `ZoomStats` are equal, and that nothing was
147 /// left behind in the scratch directory -- a stranded per-zoom bucket set would make
148 /// peak disk the SUM of the zooms rather than the largest one.
149 fn assert_identical(
150 name: &str,
151 features: &[Feature],
152 opts: &Options,
153 limits: &StreamLimits,
154 ) -> Vec<u8> {
155 let scratch = Scratch::new(name);
156 let (want_bytes, want_report) = build_archive(features, opts).unwrap();
157
158 let out = scratch.0.join("streamed.pmtiles");
159 let mut src = SliceSource::new(features);
160 let got_report = build_archive_to(&out, &scratch.0, opts, &mut src, limits).unwrap();
161 let got_bytes = std::fs::read(&out).unwrap();
162
163 assert_eq!(got_report, want_report, "{name}: the per-zoom reports differ");
164 assert_eq!(
165 got_bytes.len(),
166 want_bytes.len(),
167 "{name}: streamed {} bytes, in-memory {}",
168 got_bytes.len(),
169 want_bytes.len()
170 );
171 assert!(
172 got_bytes == want_bytes,
173 "{name}: the two archives differ byte for byte"
174 );
175
176 let leftovers: Vec<String> = std::fs::read_dir(&scratch.0)
177 .unwrap()
178 .filter_map(|e| e.ok())
179 .map(|e| e.file_name().to_string_lossy().into_owned())
180 .filter(|n| n != "streamed.pmtiles")
181 .collect();
182 assert!(
183 leftovers.is_empty(),
184 "{name}: the spill was left behind: {leftovers:?}"
185 );
186 assert!(
187 !out.with_extension("pmtiles.tiledata").exists(),
188 "{name}: the writer's scratch was left behind"
189 );
190 got_bytes
191 }
192
193 /// A fixture covering every branch the two producers could disagree on: a line
194 /// spanning many tiles, a polygon with a hole, and two features with identical
195 /// geometry so the `seq` tie-break in the importance order has to decide between
196 /// them.
197 fn mixed_fixture() -> Vec<Feature> {
198 let mut features = vec![
199 // Long enough at z11-12 to land in many tiles, which is what makes the
200 // bucket partition non-trivial.
201 line(&[(-124.0, 42.0), (-114.0, 33.0)], vec![("id", Value::Uint(0))]),
202 square(-122.5, 37.7, 0.4, "A"),
203 ];
204 // A polygon with a hole.
205 features.push(Feature {
206 geometry: Geometry::Polygons(vec![vec![
207 vec![
208 (-122.5, 37.7),
209 (-122.3, 37.7),
210 (-122.3, 37.9),
211 (-122.5, 37.9),
212 (-122.5, 37.7),
213 ],
214 vec![
215 (-122.45, 37.75),
216 (-122.35, 37.75),
217 (-122.35, 37.85),
218 (-122.45, 37.85),
219 (-122.45, 37.75),
220 ],
221 ]]),
222 props: vec![("name".to_string(), Value::String("holey".into()))],
223 });
224 // Two identical geometries: tied on `extent_of`, so only `seq` orders them.
225 for k in 0..2 {
226 features.push(line(
227 &[(-122.42, 37.77), (-122.40, 37.79)],
228 vec![("tied", Value::Uint(k))],
229 ));
230 }
231 features
232 }
233
234 #[test]
235 fn the_streaming_producer_is_byte_identical_to_the_in_memory_one() {
236 let features = mixed_fixture();
237 let opts = Options::new("l", 10, 12);
238 assert_identical("mixed", &features, &opts, &StreamLimits::default());
239 }
240
241 /// The drop policy is where the two could diverge without the output looking wrong,
242 /// so it gets a budget tight enough to bite.
243 #[test]
244 fn the_streaming_producer_matches_under_a_tight_tile_budget() {
245 let mut features = vec![line(
246 &[(-122.45, 37.75), (-122.35, 37.85)],
247 vec![("id", Value::String("long".into()))],
248 )];
249 for i in 0..200 {
250 let d = i as f64 * 0.00005;
251 features.push(line(
252 &[(-122.40 + d, 37.80), (-122.3999 + d, 37.8001)],
253 vec![("id", Value::String(format!("short{i}")))],
254 ));
255 }
256 let mut opts = Options::new("l", 11, 11);
257 opts.max_tile_bytes = 400;
258 let (_, report) = build_archive(&features, &opts).unwrap();
259 assert!(report[0].dropped > 0, "the fixture must drop: {:?}", report[0]);
260 assert_identical("tight", &features, &opts, &StreamLimits::default());
261 }
262
263 /// The `over_budget` path: one feature that does not fit is kept anyway, and both
264 /// producers must keep the same one and report it the same way.
265 #[test]
266 fn the_streaming_producer_matches_when_a_single_feature_is_over_budget() {
267 let long: Vec<(f64, f64)> = (0..4000)
268 .map(|i| (-122.42 + (i % 97) as f64 * 0.0001, 37.77 + (i % 89) as f64 * 0.0001))
269 .collect();
270 let features = vec![line(&long, vec![("name", Value::String("wiggly".into()))])];
271 let mut opts = Options::new("l", 14, 14);
272 opts.max_tile_bytes = 50;
273 let (_, report) = build_archive(&features, &opts).unwrap();
274 assert!(report[0].over_budget > 0, "the fixture must be over budget");
275 assert_identical("overbudget", &features, &opts, &StreamLimits::default());
276 }
277
278 /// Re-partitioning a dense bucket is the expected path at planet scale, not an
279 /// exotic one, so it gets its own byte-identity check rather than being trusted.
280 ///
281 /// Four buckets per level and a budget far below one zoom's spill forces recursion
282 /// all the way down to single-tile ranges; the archive must not move by a byte.
283 #[test]
284 fn re_partitioning_does_not_perturb_a_byte() {
285 let features = mixed_fixture();
286 let opts = Options::new("l", 10, 12);
287 let limits = StreamLimits {
288 buckets: 4,
289 // Well under one zoom's total spill and comfortably above one tile's, which
290 // is what makes this a recursion test rather than an error test.
291 bucket_budget_bytes: 2_000,
292 max_repartition_depth: DEFAULT_MAX_REPARTITION_DEPTH,
293 };
294 assert_identical("recursion", &features, &opts, &limits);
295 }
296
297 /// The fixture whose drop policy actually bites: one long feature plus 200 short
298 /// ones, at a budget that cannot hold them all.
299 fn tight_fixture() -> Vec<Feature> {
300 let mut features = vec![line(
301 &[(-122.45, 37.75), (-122.35, 37.85)],
302 vec![("id", Value::String("long".into()))],
303 )];
304 for i in 0..200 {
305 let d = i as f64 * 0.00005;
306 features.push(line(
307 &[(-122.40 + d, 37.80), (-122.3999 + d, 37.8001)],
308 vec![("id", Value::String(format!("short{i}")))],
309 ));
310 }
311 features
312 }
313
314 /// The gate for threading the tilers: the thread count must change only how fast
315 /// they run.
316 ///
317 /// Both producers, at 1, 2, 3 and 32 threads, against the serial result. Three is
318 /// there on purpose — counts that divide neither the bucket count (256, or 4 in the
319 /// recursion case) nor the batch length are the ones that catch an off-by-one in a
320 /// chunked fold, and a count above the core count catches an ordering bug that a
321 /// saturated pool would hide.
322 ///
323 /// Run over three cases, because they are three different code paths: the flat
324 /// partition, the recursing one, and a budget tight enough that the drop policy
325 /// runs — the last being the only one where a perturbed candidate order changes
326 /// which features survive rather than merely where they land.
327 #[test]
328 fn the_thread_count_changes_no_bytes() {
329 let recursing = StreamLimits {
330 buckets: 4,
331 bucket_budget_bytes: 2_000,
332 max_repartition_depth: DEFAULT_MAX_REPARTITION_DEPTH,
333 };
334 let mut tight_opts = Options::new("l", 11, 11);
335 tight_opts.max_tile_bytes = 400;
336
337 let cases: Vec<(&str, Vec<Feature>, Options, StreamLimits)> = vec![
338 (
339 "flat",
340 mixed_fixture(),
341 Options::new("l", 10, 12),
342 StreamLimits::default(),
343 ),
344 (
345 "recursing",
346 mixed_fixture(),
347 Options::new("l", 10, 12),
348 recursing,
349 ),
350 (
351 "tight",
352 tight_fixture(),
353 tight_opts,
354 StreamLimits::default(),
355 ),
356 ];
357
358 for (tag, features, opts, limits) in cases {
359 let run = |n: usize| {
360 par::set_threads(n);
361 let scratch = Scratch::new(&format!("threads_{tag}_{n}"));
362 let (mem, mem_report) = build_archive(&features, &opts).unwrap();
363 let out = scratch.0.join("streamed.pmtiles");
364 let mut src = SliceSource::new(&features);
365 let stream_report =
366 build_archive_to(&out, &scratch.0, &opts, &mut src, &limits).unwrap();
367 (mem, mem_report, std::fs::read(&out).unwrap(), stream_report)
368 };
369
370 let (base_mem, base_mem_report, base_stream, base_stream_report) = run(1);
371 // The property the whole crate rests on, restated at one thread so a
372 // failure below cannot be blamed on the producers disagreeing.
373 assert!(base_mem == base_stream, "{tag}: the producers disagree serially");
374
375 for n in [2, 3, 32] {
376 let (mem, mem_report, stream, stream_report) = run(n);
377 assert_eq!(
378 mem_report, base_mem_report,
379 "{tag}: {n} threads changed the in-memory report"
380 );
381 assert_eq!(
382 stream_report, base_stream_report,
383 "{tag}: {n} threads changed the streamed report"
384 );
385 assert!(
386 mem == base_mem,
387 "{tag}: {n} threads perturbed the in-memory archive"
388 );
389 assert!(
390 stream == base_stream,
391 "{tag}: {n} threads perturbed the streamed archive"
392 );
393 }
394 }
395 par::clear_threads();
396 }
397
398 /// An unsplittable group over budget errors, naming the tile, rather than being
399 /// loaded and killed by the OOM reaper. Capping candidates per tile instead would
400 /// change which features survive, which is an output change.
401 #[test]
402 fn an_unsplittable_over_budget_tile_group_is_named_in_the_error() {
403 let scratch = Scratch::new("unsplittable");
404 let long: Vec<(f64, f64)> = (0..4000)
405 .map(|i| (-122.42 + (i % 97) as f64 * 0.0001, 37.77 + (i % 89) as f64 * 0.0001))
406 .collect();
407 let features = vec![line(&long, vec![("name", Value::String("wiggly".into()))])];
408 let opts = Options::new("l", 14, 14);
409 let limits = StreamLimits {
410 buckets: 4,
411 bucket_budget_bytes: 64,
412 max_repartition_depth: DEFAULT_MAX_REPARTITION_DEPTH,
413 };
414 let mut src = SliceSource::new(&features);
415 let e = build_archive_to(
416 scratch.0.join("out.pmtiles"),
417 &scratch.0,
418 &opts,
419 &mut src,
420 &limits,
421 )
422 .expect_err("an unsplittable over-budget group must error");
423 let msg = e.to_string();
424 assert!(msg.contains("z14/"), "the error must name the tile: {msg}");
425 assert!(msg.contains("spill record(s)"), "and the record count: {msg}");
426 assert!(
427 msg.contains("--bucket-budget-bytes"),
428 "and what to do about it: {msg}"
429 );
430 }
431
432 /// An empty input is what catches the `Builder`/`StreamBuilder` default-bounds
433 /// divergence: nothing overwrites the latitude fields, and they differ by three
434 /// units between the two writers.
435 #[test]
436 fn an_empty_input_streams_to_an_empty_but_valid_archive() {
437 let opts = Options::new("l", 10, 12);
438 let bytes = assert_identical("empty", &[], &opts, &StreamLimits::default());
439 let a = Archive::parse(&bytes).unwrap();
440 assert_eq!(a.header.addressed_tiles, 0);
441 assert_eq!(a.header.min_lat_e7, -850_511_290, "Builder's default, not StreamBuilder's");
442 assert_eq!(a.header.max_lat_e7, 850_511_290);
443 }