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

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

tilespill_part3.rs458 lines · 20.4 KiBRaw
1#[cfg(test)]
2mod tests {
3 use super::*;
4 use tilecodec::mamaps::body::{GEOM_LINE, GEOM_POLYGON, WINDING_HOLE, WINDING_OUTER};
5
6 pub(super) fn tmp(name: &str) -> PathBuf {
7 use std::sync::atomic::AtomicU64;
8 static NEXT: AtomicU64 = AtomicU64::new(0);
9 std::env::temp_dir().join(format!(
10 "mamaps_tilespill_{}_{}_{name}",
11 std::process::id(),
12 NEXT.fetch_add(1, Ordering::Relaxed),
13 ))
14 }
15
16 /// The tile-chunk scratch is unlinked at creation on Unix: nothing named is left in its
17 /// directory while chunks are written and read back, and the books still balance.
18 #[test]
19 fn the_chunk_scratch_leaves_no_name_behind() {
20 let dir = tmp("unlinkdir");
21 std::fs::create_dir_all(&dir).unwrap();
22 let spill = ChunkSpill::create(dir.join("tiles.chunks.tmp")).unwrap();
23 let chunk = spill.write_chunk(std::collections::BTreeMap::new()).unwrap();
24 #[cfg(unix)]
25 assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "a chunk scratch name was left");
26 let mut reader = spill.reader(&chunk, 4096);
27 assert!(reader.next().unwrap().is_none());
28 spill.check_books().unwrap();
29 drop(spill);
30 assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0);
31 std::fs::remove_dir(&dir).unwrap();
32 }
33
34 pub(super) fn feature(kind: u16, detail: u16, geom: u8, flags: u8, at: u32, n: u32) -> BodyFeature {
35 BodyFeature {
36 kind,
37 kind_detail: detail,
38 geom_type: geom,
39 flags,
40 name_idx: tilecodec::mamaps::body::NAME_NONE,
41 parts_offset: at,
42 part_count: n,
43 transit_color: 0,
44 transit_ordinal: 0,
45 transit_lanes: 0,
46 transit_taper: 0,
47 lane_count: 0,
48 }
49 }
50
51 fn named(kind: u16, name_idx: u16) -> BodyFeature {
52 BodyFeature {
53 kind,
54 kind_detail: 0,
55 geom_type: tilecodec::mamaps::body::GEOM_POINT,
56 flags: 0,
57 name_idx,
58 parts_offset: 0,
59 part_count: 1,
60 transit_color: 0,
61 transit_ordinal: 0,
62 transit_lanes: 0,
63 transit_taper: 0,
64 lane_count: 0,
65 }
66 }
67
68 fn entry(layer_id: u8, features: Vec<BodyFeature>, names: &[&str]) -> ChunkEntry {
69 let mut layer = BodyLayer::new(layer_id);
70 layer.features = features;
71 for (i, _) in layer.features.iter().enumerate() {
72 layer.parts.push(Part {
73 coord_start: i as u32,
74 point_count: 1,
75 winding: WINDING_OUTER,
76 });
77 layer.coords.push((i as i16, 0));
78 }
79 // Fix up parts_offset to match the pushed parts (all features above use offset 0).
80 for (i, feature) in layer.features.iter_mut().enumerate() {
81 feature.parts_offset = i as u32;
82 }
83 ChunkEntry { layer, names: names.iter().map(|s| s.to_string()).collect(), ids: Vec::new(), turn_lanes: Vec::new(), buildings: Vec::new(), carriageways: Vec::new() }
84 }
85
86 /// Every shape an entry can take, including the empty ones that a naive length check would let
87 /// through and a naive decode would trip on — plus a named entry, because names are the one
88 /// variable-length arena in the spill.
89 pub(super) fn every_layer() -> Vec<((u64, u8), ChunkEntry)> {
90 let plain = |layer_id: u8, features: Vec<BodyFeature>| ChunkEntry {
91 layer: BodyLayer { layer_id, features, parts: Vec::new(), coords: Vec::new() },
92 names: Vec::new(),
93 ids: Vec::new(),
94 turn_lanes: Vec::new(),
95 buildings: Vec::new(),
96 carriageways: Vec::new(),
97 };
98 vec![
99 // Empty layer: no features, no parts, no coords.
100 ((1, 0), ChunkEntry::new(0)),
101 // Features but no parts and no coords, which `push` cannot make and a corrupt file can.
102 ((2, 1), plain(1, vec![feature(1, 2, GEOM_LINE, 0, 0, 0)])),
103 // A part with no coordinates.
104 (
105 (3, 2),
106 ChunkEntry {
107 layer: BodyLayer {
108 layer_id: 2,
109 features: vec![feature(3, 4, GEOM_LINE, 1, 0, 1)],
110 parts: vec![Part {
111 coord_start: 0,
112 point_count: 0,
113 winding: WINDING_OUTER,
114 }],
115 coords: Vec::new(),
116 },
117 names: Vec::new(),
118 ids: Vec::new(),
119 turn_lanes: Vec::new(),
120 buildings: Vec::new(),
121 carriageways: Vec::new(),
122 },
123 ),
124 // The extremes of every field: `u16::MAX` kinds, `i16` at both ends, a hole.
125 (
126 (4, 3),
127 ChunkEntry {
128 layer: BodyLayer {
129 layer_id: 3,
130 features: vec![
131 feature(u16::MAX, u16::MAX, GEOM_POLYGON, 0x0f, 0, 2),
132 feature(0, 0, GEOM_POLYGON, 0, 2, 1),
133 ],
134 parts: vec![
135 Part { coord_start: 0, point_count: 2, winding: WINDING_OUTER },
136 Part { coord_start: 2, point_count: 2, winding: WINDING_HOLE },
137 Part { coord_start: 4, point_count: 1, winding: WINDING_OUTER },
138 ],
139 coords: vec![
140 (i16::MIN, i16::MAX),
141 (i16::MAX, i16::MIN),
142 (0, 0),
143 (-1, 1),
144 (32_767, -32_768),
145 ],
146 },
147 names: Vec::new(),
148 ids: Vec::new(),
149 turn_lanes: Vec::new(),
150 buildings: Vec::new(),
151 carriageways: Vec::new(),
152 },
153 ),
154 // Several layers on one tile, which is what the merge collapses.
155 ((5, 1), ChunkEntry::new(1)),
156 (
157 (5, 7),
158 ChunkEntry {
159 layer: BodyLayer {
160 layer_id: 7,
161 features: vec![feature(9, 9, GEOM_LINE, 0, 0, 1)],
162 parts: vec![Part {
163 coord_start: 0,
164 point_count: 3,
165 winding: WINDING_OUTER,
166 }],
167 coords: vec![(1, 2), (3, 4), (5, 6)],
168 },
169 names: Vec::new(),
170 ids: Vec::new(),
171 turn_lanes: Vec::new(),
172 buildings: Vec::new(),
173 carriageways: Vec::new(),
174 },
175 ),
176 ((5, 10), ChunkEntry::new(10)),
177 // A named entry: two point labels sharing one name plus an unnamed one.
178 ((6, 8), entry(8, vec![named(3, 1), named(5, 1), named(7, 0)], &["Café"])),
179 // The id arena, which only `places` and `poi` carry: a real tagged OSM id, ID_NONE
180 // for a feature with no upstream element, and a value with its top bit set so a
181 // sign-extension bug in the u64 round trip cannot hide.
182 (
183 (7, 8),
184 ChunkEntry {
185 ids: vec![
186 crate::extract::tagged_id(240_109_189, crate::extract::ELEMENT_NODE),
187 tilecodec::mamaps::body::ID_NONE,
188 u64::MAX,
189 ],
190 ..entry(8, vec![named(3, 1), named(5, 0), named(7, 0)], &["Bar"])
191 },
192 ),
193 // The carriageway arena, which only `roads` carries: a divided road, a one-way with
194 // every lane forward, and a road whose split was never surveyed — all three in one
195 // entry, because the section is dense and the unsurveyed one still needs its slot.
196 (
197 (8, 4),
198 ChunkEntry {
199 carriageways: vec![
200 Carriageway { forward: 3, backward: 1, solid_dividers: 0b101 },
201 Carriageway { forward: 2, backward: 0, solid_dividers: u32::MAX },
202 Carriageway::default(),
203 ],
204 ..entry(4, vec![named(1, 0), named(2, 0), named(3, 0)], &[])
205 },
206 ),
207 ]
208 }
209
210 pub(super) fn drain(spill: &ChunkSpill, at: &ChunkRef, window: usize) -> Vec<((u64, u8), ChunkEntry)> {
211 let mut reader = spill.reader(at, window);
212 let mut out = Vec::new();
213 while let Some(entry) = reader.next().expect("read an entry back") {
214 out.push(entry);
215 }
216 out
217 }
218
219 #[test]
220 fn a_chunk_round_trips_through_the_scratch_file() {
221 let spill = ChunkSpill::create(tmp("roundtrip")).expect("create");
222 let want = every_layer();
223 let map: BTreeMap<(u64, u8), ChunkEntry> = want.iter().cloned().collect();
224 let at = spill.write_chunk(map).expect("write");
225 assert_eq!(at.entries, want.len() as u64);
226 assert_eq!(drain(&spill, &at, 1 << 16), want);
227 spill.check_books().expect("the books balance");
228 }
229
230 /// **The silent one.** A `ChunkEntry.carriageways` that never reaches the spill is dropped on
231 /// every build that spills chunks — which is every real build — and the archive comes out with
232 /// no carriageway table, no lane markings and no error anywhere. Nothing else in this module
233 /// would notice: the books balance, the features are all there, and the map merely looks like
234 /// the renderer is at fault.
235 ///
236 /// So the section is asserted on its own rather than only inside `every_layer`: a road with a
237 /// divided carriageway, a one-way with every lane forward, and one whose split was never
238 /// surveyed — the last because the section is dense and its slot has to survive too.
239 #[test]
240 fn a_carriageway_section_survives_the_scratch_file() {
241 let spill = ChunkSpill::create(tmp("carriageways")).expect("create");
242 let want = ChunkEntry {
243 carriageways: vec![
244 Carriageway { forward: 3, backward: 1, solid_dividers: 0b101 },
245 Carriageway { forward: 2, backward: 0, solid_dividers: u32::MAX },
246 Carriageway::default(),
247 ],
248 ..entry(4, vec![named(1, 0), named(2, 0), named(3, 0)], &[])
249 };
250 let mut map: BTreeMap<(u64, u8), ChunkEntry> = BTreeMap::new();
251 map.insert((1, 4), want.clone());
252 let at = spill.write_chunk(map).expect("write");
253 let got = drain(&spill, &at, 1 << 16);
254 assert_eq!(got, vec![((1u64, 4u8), want)]);
255 // And the books, which are what would catch a section written but not accounted for.
256 spill.check_books().expect("the books balance");
257 }
258
259 /// A layer with no surveyed split writes no section at all, so a `boundaries` or `water` tile
260 /// pays nothing for a table that only roads ever have.
261 #[test]
262 fn an_entry_with_no_carriageways_writes_no_section() {
263 let spill = ChunkSpill::create(tmp("nocarriageways")).expect("create");
264 let bare = entry(4, vec![named(1, 0), named(2, 0)], &[]);
265 let mut map: BTreeMap<(u64, u8), ChunkEntry> = BTreeMap::new();
266 map.insert((1, 4), bare.clone());
267 let at = spill.write_chunk(map).expect("write");
268 let with = ChunkEntry {
269 carriageways: vec![Carriageway::default(); 2],
270 ..entry(4, vec![named(1, 0), named(2, 0)], &[])
271 };
272 let mut map: BTreeMap<(u64, u8), ChunkEntry> = BTreeMap::new();
273 map.insert((1, 4), with);
274 let at_with = spill.write_chunk(map).expect("write");
275 assert_eq!(
276 at_with.len - at.len,
277 2 * CARRIAGEWAY_RECORD_LEN as u64,
278 "the section costs exactly one record per feature and nothing when absent",
279 );
280 assert_eq!(drain(&spill, &at, 1 << 16), vec![((1u64, 4u8), bare)]);
281 }
282
283 /// The read accounting survives a buffer compaction mid-entry. Names are pulled one inline
284 /// length at a time, so a narrow window tops the buffer up (compacting it) halfway through
285 /// an entry's names — and the bytes-read counter used to difference two offsets across that
286 /// compaction, undercounting by the compacted prefix. California z12 caught it: a megabyte
287 /// short on `check_books`. Narrow window + many long names forces the compaction here.
288 #[test]
289 fn a_narrow_window_compacting_mid_entry_still_balances_the_books() {
290 let spill = ChunkSpill::create(tmp("compactnames")).expect("create");
291 let names: Vec<String> = (0..40).map(|i| format!("name-{i}-with-padding-to-lengthen")).collect();
292 let features: Vec<BodyFeature> = names
293 .iter()
294 .enumerate()
295 .map(|(i, _)| BodyFeature {
296 kind: 1,
297 kind_detail: 0,
298 geom_type: tilecodec::mamaps::body::GEOM_POINT,
299 flags: 0,
300 name_idx: i as u16 + 1,
301 parts_offset: i as u32,
302 part_count: 1,
303 transit_color: 0,
304 transit_ordinal: 0,
305 transit_lanes: 0,
306 transit_taper: 0,
307 lane_count: 0,
308 })
309 .collect();
310 let mut layer = BodyLayer::new(8);
311 for (i, feature) in features.into_iter().enumerate() {
312 layer.features.push(feature);
313 layer.parts.push(Part {
314 coord_start: i as u32,
315 point_count: 1,
316 winding: WINDING_OUTER,
317 });
318 layer.coords.push((i as i16, 0));
319 }
320 let mut map: BTreeMap<(u64, u8), ChunkEntry> = BTreeMap::new();
321 map.insert((7, 8), ChunkEntry { layer, names: names.clone(), ids: Vec::new() , turn_lanes: Vec::new(), buildings: Vec::new(), carriageways: Vec::new() });
322 let at = spill.write_chunk(map).expect("write");
323 // Window of one header: every name tops up (and compacts) mid-entry.
324 let read = drain(&spill, &at, ENTRY_HEADER_BYTES);
325 assert_eq!(read.len(), 1);
326 assert_eq!(read[0].1.names, names);
327 spill.check_books().expect("the books balance after mid-entry compaction");
328 }
329
330 /// The claim the whole merge rests on: the file's order is `map.keys()`, so a reader hands
331 /// `Merged` the identical key sequence a `BTreeMap` did.
332 #[test]
333 fn entry_order_is_the_maps_key_order() {
334 let spill = ChunkSpill::create(tmp("order")).expect("create");
335 // Inserted in a deliberately scrambled order; a `BTreeMap` sorts them and so must the file.
336 let mut map: BTreeMap<(u64, u8), ChunkEntry> = BTreeMap::new();
337 for (tile, layer) in [(30u64, 2u8), (10, 5), (10, 1), (20, 9), (10, 3), (30, 0)] {
338 map.insert((tile, layer), ChunkEntry::new(layer));
339 }
340 let keys: Vec<(u64, u8)> = map.keys().copied().collect();
341 let at = spill.write_chunk(map).expect("write");
342 let read: Vec<(u64, u8)> = drain(&spill, &at, 1 << 16).into_iter().map(|(k, _)| k).collect();
343 assert_eq!(read, keys);
344 assert_eq!(read, vec![(10, 1), (10, 3), (10, 5), (20, 9), (30, 0), (30, 2)]);
345 }
346
347 /// Chunks written concurrently must not overlap, and every one must read back as itself.
348 #[test]
349 fn concurrent_chunks_get_disjoint_ranges_and_the_books_balance() {
350 let spill = ChunkSpill::create(tmp("concurrent")).expect("create");
351 let refs: Vec<ChunkRef> = std::thread::scope(|scope| {
352 let handles: Vec<_> = (0..8u64)
353 .map(|i| {
354 scope.spawn({
355 let spill = &spill;
356 move || {
357 let mut map: BTreeMap<(u64, u8), ChunkEntry> = BTreeMap::new();
358 for tile in 0..64u64 {
359 let mut entry = ChunkEntry::new(1);
360 entry.layer.coords =
361 vec![(i as i16, tile as i16); 1 + tile as usize];
362 map.insert((tile, 1), entry);
363 }
364 (i, spill.write_chunk(map).expect("write"))
365 }
366 })
367 })
368 .collect();
369 let mut refs: Vec<(u64, ChunkRef)> =
370 handles.into_iter().map(|h| h.join().expect("join")).collect();
371 refs.sort_by_key(|(i, _)| *i);
372 refs.into_iter().map(|(_, at)| at).collect()
373 });
374
375 let mut ranges: Vec<(u64, u64)> = refs.iter().map(|r| (r.at, r.at + r.len)).collect();
376 ranges.sort();
377 for pair in ranges.windows(2) {
378 assert!(pair[0].1 <= pair[1].0, "two chunks share bytes: {pair:?}");
379 }
380 for (i, at) in refs.iter().enumerate() {
381 let entries = drain(&spill, at, 1 << 15);
382 assert_eq!(entries.len(), 64);
383 assert_eq!(entries[3].1.layer.coords[0], (i as i16, 3));
384 }
385 spill.check_books().expect("the books balance");
386 }
387
388 #[test]
389 fn a_truncated_chunk_errors_rather_than_decoding() {
390 let spill = ChunkSpill::create(tmp("truncated")).expect("create");
391 let map: BTreeMap<(u64, u8), ChunkEntry> = every_layer().into_iter().collect();
392 let at = spill.write_chunk(map).expect("write");
393
394 // Half a chunk: the reader is told the entry count but the bytes run out first.
395 let short = ChunkRef { at: at.at, len: at.len / 2, entries: at.entries };
396 let mut reader = spill.reader(&short, 1 << 16);
397 let mut failed = false;
398 loop {
399 match reader.next() {
400 Ok(Some(_)) => {}
401 Ok(None) => break,
402 Err(_) => {
403 failed = true;
404 break;
405 }
406 }
407 }
408 assert!(failed, "a truncated chunk decoded instead of erroring");
409
410 // And the other way round: the bytes are there but fewer entries were claimed, so the
411 // cursor would leave a tail behind.
412 let fewer = ChunkRef { at: at.at, len: at.len, entries: at.entries - 1 };
413 let mut reader = spill.reader(&fewer, 1 << 16);
414 for _ in 0..fewer.entries {
415 reader.next().expect("read").expect("an entry");
416 }
417 assert!(reader.next().is_err(), "a chunk with bytes past its last entry read as complete");
418 }
419
420 /// Byte 23 was the reserved tail and is now the carriageway flag, so the three section flags
421 /// are the whole of bytes 21..24. Each is 0 or 1: a spare value there means a newer writer put
422 /// something in it, and guessing would decode a section that moved.
423 #[test]
424 fn an_unknown_section_flag_errors() {
425 let head = [0u8; ENTRY_HEADER_BYTES];
426 entry_header(&head).expect("a zero header is legal");
427 for flag in 21..24 {
428 let mut set = head;
429 set[flag] = 1;
430 entry_header(&set).unwrap_or_else(|e| panic!("byte {flag} set is legal: {e:?}"));
431 let mut spare = head;
432 spare[flag] = 2;
433 assert!(entry_header(&spare).is_err(), "byte {flag} decoded a spare value");
434 }
435 }
436
437 /// The word that was the second reserved tail is now the id count, and an id count that is
438 /// neither zero nor one-per-feature is a desynced side table — the one corruption that would
439 /// otherwise attribute every POI's id to its neighbour.
440 #[test]
441 fn an_id_count_that_does_not_match_the_features_errors() {
442 let mut head = [0u8; ENTRY_HEADER_BYTES];
443 head[8..12].copy_from_slice(&2u32.to_le_bytes());
444 head[28..32].copy_from_slice(&2u32.to_le_bytes());
445 entry_header(&head).expect("one id per feature is legal");
446 head[28..32].copy_from_slice(&0u32.to_le_bytes());
447 entry_header(&head).expect("no ids at all is legal");
448 head[28..32].copy_from_slice(&1u32.to_le_bytes());
449 assert!(entry_header(&head).is_err(), "one id for two features decoded");
450 }
451
452 #[test]
453 fn an_entry_claiming_more_than_a_gigabyte_errors() {
454 let mut head = [0u8; ENTRY_HEADER_BYTES];
455 head[16..20].copy_from_slice(&u32::MAX.to_le_bytes());
456 assert!(entry_header(&head).is_err(), "a gigabyte-plus entry decoded");
457 }
458}