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

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

spill_part3.rs492 lines · 19.2 KiBRaw
1 use super::*;
2
3 fn tmp(name: &str) -> PathBuf {
4 let d = std::env::temp_dir().join(format!(
5 "tb_spill_{}_{name}_{:?}",
6 std::process::id(),
7 std::thread::current().id()
8 ));
9 let _ = std::fs::remove_dir_all(&d);
10 std::fs::create_dir_all(&d).unwrap();
11 d
12 }
13
14 fn every_value() -> Vec<(String, Value)> {
15 vec![
16 ("s".to_string(), Value::String("héllo, wörld".into())),
17 ("f".to_string(), Value::Float(1.5)),
18 ("d".to_string(), Value::Double(-2.25)),
19 ("i".to_string(), Value::Int(-7)),
20 ("u".to_string(), Value::Uint(9)),
21 ("si".to_string(), Value::SInt(-11)),
22 ("bt".to_string(), Value::Bool(true)),
23 ("bf".to_string(), Value::Bool(false)),
24 ("empty".to_string(), Value::String(String::new())),
25 ]
26 }
27
28 fn every_int_geometry() -> Vec<IntGeometry> {
29 vec![
30 IntGeometry::Points(vec![]),
31 IntGeometry::Points(vec![(0, 0), (-5, 4096), (i32::MIN, i32::MAX)]),
32 IntGeometry::Lines(vec![]),
33 IntGeometry::Lines(vec![vec![(1, 2), (3, 4)], vec![], vec![(9, -9)]]),
34 IntGeometry::Polygons(vec![]),
35 IntGeometry::Polygons(vec![
36 // Exterior plus a hole, which is the shape a real admin polygon has.
37 vec![
38 vec![(0, 0), (10, 0), (10, 10), (0, 10), (0, 0)],
39 vec![(2, 2), (8, 2), (8, 8), (2, 8), (2, 2)],
40 ],
41 vec![vec![(20, 20), (30, 20), (30, 30), (20, 20)]],
42 ]),
43 ]
44 }
45
46 /// Every geometry variant and every `mvt::Value` must survive the round trip. A
47 /// value type that spilled wrongly would reach the encoder as a different property
48 /// and nothing between here and the rendered tile would notice.
49 #[test]
50 fn a_record_round_trips_for_every_geometry_and_every_value() {
51 let dir = tmp("roundtrip");
52 for (n, geom) in every_int_geometry().into_iter().enumerate() {
53 let rec = SpillRecord {
54 tile_id: 5 + n as u64,
55 seq: 42 + n as u64,
56 extent: -1234,
57 geom,
58 props: every_value(),
59 };
60 let bytes = rec.to_bytes().unwrap();
61 assert_eq!(
62 bytes.len(),
63 u32::from_le_bytes(bytes[0..4].try_into().unwrap()) as usize,
64 "rec_len must be the whole record"
65 );
66
67 let mut set = BucketSet::new(&dir, &format!("rt{n}"), 0, 64, 1).unwrap();
68 set.push(rec.tile_id, &bytes).unwrap();
69 set.seal().unwrap();
70 assert_eq!(set.load(0).unwrap(), vec![rec], "variant {n}");
71 }
72 }
73
74 #[test]
75 fn a_truncated_record_errors_rather_than_decoding() {
76 let dir = tmp("truncated");
77 let rec = SpillRecord {
78 tile_id: 1,
79 seq: 0,
80 extent: 0,
81 geom: IntGeometry::Lines(vec![vec![(1, 1), (2, 2), (3, 3)]]),
82 props: every_value(),
83 };
84 let bytes = rec.to_bytes().unwrap();
85
86 let mut set = BucketSet::new(&dir, "t", 0, 64, 1).unwrap();
87 set.push(1, &bytes).unwrap();
88 set.seal().unwrap();
89 let path = dir.join("t.00000.bucket");
90 assert!(set.load(0).is_ok(), "the intact fixture must read");
91
92 // Cut mid-payload: the header promises more than the file holds.
93 std::fs::write(&path, &bytes[..bytes.len() - 4]).unwrap();
94 let mut r = set.reader(0).unwrap().unwrap();
95 assert!(r.next().is_err(), "a short payload must error");
96
97 // Cut mid-header, which is a truncated file rather than a legitimate end.
98 std::fs::write(&path, &bytes[..REC_HEADER_BYTES - 1]).unwrap();
99 let mut r = set.reader(0).unwrap().unwrap();
100 assert!(r.next().is_err(), "a short header must error");
101
102 // A whole record short: the reader reaches the end and the tallies disagree.
103 std::fs::write(&path, []).unwrap();
104 let mut r = set.reader(0).unwrap().unwrap();
105 assert!(
106 r.next().is_err(),
107 "a bucket missing a record must fail the count check"
108 );
109 }
110
111 #[test]
112 fn a_wrong_length_or_a_dirty_reserved_tail_errors() {
113 let rec = SpillRecord {
114 tile_id: 1,
115 seq: 0,
116 extent: 0,
117 geom: IntGeometry::Points(vec![(1, 1)]),
118 props: vec![],
119 };
120 let good = rec.to_bytes().unwrap();
121 let mut head: [u8; REC_HEADER_BYTES] = good[..REC_HEADER_BYTES].try_into().unwrap();
122 assert!(RecHeader::parse(&head).is_ok(), "the fixture must be valid");
123
124 let mut bad = head;
125 bad[0] = bad[0].wrapping_add(1);
126 assert!(
127 RecHeader::parse(&bad).is_err(),
128 "rec_len must agree with geom_len + props_len"
129 );
130
131 head[REC_HEADER_BYTES - 1] = 1;
132 assert!(
133 RecHeader::parse(&head).is_err(),
134 "a nonzero reserved tail must be refused, not guessed at"
135 );
136 }
137
138 #[test]
139 fn an_unknown_geometry_kind_or_value_type_errors() {
140 assert!(GeomKind::from_tag(3).is_err());
141 // Value tag 7 does not exist.
142 let mut b = Vec::new();
143 put_u32(&mut b, 1);
144 put_u32(&mut b, 1);
145 b.push(b'k');
146 b.push(7);
147 assert!(decode_props(&b).is_err(), "an unknown value type must error");
148 }
149
150 /// Every record must land in the bucket its `tile_id` names, and the three
151 /// independent tallies -- push time, read time, and the file length -- must agree.
152 #[test]
153 fn every_record_lands_in_its_own_bucket_and_the_books_balance() {
154 let dir = tmp("buckets");
155 // z4: ids 21..85, 64 of them, into 16 buckets of 4.
156 let (lo, hi) = (21u64, 85u64);
157 let mut set = BucketSet::new(&dir, "z4", lo, hi, 16).unwrap();
158 assert_eq!(set.len(), 16);
159 assert_eq!(set.span(), 4);
160
161 let mut expected: Vec<Vec<u64>> = vec![Vec::new(); 16];
162 for (n, id) in (lo..hi).enumerate() {
163 // Skewed on purpose: some ids get several records, some none at all.
164 for k in 0..(n % 3) {
165 let rec = SpillRecord {
166 tile_id: id,
167 seq: (n * 10 + k) as u64,
168 extent: n as i64,
169 geom: IntGeometry::Points(vec![(n as i32, k as i32)]),
170 props: vec![("n".to_string(), Value::Uint(n as u64))],
171 };
172 set.push(id, &rec.to_bytes().unwrap()).unwrap();
173 expected[((id - lo) / 4) as usize].push(id);
174 }
175 }
176 set.seal().unwrap();
177
178 let mut total = 0u64;
179 for (i, want) in expected.iter().enumerate() {
180 let recs = set.load(i).unwrap();
181 let ids: Vec<u64> = recs.iter().map(|r| r.tile_id).collect();
182 assert_eq!(&ids, want, "bucket {i}");
183 let (blo, bhi) = set.range_of(i);
184 for r in &recs {
185 assert!(r.tile_id >= blo && r.tile_id < bhi, "bucket {i} range");
186 }
187 total += recs.len() as u64;
188 }
189 assert_eq!(total, set.total_records());
190 assert!(total > 0, "the fixture must actually push something");
191 }
192
193 #[test]
194 fn a_tile_id_outside_the_range_is_refused() {
195 let dir = tmp("range");
196 let mut set = BucketSet::new(&dir, "r", 21, 85, 16).unwrap();
197 let rec = SpillRecord {
198 tile_id: 20,
199 seq: 0,
200 extent: 0,
201 geom: IntGeometry::Points(vec![(0, 0)]),
202 props: vec![],
203 };
204 assert!(set.push(20, &rec.to_bytes().unwrap()).is_err(), "below the range");
205 assert!(set.push(85, &rec.to_bytes().unwrap()).is_err(), "above the range");
206 }
207
208 /// A bucket claiming a record it does not cover is the failure a bad partition would
209 /// produce, so the reader refuses it even though the writer could not have made it.
210 #[test]
211 fn a_reader_refuses_a_record_from_the_wrong_range() {
212 let dir = tmp("wrongrange");
213 let mut set = BucketSet::new(&dir, "w", 0, 64, 1).unwrap();
214 let rec = SpillRecord {
215 tile_id: 5,
216 seq: 0,
217 extent: 0,
218 geom: IntGeometry::Points(vec![(0, 0)]),
219 props: vec![],
220 };
221 set.push(5, &rec.to_bytes().unwrap()).unwrap();
222 set.seal().unwrap();
223
224 // Rewrite the same bucket with an out-of-range id, keeping the byte count so
225 // only the range check can catch it.
226 let mut moved = rec.clone();
227 moved.tile_id = 999;
228 let bytes = moved.to_bytes().unwrap();
229 assert_eq!(bytes.len(), rec.to_bytes().unwrap().len());
230 std::fs::write(dir.join("w.00000.bucket"), &bytes).unwrap();
231 let mut r = set.reader(0).unwrap().unwrap();
232 assert!(r.next().is_err(), "an out-of-range tile id must error");
233 }
234
235 /// Draining buckets in ascending index, each internally sorted, must give globally
236 /// ascending `tile_id` -- across two levels of re-partition, which is the expected
237 /// path for a dense metro bucket rather than an exotic one.
238 #[test]
239 fn buckets_drain_in_ascending_tile_id_across_two_recursion_levels() {
240 let dir = tmp("recursion");
241 let (lo, hi) = (21u64, 85u64);
242 let mut parent = BucketSet::new(&dir, "p", lo, hi, 4).unwrap();
243 assert_eq!(parent.span(), 16);
244
245 // Pushed in a deliberately scrambled order: the spill has no ordering
246 // requirement, which is what would make a parallel bucket pass safe later.
247 let order: Vec<u64> = (lo..hi).rev().collect();
248 for id in &order {
249 let rec = SpillRecord {
250 tile_id: *id,
251 seq: *id,
252 extent: 0,
253 geom: IntGeometry::Points(vec![(0, 0)]),
254 props: vec![],
255 };
256 parent.push(*id, &rec.to_bytes().unwrap()).unwrap();
257 }
258 parent.seal().unwrap();
259
260 let mut drained: Vec<u64> = Vec::new();
261 for i in 0..parent.len() {
262 let (blo, bhi) = parent.range_of(i);
263 // Re-partition every parent bucket, then re-partition each child again.
264 let mut child = BucketSet::new(&dir, &format!("c{i}"), blo, bhi, 4).unwrap();
265 let mut recs = parent.load(i).unwrap();
266 recs.sort_by_key(|r| r.tile_id);
267 for r in &recs {
268 child.push(r.tile_id, &r.to_bytes().unwrap()).unwrap();
269 }
270 child.seal().unwrap();
271 for j in 0..child.len() {
272 let (clo, chi) = child.range_of(j);
273 let mut grand =
274 BucketSet::new(&dir, &format!("g{i}_{j}"), clo, chi, 4).unwrap();
275 let mut crecs = child.load(j).unwrap();
276 crecs.sort_by_key(|r| r.tile_id);
277 for r in &crecs {
278 grand.push(r.tile_id, &r.to_bytes().unwrap()).unwrap();
279 }
280 grand.seal().unwrap();
281 for k in 0..grand.len() {
282 let mut g = grand.load(k).unwrap();
283 g.sort_by_key(|r| r.tile_id);
284 drained.extend(g.iter().map(|r| r.tile_id));
285 }
286 }
287 }
288 let want: Vec<u64> = (lo..hi).collect();
289 assert_eq!(drained, want, "the drain must be globally ascending");
290 }
291
292 #[test]
293 fn a_bucket_count_that_is_not_a_power_of_four_is_refused() {
294 let dir = tmp("pow4");
295 for bad in [0usize, 2, 8, 32, 100] {
296 assert!(
297 BucketSet::new(&dir, "b", 0, 64, bad).is_err(),
298 "{bad} buckets must be refused"
299 );
300 }
301 for good in [1usize, 4, 16, 64, 256] {
302 assert!(BucketSet::new(&dir, "b", 0, 1024, good).is_ok(), "{good} buckets");
303 }
304 }
305
306 /// A shallow zoom has fewer tiles than the requested bucket count. Dividing the
307 /// count down by four keeps a bucket one quadtree cell; clamping it to the tile
308 /// count would not.
309 #[test]
310 fn a_shallow_range_reduces_the_bucket_count_by_fours() {
311 let dir = tmp("shallow");
312 // z1 has 4 tiles; asking for 256 buckets gets 4.
313 let set = BucketSet::new(&dir, "z1", 1, 5, 256).unwrap();
314 assert_eq!(set.len(), 4);
315 assert_eq!(set.span(), 1);
316 // z0 has one.
317 let set = BucketSet::new(&dir, "z0", 0, 1, 256).unwrap();
318 assert_eq!(set.len(), 1);
319 assert_eq!(set.span(), 1);
320 }
321
322 #[test]
323 fn a_bucket_set_removes_its_files_when_it_is_dropped() {
324 let dir = tmp("cleanup");
325 let path;
326 {
327 let mut set = BucketSet::new(&dir, "gone", 0, 64, 1).unwrap();
328 let rec = SpillRecord {
329 tile_id: 0,
330 seq: 0,
331 extent: 0,
332 geom: IntGeometry::Points(vec![(0, 0)]),
333 props: vec![],
334 };
335 set.push(0, &rec.to_bytes().unwrap()).unwrap();
336 set.seal().unwrap();
337 path = dir.join("gone.00000.bucket");
338 assert!(path.exists(), "the bucket file must exist while the set does");
339 }
340 assert!(!path.exists(), "a dropped bucket set must take its files with it");
341 }
342
343 /// A bucket that receives no records in a rerun must not inherit the file a killed
344 /// previous run left at the same path: `seal` would report bytes nobody pushed, and
345 /// with a persistent `--spill-dir` that turns a crash into a baffling hard failure.
346 #[test]
347 fn a_stale_bucket_file_does_not_survive_a_new_set() {
348 let dir = tmp("stale");
349 let stale = dir.join("s.00001.bucket");
350 std::fs::write(&stale, b"left over by a killed run").unwrap();
351
352 let mut set = BucketSet::new(&dir, "s", 0, 64, 4).unwrap();
353 assert!(!stale.exists(), "the stale file must be cleared at construction");
354 let rec = SpillRecord {
355 tile_id: 0,
356 seq: 0,
357 extent: 0,
358 geom: IntGeometry::Points(vec![(0, 0)]),
359 props: vec![],
360 };
361 set.push(0, &rec.to_bytes().unwrap()).unwrap();
362 set.seal().expect("the books must balance despite the stale file");
363 assert!(set.load(1).unwrap().is_empty(), "bucket 1 is empty, not stale");
364 }
365
366 #[test]
367 fn a_bucket_set_must_be_sealed_before_it_is_read() {
368 let dir = tmp("sealed");
369 let mut set = BucketSet::new(&dir, "s", 0, 64, 1).unwrap();
370 assert!(set.reader(0).is_err(), "reading an unsealed set must error");
371 set.seal().unwrap();
372 assert!(set.reader(0).unwrap().is_none(), "an empty bucket has no reader");
373 let rec = SpillRecord {
374 tile_id: 0,
375 seq: 0,
376 extent: 0,
377 geom: IntGeometry::Points(vec![(0, 0)]),
378 props: vec![],
379 };
380 assert!(
381 set.push(0, &rec.to_bytes().unwrap()).is_err(),
382 "pushing to a sealed set must error"
383 );
384 }
385
386 // --- the normalized file -------------------------------------------------
387
388 /// Snap a geometry to the e7 grid, which is what [`encode_geometry`] stores.
389 ///
390 /// A plain decimal literal is only NEARLY on that grid: `-122.42` and
391 /// `-1_224_200_000 as f64 * 1e-7` are different `f64`s, an ulp apart -- 1.4e-14
392 /// degrees, seven orders of magnitude below the 1.1 cm the quantisation itself costs.
393 /// So a decoded feature is compared against its snapped input rather than against the
394 /// literal it was written from. The assertion stays exact and total -- every vertex,
395 /// every count, every property -- and states the contract the codec actually has.
396 fn snapped(g: &Geometry) -> Geometry {
397 let pt = |&(x, y): &Pt| {
398 (
399 crate::pyramid::e7(x) as f64 * 1e-7,
400 crate::pyramid::e7(y) as f64 * 1e-7,
401 )
402 };
403 let ring = |r: &Vec<Pt>| r.iter().map(pt).collect::<Vec<Pt>>();
404 match g {
405 Geometry::Points(p) => Geometry::Points(ring(p)),
406 Geometry::Lines(l) => Geometry::Lines(l.iter().map(ring).collect()),
407 Geometry::Polygons(p) => {
408 Geometry::Polygons(p.iter().map(|rs| rs.iter().map(ring).collect()).collect())
409 }
410 }
411 }
412
413 fn snapped_all(features: &[NormalizedFeature]) -> Vec<NormalizedFeature> {
414 features
415 .iter()
416 .map(|f| NormalizedFeature {
417 geometry: snapped(&f.geometry),
418 props: f.props.clone(),
419 })
420 .collect()
421 }
422
423 /// **The guarantee a byte-identical archive rests on.** Every coordinate `osm_ingest`
424 /// yields is an `i32` e7 multiplied by `1e-7`, and such a value must come back as the
425 /// same `f64` it went in as -- not merely close. If it did not, halving the spill
426 /// would have moved every OSM vertex in the build.
427 ///
428 /// Spanning the whole `i32` range, because the argument is about the two
429 /// multiplications' relative error staying under half an e7 unit and that is weakest
430 /// at the largest magnitude.
431 #[test]
432 fn an_e7_grid_coordinate_survives_the_round_trip_bit_exactly() {
433 let dir = tmp("e7exact");
434 let path = dir.join("f.bin");
435 let grid: Vec<i32> = vec![
436 0,
437 1,
438 -1,
439 1_800_000_000,
440 -1_800_000_000,
441 900_000_000,
442 -900_000_000,
443 1_224_200_000,
444 -1_224_200_000,
445 377_700_000,
446 i32::MAX,
447 i32::MIN + 1,
448 ];
449 let points: Vec<Pt> = grid
450 .iter()
451 .map(|&n| (n as f64 * 1e-7, -n as f64 * 1e-7))
452 .collect();
453 let feature = NormalizedFeature {
454 geometry: Geometry::Points(points.clone()),
455 props: every_value(),
456 };
457
458 let mut w = NormalizedWriter::create(&path).unwrap();
459 w.push(&feature.geometry, &feature.props).unwrap();
460 w.finish().unwrap();
461
462 let back = NormalizedReader::open(&path)
463 .unwrap()
464 .next()
465 .unwrap()
466 .expect("a feature");
467 assert_eq!(back, feature, "an e7-grid coordinate must not move at all");
468
469 // Eight bytes a vertex, not sixteen, in the *records* -- the whole point of the
470 // encoding. The file itself holds those records inside one compressed frame (plus the
471 // 8-byte spill header), so its length is asserted structurally instead of exactly: the
472 // frame must inflate to exactly the raw records above.
473 let bytes = std::fs::read(&path).unwrap();
474 assert_eq!(&bytes[0..4], b"NZC1", "the spill magic");
475 assert_eq!(bytes[4], 1, "the spill version");
476 assert!(bytes[5..8].iter().all(|v| *v == 0), "reserved zero");
477 let frame_len = u32::from_le_bytes(bytes[8..12].try_into().unwrap()) as usize;
478 assert_eq!(8 + 4 + frame_len, bytes.len(), "one frame fills the file");
479 let raw = miniz_oxide::inflate::decompress_to_vec(&bytes[12..]).expect("inflate");
480 let props = {
481 let mut buf = Vec::new();
482 encode_props(&feature.props, &mut buf).unwrap();
483 buf.len()
484 };
485 assert_eq!(
486 raw.len(),
487 NORM_HEADER_BYTES + 4 + points.len() * 8 + props,
488 "a vertex must cost eight bytes of record"
489 );
490
491 let _ = std::fs::remove_dir_all(&dir);
492 }