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

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

graph_build_part9.rs447 lines · 20.2 KiBRaw
1 #[test]
2 fn an_edge_that_fails_both_tests_is_one_row_not_two() {
3 let spec = vec![(0u32, 500_000u32, 0x200_0000u32)];
4 let (decoded, _, escapes) = roundtrip_edges("both", &spec);
5 assert_eq!(escapes, 1, "one row serves both fields");
6 assert_eq!(decoded[0].0, 500_000);
7 assert_eq!(decoded[0].1, 0x200_0000);
8 }
9
10 #[test]
11 fn an_escape_at_either_end_of_the_pack_is_found() {
12 // The block index is a prefix-count array, so the first and last edge are
13 // where an off-by-one in it shows up.
14 let far = 200_000u32;
15 let spec = vec![
16 (far, 0, 10),
17 (far, far + 1, 20),
18 (far, far + 2, 30),
19 (far, 0, 40),
20 ];
21 let (decoded, _, escapes) = roundtrip_edges("ends", &spec);
22 assert_eq!(escapes, 2);
23 let got: Vec<(u32, u32)> = decoded.iter().map(|d| (d.0, d.1)).collect();
24 assert_eq!(got, vec![(0, 10), (far + 1, 20), (far + 2, 30), (0, 40)]);
25 }
26
27 #[test]
28 fn a_pack_with_no_escapes_is_records_padding_and_an_index_sentinel() {
29 let spec: Vec<(u32, u32, u32)> = (0..100u32).map(|i| (1000, 1000 + i, i)).collect();
30 let (decoded, bytes, escapes) = roundtrip_edges("no_escapes", &spec);
31 assert_eq!(escapes, 0);
32 // The record array is blocked (v7): it parses and unpacks to exactly
33 // the 100 pushed records. Padding assertions belong to the v6 fixed
34 // stride; the blocked container carries its own alignment instead.
35 let blocked = tilecodec::blocked::Blocked::parse(&bytes).expect("blocked records");
36 assert_eq!(blocked.unpacked_len(), 100 * EDGE_REC_BYTES);
37 for (i, d) in decoded.iter().enumerate() {
38 assert_eq!((d.0, d.1), (1000 + i as u32, i as u32));
39 assert_eq!(d.2, NO_NAME, "no fixture edge is named");
40 }
41 }
42
43 #[test]
44 fn escape_rows_spanning_block_boundaries_are_all_found() {
45 // Every side of every block boundary a 1024-edge block has, plus both ends.
46 let far = 500_000u32;
47 let n = 3000u32;
48 let escaping = [0u32, 1023, 1024, 1025, 2047, 2048, 2049, n - 1];
49 let spec: Vec<(u32, u32, u32)> = (0..n)
50 .map(|i| {
51 // An escaping edge points a long way back; the rest are a short
52 // forward delta.
53 let target = if escaping.contains(&i) { i } else { far + i };
54 (far, target, 1000 + i)
55 })
56 .collect();
57 let (decoded, _, escapes) = roundtrip_edges("blocks", &spec);
58 assert_eq!(escapes, escaping.len() as u64);
59 for i in 0..n as usize {
60 assert_eq!(
61 (decoded[i].0, decoded[i].1),
62 (spec[i].1, spec[i].2),
63 "edge {i} decoded wrongly"
64 );
65 }
66 }
67
68 /// Named at edge 0 and E−1, unnamed either side of a rank-block boundary, and a
69 /// name offset at both ends of the `u32` range.
70 ///
71 /// The rank index covers 512 edges an entry, so the boundary at 511/512 is where
72 /// a rank computed from the wrong block would show up — and it is a boundary a
73 /// small fixture never reaches.
74 #[test]
75 fn the_sparse_name_table_survives_every_boundary() {
76 let dir = std::env::temp_dir().join("osm_ingest_edges_names");
77 let _ = std::fs::remove_dir_all(&dir);
78 std::fs::create_dir_all(&dir).unwrap();
79 let n = 1200u64;
80 // Which edges get a name, and what offset. Deliberately includes both ends,
81 // both sides of the 512-edge rank boundary and both sides of 1024.
82 let named: Vec<u64> = vec![0, 1, 510, 511, 512, 513, 1022, 1023, 1024, 1025, n - 1];
83 let mut f = EdgeFile::create(&dir, "edges.bin", n).unwrap();
84 for i in 0..n {
85 let mut e = tmp_edge(0, i as u32, 7);
86 e.speed_limit = 90;
87 if let Some(k) = named.iter().position(|x| *x == i) {
88 // A distinct offset per named edge, so a rank off by one reads a
89 // visibly wrong value rather than a plausible one.
90 e.name_offset = (k as u32) * 17;
91 }
92 f.push(&e, REVERSE_GEOMETRY_FLAG | 3).unwrap();
93 }
94 let escapes = f.escapes.len() as u64;
95 let named_count = f.name_offsets.len() as u64;
96 assert_eq!(named_count, named.len() as u64);
97 let total = f.finish(n).unwrap();
98 let bytes = std::fs::read(dir.join("edges.bin")).unwrap();
99 assert_eq!(bytes.len() as u64, total);
100 let e = Edges::new(&bytes, n, escapes);
101 for i in 0..n {
102 let (target, dist, name, type_, speed) = e.get(0, i);
103 assert_eq!(target, i as u32);
104 assert_eq!(dist, 7);
105 assert_eq!(type_, REVERSE_GEOMETRY_FLAG | 3, "edge {i}");
106 assert_eq!(speed, 90, "edge {i}");
107 let want = match named.iter().position(|x| *x == i) {
108 Some(k) => (k as u32) * 17,
109 None => NO_NAME,
110 };
111 assert_eq!(name, want, "edge {i}'s name offset");
112 }
113 }
114
115 #[test]
116 fn a_pack_where_no_edge_is_named_and_one_where_every_edge_is() {
117 for all_named in [false, true] {
118 let dir = std::env::temp_dir()
119 .join(format!("osm_ingest_edges_named_{all_named}"));
120 let _ = std::fs::remove_dir_all(&dir);
121 std::fs::create_dir_all(&dir).unwrap();
122 let n = 600u64;
123 let mut f = EdgeFile::create(&dir, "edges.bin", n).unwrap();
124 for i in 0..n {
125 let mut e = tmp_edge(0, i as u32, 1);
126 if all_named {
127 e.name_offset = i as u32 * 3;
128 }
129 f.push(&e, 1).unwrap();
130 }
131 let named_count = f.name_offsets.len() as u64;
132 assert_eq!(named_count, if all_named { n } else { 0 });
133 let total = f.finish(n).unwrap();
134 let bytes = std::fs::read(dir.join("edges.bin")).unwrap();
135 assert_eq!(bytes.len() as u64, total);
136 // v7 record array: blocked, unpacking to exactly the pushed records.
137 let blocked = tilecodec::blocked::Blocked::parse(&bytes).expect("blocked records");
138 assert_eq!(blocked.unpacked_len(), n * EDGE_REC_BYTES);
139 let e = Edges::new(&bytes, n, 0);
140 for i in 0..n {
141 let want = if all_named { i as u32 * 3 } else { NO_NAME };
142 assert_eq!(e.get(0, i).2, want, "edge {i} with all_named={all_named}");
143 }
144 }
145 }
146
147 #[test]
148 fn the_round_count_does_not_change_a_single_output_byte() {
149 // The strongest check on the rounds writer. Round boundaries move the split
150 // between which edges each pass collects, which offsets each pass appends
151 // and where `nodes.bin`'s running edge counter resumes, and none of that may
152 // reach the file. 17 is prime, so with these node counts most of its rounds
153 // are empty or hold a single node — exactly the boundaries an even split
154 // would never exercise.
155 let nodes = line_nodes(&[1, 2, 3, 4, 5, 6, 7, 8, 9]);
156 let ways: &[(i64, &[i64])] = &[
157 (100, &[1, 2, 3, 4]),
158 (101, &[4, 5, 6]),
159 (102, &[6, 7, 8, 9]),
160 (103, &[3, 7]),
161 ];
162 let (pbf, dir) = testpbf::write_shape_sample("rounds_shape", &nodes, ways);
163 let (stop_pbf, stop_dir) = testpbf::write_sample("rounds_fixture");
164
165 for opts in [Options::default(), within_opts()] {
166 for (input, base) in [(&pbf, &dir), (&stop_pbf, &stop_dir)] {
167 let mut want: Option<Vec<Vec<u8>>> = None;
168 for rounds in [1u32, 4, 17] {
169 let out = base.join(format!("r{rounds}_{}", opts.within_way_chains));
170 build_with(
171 input,
172 &out,
173 Options {
174 rounds,
175 ..opts.clone()
176 },
177 )
178 .unwrap();
179 let got: Vec<Vec<u8>> = [
180 "metadata.bin",
181 "nodes.bin",
182 "edges.bin",
183 "lanes.bin",
184 "road_names.bin",
185 "intermediate.bin",
186 ]
187 .iter()
188 .map(|f| std::fs::read(out.join(f)).unwrap())
189 .collect();
190 match &want {
191 None => want = Some(got),
192 Some(w) => assert_eq!(*w, got, "--rounds {rounds} changed the output"),
193 }
194 // The scratch blob must not survive into the pack.
195 assert!(!out.join("lanes.bin.blob").exists());
196 assert!(!out.join("chain_spill").exists(), "the spill was left behind");
197 }
198 }
199 }
200 }
201
202 // ---- the v3 layouts at their boundaries -------------------------------
203
204 #[test]
205 fn a_block_of_maximal_polylines_cannot_escape_a_u16_within_offset() {
206 // The arithmetic the two-level offset table rests on. A per-edge blob holds
207 // only the interior points — 4 bytes each, at most `geom::MAX_POINTS - 2` of
208 // them — so a block of `INTERMEDIATE_BLOCK` of them is the worst case the
209 // u16 half has to hold. Keying the table on presence rank rather than on
210 // edge index makes that bound tight rather than pessimistic: every entry in
211 // a block is a real blob, where under v2 most were zero-length.
212 let worst_edge = 4 * (u64::from(geom::MAX_POINTS) - 2);
213 assert_eq!(worst_edge, 1016);
214 assert!(
215 INTERMEDIATE_BLOCK * worst_edge <= u64::from(u16::MAX),
216 "a block of {INTERMEDIATE_BLOCK} maximal blobs is {} bytes",
217 INTERMEDIATE_BLOCK * worst_edge
218 );
219 }
220
221 #[test]
222 fn the_presence_rank_agrees_with_a_brute_force_popcount() {
223 // On-disk rank/select is a new primitive, so it is exercised on its own
224 // rather than through a graph: ids straddling byte and 512-bit block
225 // boundaries — the two places the three-term rank can be off by one — and an
226 // edge count past a single rank block, which no fixture small enough to build
227 // in a test would reach.
228 const EDGES: u64 = 1500;
229 let stored: Vec<u64> = vec![0, 1, 7, 8, 9, 63, 64, 65, 511, 512, 513, 1023, 1024, 1499];
230 let dir = std::env::temp_dir().join("osm_ingest_present_rank");
231 std::fs::create_dir_all(&dir).unwrap();
232 let mut f = GeomFile::create(&dir, "intermediate.bin", EDGES).unwrap();
233 for k in 0..EDGES {
234 match stored.iter().position(|s| *s == k) {
235 // A distinct length and content per stored edge, so an offset landing
236 // on the wrong entry shows up rather than coinciding.
237 Some(g) => f.store(&vec![g as u8; 4 * (g + 1)]).unwrap(),
238 None => f.skip(),
239 }
240 }
241 let size = f.finish(EDGES).unwrap();
242 let bytes = std::fs::read(dir.join("intermediate.bin")).unwrap();
243 assert_eq!(bytes.len() as u64, size);
244
245 let t = Inter::new(&bytes, EDGES);
246 assert_eq!(t.geometry_edges, stored.len() as u64);
247 assert_eq!(t.blob_bytes, (1..=stored.len()).map(|n| 4 * n).sum::<usize>());
248 for k in 0..EDGES {
249 assert_eq!(t.present(k), stored.contains(&k), "presence bit {k}");
250 // For every id, set or not, the rank is the brute-force count of set
251 // bits strictly below it.
252 let want = stored.iter().filter(|s| **s < k).count() as u64;
253 assert_eq!(t.rank(k), want, "rank at {k}");
254 if !stored.contains(&k) {
255 assert_eq!(t.blob(k), None, "edge {k} stores nothing");
256 }
257 }
258 // Each stored edge's blob is the one it wrote, found through that rank and
259 // both offset levels.
260 for (g, k) in stored.iter().enumerate() {
261 assert_eq!(t.blob(*k), Some(&vec![g as u8; 4 * (g + 1)][..]), "blob at {k}");
262 }
263 }
264
265 #[test]
266 fn a_chain_at_the_256_point_limit_produces_the_largest_legal_blob() {
267 // Exactly `geom::MAX_POINTS` vertices in one chain: the largest per-edge
268 // blob the format allows, and so the worst case for the within-block u16.
269 // Nodes 0.001 degrees apart, so nothing is interpolated and nothing splits.
270 let ids: Vec<i64> = (1..=i64::from(geom::MAX_POINTS)).collect();
271 let (stats, o) = within_way("inter_max_points", &line_nodes(&ids), &[(100, &ids)]);
272 assert_eq!(stats.node_count, 2, "only the two ends of the run survive");
273 assert_eq!(stats.chain_splits, 0, "256 points is exactly the budget");
274 assert_eq!(stats.edge_count, 2);
275 assert_eq!(stats.geometry_edges, 1, "the twin defers to the stored polyline");
276
277 let t = inter(&o);
278 let stored: Vec<u64> = (0..edge_count(&o)).filter(|k| t.present(*k)).collect();
279 assert_eq!(stored.len(), 1);
280 // Both endpoints are dropped, so 256 points cost 254 deltas.
281 assert_eq!(
282 t.blob(stored[0]).unwrap().len() as u64,
283 4 * (u64::from(geom::MAX_POINTS) - 2)
284 );
285 assert_eq!(t.blob_bytes, 1016);
286 // Both directions still decode the full polyline, one of them backwards.
287 for k in 0..edge_count(&o) {
288 let (pts, _) = edge_coords(&o, k).unwrap();
289 assert_eq!(pts.len(), geom::MAX_POINTS as usize);
290 }
291 }
292
293 #[test]
294 fn the_two_level_offsets_cross_block_boundaries_exactly() {
295 // 80 disjoint three-node ways: 80 chains, 160 directed edges and 80 stored
296 // polylines, so the *geometry* indices the offset table is keyed on span
297 // three coarse blocks and the two boundary cases — `g % 32 == 0` and
298 // `g % 32 == 31` — both fall inside the graph rather than at its end, where
299 // an off-by-one would be hidden by the sentinel.
300 let mut nodes: Vec<(i64, i32, i32)> = Vec::new();
301 let mut refs: Vec<Vec<i64>> = Vec::new();
302 for w in 0..80i64 {
303 let base = w * 10 + 1;
304 for k in 0..3i64 {
305 nodes.push((
306 base + k,
307 370_000_000 + (w as i32) * 100_000 + (k as i32) * 10_000,
308 -1_220_000_000,
309 ));
310 }
311 refs.push(vec![base, base + 1, base + 2]);
312 }
313 let ways: Vec<(i64, &[i64])> = refs
314 .iter()
315 .enumerate()
316 .map(|(i, r)| (100 + i as i64, r.as_slice()))
317 .collect();
318 let (_, o) = within_way("inter_blocks", &nodes, &ways);
319
320 let e = edge_count(&o);
321 assert_eq!(e, 160);
322 let t = inter(&o);
323 assert_eq!(t.geometry_edges, 80);
324 assert!(
325 t.geometry_edges > 2 * INTERMEDIATE_BLOCK,
326 "the offset table must span three blocks"
327 );
328
329 // Each chain stores one 3-point polyline, which is a single interior delta,
330 // and defers the other direction. So the offsets are a known sequence rather
331 // than merely a self-consistent one, and exactly half the presence bits are
332 // set.
333 let offs: Vec<u64> = (0..=t.geometry_edges).map(|g| t.offset(g)).collect();
334 assert!(offs.windows(2).all(|w| w[1] - w[0] == 4), "{offs:?}");
335 assert_eq!(*offs.last().unwrap(), 80 * 4);
336 assert_eq!((0..e).filter(|k| t.present(*k)).count(), 80);
337
338 // The coarse entry for a block is its first geometry edge's absolute offset,
339 // so the within-block value there is zero, and every offset in between
340 // reassembles from the pair.
341 let coarse = |b: u64| {
342 let at = t.coarse_at + b as usize * 8;
343 u64::from_le_bytes(o.inter[at..at + 8].try_into().unwrap())
344 };
345 let within = |g: u64| {
346 let at = t.within_at + g as usize * 2;
347 u16::from_le_bytes(o.inter[at..at + 2].try_into().unwrap())
348 };
349 for g in 0..=t.geometry_edges {
350 assert_eq!(
351 coarse(g / INTERMEDIATE_BLOCK) + u64::from(within(g)),
352 offs[g as usize],
353 "geometry edge {g} does not reassemble"
354 );
355 if g.is_multiple_of(INTERMEDIATE_BLOCK) {
356 assert_eq!(within(g), 0, "a block's first entry starts at its coarse entry");
357 }
358 }
359 // The whole file is the blob plus a trailer sized from `E` and `G`.
360 assert_eq!(
361 o.inter.len() as u64,
362 *offs.last().unwrap() + GeomFile::trailer_bytes(e, t.geometry_edges)
363 );
364 }
365
366 #[test]
367 fn a_graph_where_every_edge_stores_geometry_and_one_where_none_does() {
368 // The two ends of the presence bitmap. A ring collapsed to one node is a
369 // self-loop both ways round, and a self-loop can never defer to a twin
370 // (`twin_is_unique` refuses, since it would match itself), so both directions
371 // store a polyline and every presence bit is set.
372 let (all_stats, all) = within_way(
373 "present_all",
374 &line_nodes(&[1, 2, 3]),
375 &[(100, &[1, 2, 3, 1])],
376 );
377 let t = inter(&all);
378 assert_eq!(all_stats.edge_count, 2);
379 assert_eq!(t.geometry_edges, 2);
380 assert!((0..all_stats.edge_count).all(|k| t.present(k)));
381 assert_eq!((t.rank(0), t.rank(1)), (0, 1));
382
383 // A T-junction of two-node chains has no interior vertex anywhere, so nothing
384 // is stored, the blob is empty and both offset levels hold only a sentinel.
385 let (none_stats, none) = within_way(
386 "present_none",
387 &line_nodes(&[1, 2, 3, 4]),
388 &[(100, &[1, 2]), (101, &[2, 3]), (102, &[2, 4])],
389 );
390 let t = inter(&none);
391 assert_eq!(none_stats.edge_count, 6);
392 assert_eq!(t.geometry_edges, 0);
393 assert_eq!(t.blob_bytes, 0);
394 assert!((0..none_stats.edge_count).all(|k| !t.present(k) && t.blob(k).is_none()));
395 assert_eq!(t.offset(0), 0, "the sentinel is the empty blob's length");
396 assert_eq!(
397 none.inter.len() as u64,
398 GeomFile::trailer_bytes(none_stats.edge_count, 0)
399 );
400 }
401
402 #[test]
403 #[should_panic(expected = "starts off its source node")]
404 fn a_chain_that_starts_off_its_source_node_is_refused() {
405 // Dropping the endpoints is only sound because a chain begins and ends on
406 // its own nodes' coordinates. Feed the writer's check a mismatched chain to
407 // prove it fires rather than encoding a polyline the reader would rebuild
408 // wrongly.
409 let coords = vec![(370_000_000, -1_220_000_000), (370_020_000, -1_220_000_000)];
410 let chain = vec![(0, 0), (370_010_000, -1_220_000_000), coords[1]];
411 assert_endpoints(&chain, &coords, 0, 1, 7);
412 }
413
414 #[test]
415 #[should_panic(expected = "ends off its target node")]
416 fn a_chain_that_ends_off_its_target_node_is_refused() {
417 let coords = vec![(370_000_000, -1_220_000_000), (370_020_000, -1_220_000_000)];
418 let chain = vec![coords[0], (370_010_000, -1_220_000_000), (0, 0)];
419 assert_endpoints(&chain, &coords, 0, 1, 7);
420 }
421
422 #[test]
423 fn a_graph_with_no_turn_lanes_has_an_empty_lane_index() {
424 // The common case at planet scale: 99.7% of edges carry no `turn:lanes`, and
425 // under the sparse layout they cost nothing at all rather than 8 bytes each.
426 let (stats, o) = within_way(
427 "lanes_none",
428 &line_nodes(&[1, 2, 3, 4]),
429 &[(100, &[1, 2, 3, 4])],
430 );
431 assert!(stats.edge_count > 0);
432 let (index, blob) = lane_index(&o);
433 assert_eq!(index, vec![(u32::MAX, 0)], "only the sentinel");
434 assert!(blob.is_empty());
435 assert_eq!(o.lanes.len(), 4 + 8);
436 for k in 0..stats.edge_count {
437 assert_eq!(lane_masks(&o, k), None);
438 }
439 }
440
441 #[test]
442 fn an_edge_count_past_the_u32_ceiling_is_refused() {
443 // `nodes.bin`'s `edge_ptr` is a u32, so a wrapped edge count would point a
444 // node at another node's edge range and the build would report success.
445 assert_eq!(cap_u32("directed edge", u64::from(u32::MAX)).unwrap(), u32::MAX);
446 let err = cap_u32("directed edge", u64::from(u32::MAX) + 1).unwrap_err();
447 assert!(err.0.contains("directed edge"), "{}", err.0); }