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

Modern-Apps.git / scripts / maps / mamaps_build / src / store_part5.rs

store_part5.rs401 lines · 20.7 KiBRaw
1#[cfg(test)]
2mod tests {
3 /// **The guard on chunk skipping.** A zoom-filtered read must yield exactly what a full read
4 /// yields after the same filter, in the same order. Otherwise skipping drops real geometry, and
5 /// the symptom would be a few tiles quietly missing features at one zoom -- no error, no crash.
6 #[test]
7 fn skipping_chunks_yields_exactly_what_a_full_read_would() {
8 let path = temp("zoomfilter");
9 let mut sink = Sink::create(&path).expect("create");
10 // Several chunks' worth, with min_zoom varying so chunks genuinely differ in what they hold.
11 let mut expected_by_zoom: Vec<Vec<u16>> = vec![Vec::new(); 15];
12 for i in 0..500u16 {
13 let min_zoom = (i % 15) as u8;
14 let kind = i.max(1);
15 let class = Class::line(dict::LAYER_ROADS, kind, min_zoom);
16 let line = vec![(-120.0 + i as f64 * 0.001, 35.0), (-119.9, 35.1)];
17 sink.push(&class, &EncodedGeom::live(&Geometry::Lines(vec![line])).expect("encode")).expect("push");
18 for z in min_zoom as usize..15 {
19 expected_by_zoom[z].push(kind);
20 }
21 }
22 let store = sink.finish(&path).expect("finish");
23
24 for z in 0..15u8 {
25 let mut got = Vec::new();
26 let mut reader = store.reader_for_zoom(z).expect("reader");
27 while let Some(feature) = reader.next().expect("read") {
28 // Asserted, not filtered. The chunk index only skips a chunk when *every* feature
29 // in it is too deep, so a kept chunk still carries features this zoom does not
30 // draw -- and the reader's lanes are now what drops them. Anything arriving below
31 // the floor means that filter has gone missing.
32 assert!(feature.class.min_zoom <= z, "z{z} was handed a z{} feature", feature.class.min_zoom);
33 got.push(feature.class.kind);
34 }
35 assert_eq!(got, expected_by_zoom[z as usize], "z{z}");
36 }
37
38 // The deepest zoom keeps every chunk, so it must match the sequential reader exactly.
39 let mut full = Vec::new();
40 let mut reader = store.reader().expect("reader");
41 while let Some(feature) = reader.next().expect("read") {
42 full.push(feature.class.kind);
43 }
44 let mut deep = Vec::new();
45 let mut reader = store.reader_for_zoom(14).expect("reader");
46 while let Some(feature) = reader.next().expect("read") {
47 deep.push(feature.class.kind);
48 }
49 assert_eq!(deep, full, "at the deepest zoom nothing is skipped");
50 }
51
52 use super::*;
53 use crate::schema;
54 use tilecodec::mamaps::dict;
55
56 fn temp(name: &str) -> PathBuf {
57 std::env::temp_dir().join(format!("mamaps_store_{}_{name}", std::process::id()))
58 }
59
60 #[test]
61 fn a_class_survives_being_packed_into_one_integer() {
62 let class = Class {
63 layer: dict::LAYER_ROADS,
64 kind: 0xbeef,
65 kind_detail: 0xcafe,
66 flags: 0b1010_0101,
67 area: true,
68 min_zoom: 14,
69 min_area_px: 8.0,
70 };
71 assert_eq!(unpack(pack(&class).expect("pack")), class);
72
73 // And the zero case, which is most features.
74 let plain = Class::line(dict::LAYER_LANDTYPE, 1, 0);
75 assert_eq!(unpack(pack(&plain).expect("pack")), plain);
76 }
77
78 /// **Every class the schema can actually produce** has to round-trip, or a feature arrives at the
79 /// tiler as something else. Cheaper to prove exhaustively than to trust the bit widths.
80 #[test]
81 fn every_class_the_schema_emits_round_trips() {
82 let cases: &[&[(&str, &str)]] = &[
83 &[("natural", "water")],
84 &[("waterway", "river")],
85 &[("building", "yes")],
86 &[("building:part", "yes")],
87 &[("highway", "motorway")],
88 &[("highway", "motorway_link"), ("bridge", "yes"), ("tunnel", "yes")],
89 &[("railway", "subway")],
90 &[("boundary", "administrative"), ("admin_level", "2")],
91 &[("boundary", "administrative"), ("admin_level", "8")],
92 &[("natural", "wood")],
93 &[("leisure", "park")],
94 &[("leisure", "pitch")],
95 &[("landuse", "residential")],
96 &[("place", "island")],
97 &[("natural", "cliff")],
98 ];
99 for tags in cases {
100 let class =
101 schema::classify(*tags, true, schema::Layers::all()).expect("classified");
102 let bits = pack(&class).unwrap_or_else(|e| panic!("{tags:?} will not pack: {e:?}"));
103 assert_eq!(unpack(bits), class, "{tags:?}");
104 }
105 }
106
107 /// A threshold that cannot be represented is refused, not rounded. A minimum area quietly
108 /// changed is a layer quietly wrong, and it would be invisible.
109 #[test]
110 fn an_unrepresentable_class_is_refused_rather_than_rounded() {
111 let fractional = Class { min_area_px: 2.5, ..Class::area(0, 1, 0) };
112 assert!(pack(&fractional).is_err(), "a fractional threshold");
113 let huge = Class { min_area_px: 4096.0, ..Class::area(0, 1, 0) };
114 assert!(pack(&huge).is_err(), "a threshold past a byte");
115 let deep = Class { min_zoom: 32, ..Class::area(0, 1, 0) };
116 assert!(pack(&deep).is_err(), "a zoom past five bits");
117 }
118
119 /// **The lane partition, across every lane and past the wrap.**
120 ///
121 /// [`ZoomReader`] deals chunks over [`prefetch_lanes`] threads and reads them back by walking
122 /// the lanes in the same order, and the archive's whole feature ordering rests on those two
123 /// agreeing. Nothing else here reaches that code: the other store fixtures are a few hundred
124 /// features, which is fewer chunks than there are lanes, so they run on a handful of lanes with
125 /// one chunk each and would pass against a partition that shuffled the file.
126 ///
127 /// So this writes three full rounds over every lane, sized off the constants rather than a
128 /// literal so it keeps its teeth if they change. Three rather than one because the wrap is the
129 /// interesting part — a reader that dealt correctly but read back assuming one chunk per lane
130 /// would agree for the first round and diverge after it. Every feature carries a coordinate
131 /// unique to its position, so the assertion is the file's exact order rather than a count or a
132 /// checksum.
133 #[test]
134 fn a_zoom_reader_returns_chunks_in_file_order_across_every_lane() {
135 let count = 3 * prefetch_lanes() * PREFETCH_RUN * NORM_CHUNK_FEATURES as usize;
136 // Unique per feature and inside real lon/lat, so the bbox fold has nothing to complain
137 // about. 997 is prime, so it shares no factor with the lane or chunk counts and no aliasing
138 // can hide a swapped chunk.
139 //
140 // Compared as e7 integers, never as `f64`. The spill quantises to the same 1e-7 grid the
141 // archive header uses, so a round trip is exact on that grid and an ULP apart off it — and
142 // an ULP is not what this test is about.
143 let at = |i: usize| (-120.0 + (i % 997) as f64 * 0.0001, 35.0 + (i / 997) as f64 * 0.0001);
144 let grid = |(x, y): (f64, f64)| ((x * 1e7).round() as i64, (y * 1e7).round() as i64);
145
146 let path = temp("laneorder");
147 let mut sink = Sink::create(&path).expect("create");
148 let class = Class::line(dict::LAYER_ROADS, schema::kind("highway"), 0);
149 for i in 0..count {
150 let (x, y) = at(i);
151 sink.push(&class, &EncodedGeom::live(&Geometry::Lines(vec![vec![(x, y), (x, y + 0.0001)]])).expect("encode"))
152 .expect("push");
153 }
154 let store = sink.finish(&path).expect("finish");
155 assert_eq!(store.len(), count as u64);
156
157 // z0 keeps every chunk, because the class above is drawn from z0 -- so this is the whole
158 // file, through the prefetch, with every lane loaded.
159 let mut got = Vec::with_capacity(count);
160 let mut reader = store.reader_for_zoom(0).expect("reader");
161 while let Some(feature) = reader.next().expect("read") {
162 let Geometry::Lines(lines) = &feature.geometry else { panic!("a line went in") };
163 got.push(grid(lines[0][0]));
164 }
165 let expected: Vec<(i64, i64)> = (0..count).map(|i| grid(at(i))).collect();
166 assert_eq!(got.len(), expected.len(), "the prefetch lost or invented features");
167 // Located rather than just reported: `assert_eq` on two vectors this long prints something
168 // nobody can read, and which chunk went astray is the whole diagnosis.
169 if let Some(i) = (0..count).find(|&i| got[i] != expected[i]) {
170 let chunk = i / NORM_CHUNK_FEATURES as usize;
171 panic!(
172 "feature {i} (chunk {chunk}, lane {}) is {:?}, expected {:?}",
173 (chunk / PREFETCH_RUN) % prefetch_lanes(),
174 got[i],
175 expected[i],
176 );
177 }
178 }
179
180 #[test]
181 fn features_written_come_back_in_order_with_their_geometry() {
182 let path = temp("roundtrip");
183 let mut sink = Sink::create(&path).expect("create");
184 let square = vec![vec![
185 (-120.0, 35.0),
186 (-119.0, 35.0),
187 (-119.0, 36.0),
188 (-120.0, 36.0),
189 (-120.0, 35.0),
190 ]];
191 let lake = Class::area(dict::LAYER_LANDTYPE, schema::kind("lake"), 6);
192 let road = Class::line(dict::LAYER_ROADS, schema::kind("highway"), 3);
193 sink.push(&lake, &EncodedGeom::live(&Geometry::Polygons(vec![square.clone()])).expect("encode")).expect("push");
194 sink.push(&road, &EncodedGeom::live(&Geometry::Lines(vec![vec![(-120.0, 35.0), (-119.5, 35.5)]])).expect("encode"))
195 .expect("push");
196 let store = sink.finish(&path).expect("finish");
197
198 assert_eq!(store.len(), 2);
199 // The bbox came for free, rather than from a pass of its own over the whole file.
200 assert_eq!(store.bbox(), (-1_200_000_000, 350_000_000, -1_190_000_000, 360_000_000));
201
202 let mut reader = store.reader().expect("reader");
203 let first = reader.next().expect("read").expect("a feature");
204 assert_eq!(first.class, lake);
205 assert!(matches!(first.geometry, Geometry::Polygons(ref p) if p[0] == square));
206 let second = reader.next().expect("read").expect("a feature");
207 assert_eq!(second.class, road);
208 assert!(matches!(second.geometry, Geometry::Lines(_)));
209 assert!(reader.next().expect("read").is_none(), "and then the end");
210
211 // Re-readable, because the tiler reads it once per zoom.
212 let mut again = store.reader().expect("reader");
213 assert_eq!(again.next().expect("read").expect("a feature").class, lake);
214 }
215
216 /// Ids, classes and refs all come back exactly, in the order they went in. The one thing the
217 /// ways spill has to guarantee, because the archive's feature order is this file's record order.
218 #[test]
219 fn spilled_ways_come_back_in_the_order_and_with_the_refs_they_went_in_with() {
220 let path = temp("ways_roundtrip");
221 let lake = Class::area(dict::LAYER_LANDTYPE, schema::kind("lake"), 6);
222 let road = Class::line(dict::LAYER_ROADS, schema::kind("highway"), 3);
223 // Refs chosen to exercise the delta coding: a large first id, a run of neighbours, a jump
224 // backwards, and a way with none at all.
225 let cases: Vec<(i64, Class, Vec<i64>, u8, Vec<u16>, Vec<u16>, Carriageway)> = vec![
226 (1, lake, vec![10_000_000_001, 10_000_000_002, 10_000_000_003, 9_000_000_000], 0, vec![], vec![], Carriageway::default()),
227 // A four-lane road with forward and backward turn masks and a 3/1 split, all surviving
228 // the spill.
229 (
230 2,
231 road,
232 vec![],
233 4,
234 vec![4u16, 2, 2, 34],
235 vec![1, 2],
236 Carriageway { forward: 3, backward: 1, solid_dividers: 0b101 },
237 ),
238 (i64::MAX, lake, vec![-5, 0, 5, i64::MAX, i64::MIN], 0, vec![], vec![], Carriageway::default()),
239 ];
240 let mut sink = WaySink::create(&path).expect("create");
241 for (id, class, refs, lanes, fwd, bwd, carriageway) in &cases {
242 sink.push(*id, class, refs, None, *lanes, fwd, bwd, *carriageway, None).expect("push");
243 }
244 let counts = sink.finish().expect("finish");
245 assert_eq!(counts.ways, 3, "one record per push");
246 assert_eq!(counts.refs, 9, "refs summed over every way, so `needed` can be sized once");
247
248 let mut reader = WayReader::open(&path).expect("open");
249 let mut refs: Vec<i64> = Vec::new();
250 for (id, class, expected, lanes, fwd, bwd, carriageway) in &cases {
251 let (got_id, got_class, got_name, got_lanes, got_fwd, got_bwd, got_cw, _got_building) =
252 reader.next(&mut refs).expect("read").expect("a way");
253 assert_eq!(got_id, *id);
254 assert_eq!(got_class, *class);
255 assert_eq!(got_name, None, "these ways are nameless");
256 assert_eq!(got_lanes, *lanes, "a road's lane count survives the spill");
257 assert_eq!(&got_fwd, fwd, "forward turn masks survive the spill");
258 assert_eq!(&got_bwd, bwd, "backward turn masks survive the spill");
259 assert_eq!(got_cw, *carriageway, "the directional split survives the spill");
260 assert_eq!(&refs, expected);
261 }
262 assert!(reader.next(&mut refs).expect("read").is_none(), "and then the end");
263 assert!(refs.is_empty(), "the caller's buffer is cleared even at the end");
264 }
265
266 /// The anon ways spill stages byte-identical records: write through
267 /// `create_anon`, read back through `open_anon`, same ids/classes/refs in
268 /// the same order. This is what lets -Verify hold the anon build to the
269 /// same hash as the file build.
270 #[test]
271 fn spilled_ways_come_back_identical_from_anonymous_memory() {
272 let lake = Class::area(dict::LAYER_LANDTYPE, schema::kind("lake"), 6);
273 let road = Class::line(dict::LAYER_ROADS, schema::kind("highway"), 3);
274 let cases: Vec<(i64, Class, Vec<i64>, u8, Vec<u16>, Vec<u16>, Carriageway)> = vec![
275 (1, lake, vec![10_000_000_001, 10_000_000_002, 9_000_000_000], 0, vec![], vec![], Carriageway::default()),
276 (
277 2,
278 road,
279 vec![],
280 4,
281 vec![4u16, 2],
282 vec![1],
283 Carriageway { forward: 3, backward: 1, solid_dividers: 0b101 },
284 ),
285 ];
286 // File path (reference).
287 let path = temp("ways_anon_file");
288 let mut sink = WaySink::create(&path).expect("create");
289 for (id, class, refs, lanes, fwd, bwd, carriageway) in &cases {
290 sink.push(*id, class, refs, None, *lanes, fwd, bwd, *carriageway, None).expect("push");
291 }
292 let file_counts = sink.finish().expect("finish");
293 // Anon path.
294 let mut asink = WaySink::create_anon(&path).expect("create_anon");
295 for (id, class, refs, lanes, fwd, bwd, carriageway) in &cases {
296 asink.push(*id, class, refs, None, *lanes, fwd, bwd, *carriageway, None).expect("push");
297 }
298 let (anon_counts, store) = asink.finish_anon().expect("finish_anon");
299 assert_eq!(anon_counts.ways, file_counts.ways);
300 assert_eq!(anon_counts.refs, file_counts.refs);
301 assert_eq!(anon_counts.max_ref, file_counts.max_ref);
302 assert_eq!(
303 store.len(),
304 std::fs::metadata(&path).expect("stat").len(),
305 "staged bytes must match"
306 );
307
308 let store = std::sync::Arc::new(store);
309 let mut reader = WayReader::open_anon(&path, std::sync::Arc::clone(&store)).expect("open_anon");
310 let mut refs: Vec<i64> = Vec::new();
311 for (id, class, expected, lanes, fwd, bwd, carriageway) in &cases {
312 let (got_id, got_class, got_name, got_lanes, got_fwd, got_bwd, got_cw, _) =
313 reader.next(&mut refs).expect("read").expect("a way");
314 assert_eq!(got_id, *id);
315 assert_eq!(got_class, *class);
316 assert_eq!(got_name, None);
317 assert_eq!(got_lanes, *lanes);
318 assert_eq!(&got_fwd, fwd);
319 assert_eq!(&got_bwd, bwd);
320 assert_eq!(got_cw, *carriageway);
321 assert_eq!(&refs, expected);
322 }
323 assert!(reader.next(&mut refs).expect("read").is_none(), "and then the end");
324 // A second reader over the same store replays from the front: the four
325 // stage-A readers each open their own.
326 let mut again = WayReader::open_anon(&path, store).expect("open_anon");
327 assert!(again.next(&mut refs).expect("read").is_some());
328 }
329
330 /// The spill's whole premise is that a PBF's ways arrive sorted, so materialisation can stream
331 /// the file instead of sorting a map's keys. An input that breaks the premise has to say so:
332 /// accepting it would reorder the archive, and a reordered archive is only visible as a
333 /// different hash of 655 MB.
334 #[test]
335 fn a_way_id_that_does_not_advance_is_refused_rather_than_reordering_the_archive() {
336 let path = temp("ways_unsorted");
337 let class = Class::line(dict::LAYER_ROADS, schema::kind("highway"), 3);
338 let mut sink = WaySink::create(&path).expect("create");
339 let none = Carriageway::default();
340 sink.push(100, &class, &[1, 2], None, 0, &[], &[], none, None).expect("push");
341 assert!(sink.push(99, &class, &[3], None, 0, &[], &[], none, None).is_err(), "an id going backwards");
342 assert!(sink.push(100, &class, &[3], None, 0, &[], &[], none, None).is_err(), "and the same id twice");
343 sink.push(101, &class, &[3], None, 0, &[], &[], none, None).expect("but forwards is fine");
344 }
345
346 /// A truncated spill is a corrupt file, not a short one. It was written by `WaySink` in this
347 /// same process moments earlier, so a record that will not parse means the file is not ours.
348 #[test]
349 fn a_truncated_ways_spill_is_an_error_rather_than_a_silently_short_read() {
350 let path = temp("ways_truncated");
351 let class = Class::area(dict::LAYER_LANDTYPE, schema::kind("lake"), 6);
352 let mut sink = WaySink::create(&path).expect("create");
353 let none = Carriageway::default();
354 sink.push(1, &class, &[7, 8, 9], None, 0, &[], &[], none, None).expect("push");
355 sink.push(2, &class, &[11, 12, 13], Some("named"), 0, &[], &[], none, None).expect("push");
356 sink.finish().expect("finish");
357
358 let whole = std::fs::read(&path).expect("read");
359 // Cut the second record short, leaving it claiming refs the file does not hold.
360 std::fs::write(&path, &whole[..whole.len() - 2]).expect("truncate");
361 let mut reader = WayReader::open(&path).expect("open");
362 let mut refs: Vec<i64> = Vec::new();
363 assert!(reader.next(&mut refs).expect("read").is_some(), "the first record survives");
364 assert!(reader.next(&mut refs).is_err(), "the cut one does not");
365 }
366
367 /// Delta coding is the reason the file can be read twice without the I/O mattering. Worth
368 /// pinning: a regression to fixed-width would be invisible except as a slower build.
369 #[test]
370 fn near_consecutive_refs_cost_about_a_byte_each() {
371 let path = temp("ways_size");
372 let class = Class::line(dict::LAYER_ROADS, schema::kind("highway"), 3);
373 let refs: Vec<i64> = (0..1000).map(|i| 10_000_000_000 + i).collect();
374 let mut sink = WaySink::create(&path).expect("create");
375 sink.push(1, &class, &refs, None, 0, &[], &[], Carriageway::default(), None).expect("push");
376 sink.finish().expect("finish");
377 let bytes = std::fs::metadata(&path).expect("metadata").len();
378 // The first ref is a full-width id; every one after it is a delta of 1, one byte.
379 assert!(bytes < 1100, "{bytes} bytes for 1000 refs, against 8000 fixed-width");
380 }
381
382 /// A named way round-trips its label; a truncated name errors like a truncated ref.
383 #[test]
384 fn a_named_way_keeps_its_name() {
385 let path = temp("ways_named");
386 let class = Class::line(dict::LAYER_POI, schema::kind("cafe"), 15);
387 let mut sink = WaySink::create(&path).expect("create");
388 let none = Carriageway::default();
389 sink.push(1, &class, &[7, 8], Some("Café"), 0, &[], &[], none, None).expect("push");
390 sink.push(2, &class, &[9], None, 0, &[], &[], none, None).expect("push");
391 sink.finish().expect("finish");
392 let mut reader = WayReader::open(&path).expect("open");
393 let mut refs: Vec<i64> = Vec::new();
394 let (_, _, name, _, _, _, _, _) = reader.next(&mut refs).expect("read").expect("a way");
395 assert_eq!(name.as_deref(), Some("Café"), "UTF-8 survives the spill");
396 let (_, _, name, _, _, _, _, _) = reader.next(&mut refs).expect("read").expect("a way");
397 assert_eq!(name, None);
398 }
399}
400
401