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

Modern-Apps.git / scripts / maps / osm_ingest / src / pbf_extra_s1.rs

pbf_extra_s1.rs401 lines · 16.8 KiBRaw
1#[cfg(test)]
2mod tests {
3 use super::*;
4 use crate::pbf::{
5 run_pass, run_pass_sink, scan_blobs, CHUNK_BLOBS, KIND_NODES, KIND_RELATIONS, KIND_WAYS,
6 };
7 use crate::testpbf;
8 use std::sync::atomic::{AtomicUsize, Ordering};
9
10 /// A file with enough `OSMData` blobs to span several chunks, so the reorder
11 /// buffer and its window are actually reached.
12 fn multi_chunk_pbf(chunks: usize) -> (std::path::PathBuf, std::path::PathBuf) {
13 let block = testpbf::primitive_block();
14 let blobs = chunks * CHUNK_BLOBS;
15 let refs: Vec<&[u8]> = (0..blobs).map(|_| block.as_slice()).collect();
16 let bytes = testpbf::pbf_from_blocks(refs);
17 let dir = std::env::temp_dir().join(format!(
18 "osm_ingest_window_{}_{chunks}_{:?}",
19 std::process::id(),
20 std::thread::current().id()
21 ));
22 let _ = std::fs::remove_dir_all(&dir);
23 std::fs::create_dir_all(&dir).unwrap();
24 let path = dir.join("many.osm.pbf");
25 std::fs::write(&path, &bytes).unwrap();
26 (path, dir)
27 }
28
29 /// The reorder buffer must not grow with the file.
30 ///
31 /// A worker deposits a finished chunk and immediately claims another, so without a
32 /// window one slow chunk 0 parks every later chunk's accumulator at once — and on a
33 /// planet pass those accumulators are the largest things in the build. Chunk 0 is
34 /// made slow here on purpose; the counter is what proves the bound, because the
35 /// pass would produce correct output either way.
36 #[test]
37 fn the_reorder_buffer_stays_bounded_when_the_first_chunk_lags() {
38 let (path, _dir) = multi_chunk_pbf(40);
39 crate::par::set_threads(4);
40 let blobs = scan_blobs(&path).unwrap();
41 let n_chunks = blobs.len().div_ceil(CHUNK_BLOBS);
42 assert!(n_chunks >= 40, "{n_chunks} chunk(s) is not enough to bound anything");
43
44 // Accumulators alive right now, and the worst it ever got.
45 let live = std::sync::Arc::new(AtomicUsize::new(0));
46 let peak = std::sync::Arc::new(AtomicUsize::new(0));
47
48 struct Acc {
49 live: std::sync::Arc<AtomicUsize>,
50 }
51 impl Drop for Acc {
52 fn drop(&mut self) {
53 self.live.fetch_sub(1, Ordering::SeqCst);
54 }
55 }
56
57 let first_seen = AtomicUsize::new(0);
58 let (mk_live, mk_peak) = (live.clone(), peak.clone());
59 let drained = std::sync::Mutex::new(Vec::new());
60 run_pass_sink(
61 &path,
62 &blobs,
63 crate::pbf::PassSpec { blob_kinds: None, want: KIND_NODES, label: "window" },
64 || {
65 let n = mk_live.fetch_add(1, Ordering::SeqCst) + 1;
66 mk_peak.fetch_max(n, Ordering::SeqCst);
67 Acc { live: mk_live.clone() }
68 },
69 |_acc, _block| {
70 // Only the very first chunk to start is slowed, which is enough to make
71 // every other worker run ahead of the sink.
72 if first_seen.fetch_add(1, Ordering::SeqCst) == 0 {
73 std::thread::sleep(std::time::Duration::from_millis(300));
74 }
75 Ok(KIND_NODES)
76 },
77 |acc: Acc| {
78 drained.lock().unwrap().push(());
79 drop(acc);
80 Ok(())
81 },
82 )
83 .unwrap();
84
85 assert_eq!(drained.into_inner().unwrap().len(), n_chunks, "every chunk drains");
86 assert_eq!(live.load(Ordering::SeqCst), 0, "an accumulator leaked");
87 // 4 threads => a window of 8, plus the one each worker is filling. Well under
88 // the ~40 that would pile up if the workers were free to run to the end of the
89 // file, which is what makes this assertion mean something.
90 let bound = 8 + 4;
91 let got = peak.load(Ordering::SeqCst);
92 assert!(
93 got <= bound,
94 "{got} accumulators were live at once over {n_chunks} chunks; \
95 the window should have held it to {bound}"
96 );
97 crate::par::clear_threads();
98 }
99
100 #[test]
101 fn round_trips_a_synthetic_file() {
102 let (path, _dir) = testpbf::write_sample("pbf_pass");
103
104 let blobs = scan_blobs(&path).unwrap();
105 assert_eq!(blobs.len(), 1, "the OSMHeader blob is not returned");
106
107 let (states, kinds) = run_pass(
108 &path,
109 &blobs,
110 None,
111 KIND_NODES | KIND_WAYS | KIND_RELATIONS,
112 "test",
113 || (0usize, 0usize, 0usize),
114 |s: &mut (usize, usize, usize), block| {
115 let mut mask = 0;
116 crate::osm::visit_block(
117 block,
118 KIND_NODES | KIND_WAYS | KIND_RELATIONS,
119 &mut mask,
120 &mut |el: crate::osm::Element| {
121 match el {
122 crate::osm::Element::Node(_) => s.0 += 1,
123 crate::osm::Element::Way(_) => s.1 += 1,
124 crate::osm::Element::Relation(_) => s.2 += 1,
125 }
126 Ok(())
127 },
128 )?;
129 Ok(mask)
130 },
131 )
132 .unwrap();
133 let totals = states.iter().fold((0, 0, 0), |a, b| (a.0 + b.0, a.1 + b.1, a.2 + b.2));
134 assert_eq!(totals, (testpbf::NODE_COUNT, 3, 1));
135 assert_eq!(kinds[0], KIND_NODES | KIND_WAYS | KIND_RELATIONS);
136 }
137
138 #[test]
139 fn blob_kind_filter_skips_whole_blobs() {
140 let (path, _dir) = testpbf::write_sample("pbf_filter");
141 let blobs = scan_blobs(&path).unwrap();
142 // Pretend the only blob holds nothing but nodes; a ways pass must then
143 // never even read it.
144 let (states, _) = run_pass(
145 &path,
146 &blobs,
147 Some(&[KIND_NODES]),
148 KIND_WAYS,
149 "test",
150 || 0usize,
151 |s: &mut usize, _block| {
152 *s += 1;
153 Ok(0)
154 },
155 )
156 .unwrap();
157 assert_eq!(states.iter().sum::<usize>(), 0);
158 }
159
160 #[test]
161 fn a_skipped_blob_keeps_its_kinds_in_the_returned_mask() {
162 let (path, _dir) = testpbf::write_sample("pbf_carry");
163 let blobs = scan_blobs(&path).unwrap();
164 let all = KIND_NODES | KIND_WAYS | KIND_RELATIONS;
165 // A relations-only pass skips this nodes-and-ways-and-relations blob only
166 // if we lie about its contents; do that, and check the lie comes back
167 // rather than a zero. A pass that dropped the kinds would make its own
168 // returned mask useless to the pass after it.
169 let (_, kinds) = run_pass(
170 &path,
171 &blobs,
172 Some(&[KIND_NODES]),
173 KIND_WAYS,
174 "test",
175 || (),
176 |_: &mut (), _| Ok(all),
177 )
178 .unwrap();
179 assert_eq!(kinds, vec![KIND_NODES]);
180
181 // A blob the pass does read reports what it actually saw.
182 let (_, kinds) = run_pass(
183 &path,
184 &blobs,
185 Some(&[KIND_WAYS]),
186 KIND_WAYS,
187 "test",
188 || (),
189 |_: &mut (), _| Ok(all),
190 )
191 .unwrap();
192 assert_eq!(kinds, vec![all]);
193 }
194
195 #[test]
196 fn the_compression_probe_accepts_zlib_and_rejects_zstd() {
197 let (path, dir) = testpbf::write_sample("pbf_probe");
198 let blobs = scan_blobs(&path).unwrap();
199 probe_compression(&path, &blobs).unwrap();
200
201 // One OSMData blob whose only field is `zstd_data`.
202 let blob = [7 << 3 | WIRE_BYTES, 1, 0];
203 let mut header = vec![1 << 3 | WIRE_BYTES, 7];
204 header.extend_from_slice(b"OSMData");
205 header.extend_from_slice(&[3 << 3 | proto::WIRE_VARINT, blob.len() as u8]);
206 let mut file = Vec::new();
207 file.extend_from_slice(&(header.len() as u32).to_be_bytes());
208 file.extend_from_slice(&header);
209 file.extend_from_slice(&blob);
210 let zstd_path = dir.join("zstd.osm.pbf");
211 std::fs::write(&zstd_path, &file).unwrap();
212
213 let blobs = scan_blobs(&zstd_path).unwrap();
214 assert_eq!(blobs.len(), 1);
215 let err = probe_compression(&zstd_path, &blobs).unwrap_err();
216 assert!(err.0.contains("zstd"), "{}", err.0);
217 }
218
219 /// Unsigned varint, for the two length-delimited fields the helpers below write. The
220 /// crate's `proto` has the decoder but no encoder — nothing in `osm_ingest` writes
221 /// protobuf outside tests.
222 fn put_uvarint(out: &mut Vec<u8>, mut value: u64) {
223 loop {
224 let byte = (value & 0x7f) as u8;
225 value >>= 7;
226 if value == 0 {
227 out.push(byte);
228 return;
229 }
230 out.push(byte | 0x80);
231 }
232 }
233
234 /// A zlib stream wrapping `data` in a single STORED deflate block.
235 ///
236 /// Hand-rolled rather than compressed, because `osm_ingest` takes miniz_oxide for its
237 /// inflate side only and a test should not pull in a compressor to make three bytes.
238 /// A stored block still exercises the whole path this cares about: the zlib header is
239 /// parsed and the Adler-32 trailer is verified exactly as it is for a real blob.
240 fn zlib_stored(data: &[u8]) -> Vec<u8> {
241 let mut out = vec![0x78, 0x01];
242 let len = data.len() as u16;
243 out.push(0x01); // BFINAL = 1, BTYPE = 00 (stored)
244 out.extend_from_slice(&len.to_le_bytes());
245 out.extend_from_slice(&(!len).to_le_bytes());
246 out.extend_from_slice(data);
247 let (mut a, mut b) = (1u32, 0u32);
248 for &byte in data {
249 a = (a + byte as u32) % 65521;
250 b = (b + a) % 65521;
251 }
252 out.extend_from_slice(&((b << 16) | a).to_be_bytes());
253 out
254 }
255
256 /// A `Blob` message carrying `zlib_data` and a `raw_size`.
257 fn zlib_blob(data: &[u8], raw_size: usize) -> Vec<u8> {
258 let stream = zlib_stored(data);
259 let mut blob = Vec::new();
260 blob.push(2 << 3 | proto::WIRE_VARINT);
261 put_uvarint(&mut blob, raw_size as u64);
262 blob.push(3 << 3 | WIRE_BYTES);
263 put_uvarint(&mut blob, stream.len() as u64);
264 blob.extend_from_slice(&stream);
265 blob
266 }
267
268 /// **The allocation bound on a parallel pass.** `run_pass_sink` gives each worker one
269 /// inflate buffer for the whole file, so `inflate_blob` must decompress *into* it.
270 ///
271 /// Assigning a fresh `Vec` over `out` instead measured 1.5 GB of a 2.19 GB California
272 /// peak — 64 workers each holding a blob buffer, briefly two, none of them reused —
273 /// and that peak was the whole build's, one second in. Nothing about the output bytes
274 /// changes either way, so only a capacity assertion can catch a regression.
275 #[test]
276 fn inflating_reuses_the_callers_buffer_rather_than_replacing_it() {
277 let big = vec![7u8; 40_000];
278 let small = b"tiny".to_vec();
279 let mut out = Vec::new();
280
281 inflate_blob(&zlib_blob(&big, big.len()), &mut out).expect("big");
282 assert_eq!(out, big, "the big blob must round trip");
283 let capacity = out.capacity();
284 assert!(capacity >= big.len(), "buffer must hold what it inflated");
285
286 inflate_blob(&zlib_blob(&small, small.len()), &mut out).expect("small");
287 assert_eq!(out, small, "the small blob must round trip");
288 assert_eq!(
289 out.capacity(),
290 capacity,
291 "a second, smaller blob must reuse the buffer rather than allocate a new one",
292 );
293 }
294
295 /// The allocating path verified the Adler-32 trailer, and the in-place one has to as
296 /// well. A corrupt blob that inflated silently would be a quietly incomplete graph.
297 #[test]
298 fn a_corrupt_adler_trailer_is_still_rejected() {
299 let data = b"the quick brown fox".to_vec();
300 let mut blob = zlib_blob(&data, data.len());
301 let last = blob.len() - 1;
302 blob[last] ^= 0xff;
303 let mut out = Vec::new();
304 let err = inflate_blob(&blob, &mut out).expect_err("a bad checksum must be refused");
305 assert!(err.0.contains("inflate failed"), "{}", err.0);
306 }
307
308 /// A `raw_size` smaller than the payload must error rather than hand back a truncated
309 /// block. The buffer is sized from `raw_size`, so `out.len()` matches it whatever
310 /// happened and the length check at the end of `inflate_blob` cannot see this.
311 #[test]
312 fn a_zlib_blob_whose_raw_size_is_too_small_is_rejected() {
313 let data = b"0123456789".to_vec();
314 let mut out = Vec::new();
315 let err = inflate_blob(&zlib_blob(&data, 4), &mut out)
316 .expect_err("a short raw_size must be refused");
317 assert!(err.0.contains("inflate"), "{}", err.0);
318 }
319
320 #[test]
321 fn raw_size_mismatch_is_rejected() {
322 // Blob claiming a raw_size that disagrees with the payload.
323 let mut blob = Vec::new();
324 blob.push(1 << 3 | WIRE_BYTES);
325 blob.push(3);
326 blob.extend_from_slice(b"abc");
327 blob.push(2 << 3 | proto::WIRE_VARINT);
328 blob.push(9);
329 let mut out = Vec::new();
330 assert!(inflate_blob(&blob, &mut out).is_err());
331 }
332
333 #[test]
334 fn unsupported_compression_is_reported() {
335 let mut blob = vec![7 << 3 | WIRE_BYTES, 1, 0];
336 let mut out = Vec::new();
337 let err = inflate_blob(&blob, &mut out).unwrap_err();
338 assert!(err.0.contains("zstd"), "{}", err.0);
339 blob[0] = 4 << 3 | WIRE_BYTES;
340 let err = inflate_blob(&blob, &mut out).unwrap_err();
341 assert!(err.0.contains("lzma"), "{}", err.0);
342 }
343
344 /// The blob-kinds sidecar round trips, and every guard rejects a file that no longer matches: a
345 /// stale sidecar must load as `None` (a full-scan fallback), never as a wrong mask.
346 #[test]
347 fn a_blob_kinds_sidecar_round_trips_and_the_guards_reject_a_changed_file() {
348 let dir = std::env::temp_dir().join(format!(
349 "osm_ingest_bk_{}_{:?}",
350 std::process::id(),
351 std::thread::current().id()
352 ));
353 let _ = std::fs::remove_dir_all(&dir);
354 std::fs::create_dir_all(&dir).unwrap();
355 let input = dir.join("in.osm.pbf");
356 std::fs::write(&input, b"a fake pbf, only its bytes matter here").unwrap();
357
358 let blobs: Vec<BlobLoc> =
359 (0..5).map(|i| BlobLoc { offset: i * 10, datasize: 10 }).collect();
360 let kinds = vec![KIND_NODES, KIND_NODES | KIND_WAYS, KIND_WAYS, KIND_RELATIONS, 0];
361 write_blob_kinds(&dir, &input, &blobs, &kinds).unwrap();
362
363 // Happy path: same file, same blob count.
364 assert_eq!(load_blob_kinds(&dir, &input, &blobs).as_deref(), Some(kinds.as_slice()));
365 // Place and time are not content: the same bytes copied elsewhere and touched later still
366 // match, and the sidecar written for the copy is byte-identical.
367 let elsewhere = dir.join("moved");
368 std::fs::create_dir_all(&elsewhere).unwrap();
369 let copy = elsewhere.join("renamed.osm.pbf");
370 std::thread::sleep(std::time::Duration::from_millis(20));
371 std::fs::copy(&input, &copy).unwrap();
372 assert_eq!(load_blob_kinds(&dir, &copy, &blobs).as_deref(), Some(kinds.as_slice()));
373 write_blob_kinds(&elsewhere, &copy, &blobs, &kinds).unwrap();
374 assert_eq!(
375 std::fs::read(dir.join(BLOB_KINDS_FILE)).unwrap(),
376 std::fs::read(elsewhere.join(BLOB_KINDS_FILE)).unwrap(),
377 "the sidecar depends on the input's path or mtime"
378 );
379 // Same length, different bytes: the content guard fires.
380 std::fs::write(&copy, b"a fake pbf, only its BYTES matter here").unwrap();
381 assert!(load_blob_kinds(&dir, &copy, &blobs).is_none(), "content guard did not fire");
382 // A resized blob in the index is a different file even with the same bytes sampled.
383 let mut moved = blobs.clone();
384 moved[2].datasize += 1;
385 assert!(load_blob_kinds(&dir, &input, &moved).is_none(), "blob-index guard did not fire");
386 // A different blob count is a different file to pass 1, whatever the sidecar claims.
387 let fewer: Vec<BlobLoc> = blobs[..4].to_vec();
388 assert!(load_blob_kinds(&dir, &input, &fewer).is_none(), "blob-count guard did not fire");
389 // A changed source length must invalidate it.
390 std::fs::write(&input, b"a different length entirely").unwrap();
391 assert!(load_blob_kinds(&dir, &input, &blobs).is_none(), "length guard did not fire");
392 // Wrong magic: a foreign or corrupt file at the path is rejected, not misread.
393 std::fs::write(dir.join(BLOB_KINDS_FILE), b"not a real sidecar").unwrap();
394 assert!(load_blob_kinds(&dir, &input, &blobs).is_none(), "magic guard did not fire");
395 // A missing sidecar is simply a full-scan fallback.
396 std::fs::remove_file(dir.join(BLOB_KINDS_FILE)).unwrap();
397 assert!(load_blob_kinds(&dir, &input, &blobs).is_none(), "a missing sidecar must be None");
398
399 let _ = std::fs::remove_dir_all(&dir);
400 }
401}