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

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

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