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

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

spill_part4.rs457 lines · 18.9 KiBRaw
1
2
3 #[test]
4 fn the_normalized_file_round_trips_and_folds_its_summary() {
5 let dir = tmp("normalized");
6 let path = dir.join("features.bin");
7 let features = vec![
8 NormalizedFeature {
9 geometry: Geometry::Lines(vec![vec![(-122.42, 37.77), (-122.40, 37.79)]]),
10 props: every_value(),
11 },
12 NormalizedFeature {
13 geometry: Geometry::Lines(vec![vec![(-74.01, 40.71), (-73.99, 40.73)]]),
14 props: vec![],
15 },
16 NormalizedFeature {
17 geometry: Geometry::Points(vec![(2.35, 48.85)]),
18 props: vec![("x".to_string(), Value::Bool(true))],
19 },
20 ];
21
22 let mut w = NormalizedWriter::create(&path).unwrap();
23 for f in &features {
24 w.push(&f.geometry, &f.props).unwrap();
25 }
26 w.skip();
27 w.skip();
28 let summary = w.finish().unwrap();
29
30 assert_eq!(summary.count, 3);
31 assert_eq!(summary.skipped, 2);
32 // The FIRST feature's kind, even though a point follows.
33 assert_eq!(summary.geom_kind, Some(GeomKind::Lines));
34 let b = summary.bounds.expect("bounds");
35 assert_eq!((b.min_x, b.max_x), (-122.42, 2.35));
36 assert_eq!((b.min_y, b.max_y), (37.77, 48.85));
37
38 let mut r = NormalizedReader::open(&path).unwrap();
39 let mut back = Vec::new();
40 while let Some(f) = r.next().unwrap() {
41 back.push(f);
42 }
43 let want = snapped_all(&features);
44 assert_eq!(back, want);
45
46 // Every zoom re-reads it from the front.
47 r.rewind().unwrap();
48 assert_eq!(r.next().unwrap().as_ref(), Some(&want[0]));
49
50 let _ = std::fs::remove_dir_all(&dir);
51 }
52
53 /// The chunked reader must yield exactly the sequential reader's features in exactly
54 /// its order, and its chunk boundaries must land on multiples of
55 /// `NORM_CHUNK_FEATURES` — that alignment is what the bucket pass relies on to
56 /// reconstruct `seq` without reading the whole file.
57 #[test]
58 fn the_chunked_reader_yields_what_the_sequential_one_does() {
59 let dir = tmp("normchunks");
60 let path = dir.join("features.bin");
61
62 // Deliberately not a multiple of the stride, so the last chunk is partial, and
63 // varied enough that a record-length mistake cannot cancel out.
64 let n = 2 * NORM_CHUNK_FEATURES as usize + 7;
65 let features: Vec<NormalizedFeature> = (0..n)
66 .map(|i| {
67 let f = i as f64;
68 if i % 3 == 0 {
69 NormalizedFeature {
70 geometry: Geometry::Points(vec![(f * 0.01, -f * 0.02)]),
71 props: vec![("i".to_string(), Value::Uint(i as u64))],
72 }
73 } else if i % 3 == 1 {
74 NormalizedFeature {
75 geometry: Geometry::Lines(vec![vec![(f * 0.01, 1.0), (f * 0.01, 2.0)]]),
76 props: every_value(),
77 }
78 } else {
79 NormalizedFeature {
80 geometry: Geometry::Lines(vec![vec![(0.0, f * 0.01), (1.0, f * 0.01)]]),
81 props: vec![],
82 }
83 }
84 })
85 .collect();
86
87 let mut w = NormalizedWriter::create(&path).unwrap();
88 for f in &features {
89 w.push(&f.geometry, &f.props).unwrap();
90 }
91 let summary = w.finish().unwrap();
92 assert_eq!(summary.count, n as u64);
93 assert_eq!(summary.chunk_count(), 3, "two full chunks and a partial one");
94 assert_eq!(
95 *summary.chunks.last().unwrap(),
96 std::fs::metadata(&path).unwrap().len(),
97 "the sentinel must be the file's length"
98 );
99
100 let chunks = NormalizedChunks::open(&path, summary.chunks.clone()).unwrap();
101 let mut scratch = Vec::new();
102 let mut out = Vec::new();
103 let mut back = Vec::new();
104 for i in 0..chunks.chunk_count() {
105 chunks.read_into(i, &mut scratch, &mut out).unwrap();
106 // The alignment the `seq` reconstruction depends on.
107 assert_eq!(
108 back.len() as u64,
109 i as u64 * NORM_CHUNK_FEATURES,
110 "chunk {i} must start at feature {}",
111 i as u64 * NORM_CHUNK_FEATURES
112 );
113 back.extend(out.iter().cloned());
114 }
115 assert_eq!(back, snapped_all(&features), "the chunked read must match the input");
116
117 // And the sequential reader, so neither can drift from the other.
118 let mut r = NormalizedReader::open(&path).unwrap();
119 let mut seq = Vec::new();
120 while let Some(f) = r.next().unwrap() {
121 seq.push(f);
122 }
123 assert_eq!(back, seq, "the two readers must agree");
124
125 assert!(
126 chunks
127 .read_into(chunks.chunk_count(), &mut scratch, &mut out)
128 .is_err(),
129 "a chunk past the end must error rather than read nothing"
130 );
131
132 let _ = std::fs::remove_dir_all(&dir);
133 }
134
135 /// The anon backend stages byte-identical chunks: write through
136 /// `create_anon`, read back through `open_anon`, and the records plus the
137 /// chunk index match the file path exactly. This is what lets -Verify hold
138 /// the anon build to the same hash as the file build.
139 #[test]
140 fn the_anon_backend_stages_what_the_file_does() {
141 let n = 2 * NORM_CHUNK_FEATURES as usize + 7;
142 let features: Vec<NormalizedFeature> = (0..n)
143 .map(|i| {
144 let f = i as f64;
145 NormalizedFeature {
146 geometry: Geometry::Lines(vec![vec![(f * 0.01, 1.0), (f * 0.01, 2.0)]]),
147 props: vec![("i".to_string(), Value::Uint(i as u64))],
148 }
149 })
150 .collect();
151
152 // File path (reference).
153 let dir = tmp("normanonfile");
154 let path = dir.join("features.bin");
155 let mut w = NormalizedWriter::create(&path).unwrap();
156 for f in &features {
157 w.push(&f.geometry, &f.props).unwrap();
158 }
159 let file_summary = w.finish().unwrap();
160
161 // Anon path.
162 let mut a = NormalizedWriter::create_anon("anon-test").unwrap();
163 for f in &features {
164 a.push(&f.geometry, &f.props).unwrap();
165 }
166 let (anon_summary, store) = a.finish_anon().unwrap();
167
168 assert_eq!(anon_summary, file_summary, "summaries must match");
169 assert_eq!(
170 store.len(),
171 std::fs::metadata(&path).unwrap().len(),
172 "staged bytes must match"
173 );
174
175 let chunks = NormalizedChunks::open_anon(
176 "anon-test",
177 anon_summary.chunks.clone(),
178 std::sync::Arc::new(store),
179 )
180 .unwrap();
181 let mut scratch = Vec::new();
182 let mut out = Vec::new();
183 let mut back = Vec::new();
184 for i in 0..chunks.chunk_count() {
185 chunks.read_into(i, &mut scratch, &mut out).unwrap();
186 back.extend(out.iter().cloned());
187 }
188 assert_eq!(back, snapped_all(&features), "anon reads must match the input");
189
190 let _ = std::fs::remove_dir_all(&dir);
191 }
192
193 /// A corrupt chunk index must be reported, not silently mis-decoded: the offsets are
194 /// the one part of the format the records themselves cannot validate.
195 #[test]
196 fn a_chunk_index_pointing_into_a_record_errors() {
197 let dir = tmp("normchunkbad");
198 let path = dir.join("f.bin");
199 let mut w = NormalizedWriter::create(&path).unwrap();
200 for i in 0..NORM_CHUNK_FEATURES + 3 {
201 w.push(
202 &Geometry::Lines(vec![vec![(i as f64, 1.0), (i as f64, 2.0)]]),
203 &every_value(),
204 )
205 .unwrap();
206 }
207 let summary = w.finish().unwrap();
208
209 let mut scratch = Vec::new();
210 let mut out = Vec::new();
211
212 // Nudge a boundary into the middle of a record.
213 let mut bad = summary.chunks.clone();
214 bad[1] += 3;
215 let chunks = NormalizedChunks::open(&path, bad).unwrap();
216 assert!(
217 chunks.read_into(0, &mut scratch, &mut out).is_err()
218 || chunks.read_into(1, &mut scratch, &mut out).is_err(),
219 "a misaligned boundary must error"
220 );
221
222 // A boundary that runs backwards.
223 let mut backwards = summary.chunks.clone();
224 backwards[1] = backwards[0];
225 backwards[0] = *summary.chunks.last().unwrap();
226 let chunks = NormalizedChunks::open(&path, backwards).unwrap();
227 assert!(
228 chunks.read_into(0, &mut scratch, &mut out).is_err(),
229 "a backwards range must error"
230 );
231
232 let _ = std::fs::remove_dir_all(&dir);
233 }
234
235 /// The summary's bounds must be exactly what the in-memory path computes, or the
236 /// two producers write different header bytes for the same input.
237 #[test]
238 fn the_summary_bounds_match_the_in_memory_fold() {
239 let dir = tmp("bounds");
240 let path = dir.join("f.bin");
241 let geoms = vec![
242 Geometry::Lines(vec![vec![(-10.0, -5.0), (3.0, 8.0)]]),
243 Geometry::Points(vec![(20.0, -30.0)]),
244 // No vertices at all, so it must not move the box.
245 Geometry::Lines(vec![]),
246 ];
247 let mut w = NormalizedWriter::create(&path).unwrap();
248 for g in &geoms {
249 w.push(g, &[]).unwrap();
250 }
251 let summary = w.finish().unwrap();
252
253 let want = geoms.iter().fold(None, crate::pyramid::fold_bounds);
254 assert_eq!(summary.bounds, want);
255
256 let _ = std::fs::remove_dir_all(&dir);
257 }
258
259 #[test]
260 fn an_empty_normalized_file_reads_as_no_features() {
261 let dir = tmp("empty");
262 let path = dir.join("f.bin");
263 let summary = NormalizedWriter::create(&path).unwrap().finish().unwrap();
264 assert_eq!(summary, NormalizedSummary::default());
265 assert!(NormalizedReader::open(&path).unwrap().next().unwrap().is_none());
266 let _ = std::fs::remove_dir_all(&dir);
267 }
268
269 #[test]
270 fn a_truncated_normalized_record_errors() {
271 let dir = tmp("normtrunc");
272 let path = dir.join("f.bin");
273 let mut w = NormalizedWriter::create(&path).unwrap();
274 w.push(
275 &Geometry::Lines(vec![vec![(1.0, 2.0), (3.0, 4.0)]]),
276 &every_value(),
277 )
278 .unwrap();
279 w.finish().unwrap();
280
281 let bytes = std::fs::read(&path).unwrap();
282 // Layout is the 8-byte spill header, then one frame (`u32` len + DEFLATE). Truncations
283 // are relative to that: cutting the frame is a truncated file, cutting into the spill
284 // header is a file that is not a spill at all.
285 assert!(bytes.len() > 8 + 4, "the fixture must hold a frame");
286 std::fs::write(&path, &bytes[..bytes.len() - 8]).unwrap();
287 assert!(NormalizedReader::open(&path).unwrap().next().is_err(), "short payload");
288 std::fs::write(&path, &bytes[..8 + 4 - 1]).unwrap();
289 assert!(NormalizedReader::open(&path).unwrap().next().is_err(), "short frame header");
290 // A file shorter than the spill header is not a spill file at all.
291 std::fs::write(&path, &bytes[..8 - 1]).unwrap();
292 assert!(NormalizedReader::open(&path).is_err(), "short spill header");
293 // Corrupt the first record's reserved tail *inside* the frame: inflate the frame,
294 // dirty byte 15 of the record header, recompress, and rewrite the file. The reader
295 // must refuse the record, not decode past it.
296 let frame_len =
297 u32::from_le_bytes(bytes[8..12].try_into().unwrap()) as usize;
298 let mut raw =
299 miniz_oxide::inflate::decompress_to_vec(&bytes[12..12 + frame_len]).unwrap();
300 raw[NORM_HEADER_BYTES - 1] = 1;
301 let sealed = miniz_oxide::deflate::compress_to_vec(&raw, 6);
302 let mut dirty = bytes[..12].to_vec();
303 dirty[8..12].copy_from_slice(&(sealed.len() as u32).to_le_bytes());
304 dirty.extend_from_slice(&sealed);
305 std::fs::write(&path, &dirty).unwrap();
306 assert!(
307 NormalizedReader::open(&path).unwrap().next().is_err(),
308 "nonzero reserved tail"
309 );
310 // And the chunked reader agrees on the truncated file: a frame that will not inflate
311 // is corruption, not a short chunk.
312 std::fs::write(&path, &bytes[..bytes.len() - 8]).unwrap();
313 let summary = NormalizedSummary { count: 1, chunks: vec![8, bytes.len() as u64 - 8], ..Default::default() };
314 let chunks = NormalizedChunks::open(&path, summary.chunks.clone()).unwrap();
315 let mut scratch = Vec::new();
316 let mut out = Vec::new();
317 assert!(chunks.read_into(0, &mut scratch, &mut out).is_err(), "short frame");
318 let _ = std::fs::remove_dir_all(&dir);
319 }
320
321 /// A file with the wrong magic or version is refused on open, not decoded as frames.
322 #[test]
323 fn a_spill_with_bad_magic_or_version_is_refused() {
324 let dir = tmp("normmagic");
325 let path = dir.join("f.bin");
326 let mut w = NormalizedWriter::create(&path).unwrap();
327 w.push(&Geometry::Points(vec![(1.0, 2.0)]), &[]).unwrap();
328 w.finish().unwrap();
329 let bytes = std::fs::read(&path).unwrap();
330
331 let mut bad = bytes.clone();
332 bad[0] = b'X';
333 std::fs::write(&path, &bad).unwrap();
334 assert!(NormalizedReader::open(&path).is_err(), "bad magic decodes");
335
336 let mut bad = bytes.clone();
337 bad[4] = 9;
338 std::fs::write(&path, &bad).unwrap();
339 assert!(NormalizedReader::open(&path).is_err(), "bad version decodes");
340
341 let mut bad = bytes.clone();
342 bad[7] = 1;
343 std::fs::write(&path, &bad).unwrap();
344 assert!(NormalizedReader::open(&path).is_err(), "nonzero reserved decodes");
345
346 let _ = std::fs::remove_dir_all(&dir);
347 }
348
349 /// Compression is the point: 64 repetitive line features must stage at a fraction of
350 /// their raw records. A regression to uncompressed staging fails here rather than on a
351 /// planet disk at z14.
352 #[test]
353 fn a_chunk_of_repetitive_features_stages_compressed() {
354 let dir = tmp("normratio");
355 let path = dir.join("f.bin");
356 let mut w = NormalizedWriter::create(&path).unwrap();
357 for i in 0..NORM_CHUNK_FEATURES {
358 let f = i as f64;
359 w.push(
360 &Geometry::Lines(vec![vec![(f * 0.001, 1.0), (f * 0.001, 2.0)]]),
361 &[("i".to_string(), Value::Uint(i))],
362 )
363 .unwrap();
364 }
365 let summary = w.finish().unwrap();
366 assert_eq!(summary.chunk_count(), 1);
367 let staged = std::fs::metadata(&path).unwrap().len();
368 // Raw records: each ~50+ bytes, so ~3.2 KB minimum unstaged. The frame must be
369 // well under that; 1 KB is generous to DEFLATE on coordinate runs.
370 assert!(staged < 8 + 4 + 1024, "{staged} staged bytes for one chunk is not compressed");
371 // And it still reads back exactly.
372 let chunks = NormalizedChunks::open(&path, summary.chunks.clone()).unwrap();
373 let mut scratch = Vec::new();
374 let mut out = Vec::new();
375 chunks.read_into(0, &mut scratch, &mut out).unwrap();
376 assert_eq!(out.len(), NORM_CHUNK_FEATURES as usize);
377 let _ = std::fs::remove_dir_all(&dir);
378 }
379
380 #[test]
381 fn the_normalized_file_guard_removes_it_on_drop() {
382 let dir = tmp("normguard");
383 let path = dir.join("f.bin");
384 {
385 let guard = NormalizedFile::new(&path);
386 NormalizedWriter::create(guard.path()).unwrap().finish().unwrap();
387 assert!(path.exists());
388 }
389 assert!(!path.exists(), "the guard must remove it");
390 let _ = std::fs::remove_dir_all(&dir);
391 }
392
393 /// Runs pushed whole ([`NormalizedWriter::push_run`]) -- of every length, starting mid-frame
394 /// and on frame boundaries, mixed with single records and with enough frames to cross a
395 /// background batch -- write the same file and the same summary as pushing record by record.
396 #[test]
397 fn pushing_runs_writes_what_pushing_records_writes() {
398 let dir = tmp("runs");
399 let mut records: Vec<(GeomKind, Vec<u8>, Option<crate::geom::Rect>)> = Vec::new();
400 for i in 0..(NORM_CHUNK_FEATURES as usize * 4200 + 37) {
401 let g = Geometry::Lines(vec![vec![(i as f64 * 1e-4, 1.0), (i as f64 * 1e-4 + 0.5, (i % 7) as f64)]]);
402 let mut geom = Vec::new();
403 encode_geometry(&g, &mut geom).unwrap();
404 let mut rec = Vec::new();
405 let props = vec![("c".to_string(), Value::Uint(i as u64))];
406 encode_normalized_record(GeomKind::of(&g), &geom, &props, &mut rec).unwrap();
407 records.push((GeomKind::of(&g), rec, crate::geom::bounds(&g)));
408 }
409 for anon in [false, true] {
410 let (a, b) = (dir.join(format!("one{anon}.bin")), dir.join(format!("run{anon}.bin")));
411 let mk = |p: &std::path::Path| {
412 if anon { NormalizedWriter::create_anon(p) } else { NormalizedWriter::create(p) }.unwrap()
413 };
414 let mut one = mk(&a);
415 for (k, r, bd) in &records {
416 one.push_record(*k, r, *bd).unwrap();
417 }
418 let mut run = mk(&b);
419 let mut i = 0usize;
420 let mut step = 1usize;
421 while i < records.len() {
422 let n = step.min(records.len() - i);
423 let mut bytes = Vec::new();
424 let mut ends = Vec::new();
425 let mut bounds = None;
426 for (_, r, bd) in &records[i..i + n] {
427 bytes.extend_from_slice(r);
428 ends.push(bytes.len());
429 bounds = match (bounds, *bd) {
430 (None, x) => x,
431 (x, None) => x,
432 (Some(p), Some(q)) => Some(crate::geom::Rect {
433 min_x: f64::min(p.min_x, q.min_x),
434 min_y: f64::min(p.min_y, q.min_y),
435 max_x: f64::max(p.max_x, q.max_x),
436 max_y: f64::max(p.max_y, q.max_y),
437 }),
438 };
439 }
440 run.push_run(bytes, &ends, Some(records[i].0), bounds).unwrap();
441 i += n;
442 step = [1, 63, 64, 65, 200, 4096 * 64 + 3][(step + i) % 6];
443 }
444 let (s1, st1) = one.finish_either().unwrap();
445 let (s2, st2) = run.finish_either().unwrap();
446 assert_eq!(s1, s2, "summaries (chunk index included) agree, anon={anon}");
447 let bytes = |p: &std::path::Path, st: Option<crate::anon::AnonStore>| match st {
448 Some(s) => {
449 let mut v = vec![0u8; s.len() as usize];
450 s.read_at(0, &mut v).unwrap();
451 v
452 }
453 None => std::fs::read(p).unwrap(),
454 };
455 assert_eq!(bytes(&a, st1), bytes(&b, st2), "same bytes, anon={anon}");
456 }
457 }