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

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

graph_build_part8.rs496 lines · 21.1 KiBRaw
1 /// Ties on `spatial` are the only case where the two could differ, so the fixture
2 /// is mostly ties, with `dense` ascending as the real builder pushes them.
3 #[test]
4 fn the_spatial_key_is_total_so_an_unstable_sort_matches_the_stable_one() {
5 let keys: Vec<(u64, u32)> = vec![
6 (5, 0),
7 (3, 1),
8 (5, 2),
9 (1, 3),
10 (3, 4),
11 (5, 5),
12 (1, 6),
13 (9, 7),
14 (3, 8),
15 ];
16 // What the code used to do: stable, keyed on `spatial` alone, so ties kept
17 // their insertion order -- which was ascending `dense`.
18 let mut stable = keys.clone();
19 stable.sort_by_key(|(spatial, _)| *spatial);
20 // What it does now.
21 let mut unstable = keys;
22 unstable.par_sort_unstable();
23 assert_eq!(unstable, stable);
24 // And the property that makes it true: no two entries share a full key.
25 let mut seen = unstable.clone();
26 seen.dedup();
27 assert_eq!(seen.len(), unstable.len(), "the key must be unique per node");
28 }
29
30 // ---- the within-way chain path ---------------------------------------
31
32 fn within_opts() -> Options {
33 Options {
34 within_way_chains: true,
35 ..Options::default()
36 }
37 }
38
39 /// A line of nodes 0.001 degrees apart along 122°W, so no geometry in these
40 /// shape tests is ever interpolated or split.
41 fn line_nodes(ids: &[i64]) -> Vec<(i64, i32, i32)> {
42 ids.iter()
43 .map(|id| (*id, 370_000_000 + (*id as i32) * 10_000, -1_220_000_000))
44 .collect()
45 }
46
47 /// Build `nodes`/`ways` both ways round and return `(legacy, within_way)`.
48 fn both_paths(tag: &str, nodes: &[(i64, i32, i32)], ways: &[(i64, &[i64])]) -> (Stats, Stats) {
49 let (pbf, dir) = testpbf::write_shape_sample(tag, nodes, ways);
50 let legacy = build(&pbf, &dir.join("legacy")).unwrap();
51 let within = build_with(
52 &pbf,
53 &dir.join("within"),
54 within_opts(),
55 )
56 .unwrap();
57 (legacy, within)
58 }
59
60 fn within_way(tag: &str, nodes: &[(i64, i32, i32)], ways: &[(i64, &[i64])]) -> (Stats, Outputs) {
61 let (pbf, dir) = testpbf::write_shape_sample(tag, nodes, ways);
62 let stats = build_with(
63 &pbf,
64 &dir,
65 within_opts(),
66 )
67 .unwrap();
68 (stats, read_outputs(&dir))
69 }
70
71 #[test]
72 fn a_within_way_chain_collapses_a_plain_run() {
73 let (stats, o) = within_way(
74 "chain_run",
75 &line_nodes(&[1, 2, 3, 4, 5]),
76 &[(100, &[1, 2, 3, 4, 5])],
77 );
78 // Only the two ends survive, and the one chain becomes a bidirectional
79 // pair carrying every interior vertex as geometry.
80 assert_eq!(stats.raw_node_count, 5);
81 assert_eq!(stats.node_count, 2);
82 assert_eq!(stats.edge_count, 2);
83 assert_eq!(stats.raw_edge_count, 8, "four segments, both directions");
84 let (pts, _) = edge_coords(&o, 0).unwrap();
85 assert_eq!(pts.len(), 5);
86 }
87
88 #[test]
89 fn an_interior_node_that_another_way_ends_at_is_not_collapsed() {
90 // Way 100's node 2 looks interior *within way 100*, but way 101 also ends
91 // there, so globally it has three incidences and is a real junction. This
92 // is the whole reason the degree count is global rather than per way: a
93 // per-way count would read 2 here and collapse a T-junction away.
94 let (stats, o) = within_way(
95 "chain_tee",
96 &line_nodes(&[1, 2, 3, 4]),
97 &[(100, &[1, 2, 3]), (101, &[2, 4])],
98 );
99 assert_eq!(stats.node_count, 4, "nothing may collapse at a T-junction");
100 // 1-2, 2-3 and 2-4, each both ways.
101 assert_eq!(stats.edge_count, 6);
102 for k in 0..stats.edge_count {
103 assert!(edge_coords(&o, k).is_none(), "no chain here has an interior vertex");
104 }
105 }
106
107 #[test]
108 fn a_ring_way_closes_on_its_own_first_node() {
109 // Every node on the ring has two incidences and none is special, so
110 // `compact` has to hunt for an anchor to break it at. Walking positions
111 // makes that free: the way's own first node is the boundary, and the walk
112 // cannot loop because it is advancing through a finite ref list.
113 let (stats, o) = within_way(
114 "chain_ring",
115 &line_nodes(&[1, 2, 3]),
116 &[(100, &[1, 2, 3, 1])],
117 );
118 assert_eq!(stats.node_count, 1, "the ring keeps exactly one node");
119 assert_eq!(stats.edge_count, 2, "a self-loop, both directions");
120 for k in 0..stats.edge_count {
121 let (target, _, _, _, _) = edge_at(&o, k as usize);
122 assert_eq!(target, 0, "both edges close on the anchor");
123 let (pts, _) = edge_coords(&o, k).unwrap();
124 assert_eq!(pts.len(), 4, "the ring's shape is preserved as geometry");
125 assert_eq!(pts[0], pts[3]);
126 }
127 }
128
129 #[test]
130 fn a_repeated_ref_is_skipped_without_breaking_the_run() {
131 // `[1, 2, 2, 3]` is a mapping artefact, not a zero-length road at node 2.
132 // Counting it would give node 2 four incidences and promote a genuine
133 // pass-through into a junction, so both the degree pass and the walk must
134 // reject it — and the walk must then still join 1-2 to 2-3.
135 let nodes = line_nodes(&[1, 2, 3]);
136 let ways: &[(i64, &[i64])] = &[(100, &[1, 2, 2, 3])];
137 let (stats, o) = within_way("chain_dup", &nodes, ways);
138 assert_eq!(stats.node_count, 2);
139 assert_eq!(stats.edge_count, 2);
140 let (pts, _) = edge_coords(&o, 0).unwrap();
141 assert_eq!(pts.len(), 3, "node 2 survives as a vertex, not as a node");
142
143 // The reference path asks the same question about a pair, so it must reach
144 // the same answer. It used to emit a zero-length self-loop here instead.
145 let (pbf, dir) = testpbf::write_shape_sample("chain_dup_ref", &nodes, ways);
146 let a = dir.join("legacy");
147 let b = dir.join("within");
148 build(&pbf, &a).unwrap();
149 build_with(&pbf, &b, within_opts()).unwrap();
150 for f in ["nodes.bin", "edges.bin", "intermediate.bin"] {
151 assert_eq!(
152 std::fs::read(a.join(f)).unwrap(),
153 std::fs::read(b.join(f)).unwrap(),
154 "{f} differs on a repeated ref"
155 );
156 }
157 }
158
159 #[test]
160 fn a_self_touching_way_cuts_at_the_node_it_revisits() {
161 // `[1, 2, 3, 2, 4]` visits node 2 twice, giving it four incidences. The
162 // positional walk cuts there both times without needing to notice that it
163 // has been there before.
164 let (stats, _) = within_way(
165 "chain_touch",
166 &line_nodes(&[1, 2, 3, 4]),
167 &[(100, &[1, 2, 3, 2, 4])],
168 );
169 assert_eq!(stats.node_count, 3, "node 3 folds into the 2 -> 3 -> 2 loop");
170 // 1-2 and 2-4 both ways, plus the self-loop at 2 both ways.
171 assert_eq!(stats.edge_count, 6);
172 }
173
174 #[test]
175 fn a_gap_left_by_a_dangling_ref_ends_the_run_it_interrupts() {
176 // Node 999 is referenced but never defined, so 2-999 and 999-3 are not
177 // segments. The run 1-2 must be closed and a new one started at 3, not
178 // silently joined across the gap.
179 let (pbf, dir) = testpbf::write_shape_sample(
180 "chain_gap",
181 &line_nodes(&[1, 2, 3, 4]),
182 &[(100, &[1, 2, 999, 3, 4])],
183 );
184 let stats = build_with(
185 &pbf,
186 &dir,
187 within_opts(),
188 )
189 .unwrap();
190 assert_eq!(stats.raw_node_count, 4, "999 never becomes a node");
191 assert_eq!(stats.node_count, 4, "1-2 and 3-4 are two separate chains");
192 assert_eq!(stats.edge_count, 4);
193 }
194
195 #[test]
196 fn within_way_chains_keep_the_node_where_two_ways_meet() {
197 // The accepted regression, stated as a test rather than as an estimate.
198 // Two residential ways meet end-to-end at node 3 and agree on every
199 // attribute, so `compact` folds node 3 into one five-point chain. Chains
200 // confined to a single way cannot, and node 3 stays.
201 let (legacy, within) = both_paths(
202 "chain_crossway",
203 &line_nodes(&[1, 2, 3, 4, 5]),
204 &[(100, &[1, 2, 3]), (101, &[3, 4, 5])],
205 );
206 assert_eq!(legacy.node_count, 2);
207 assert_eq!(legacy.edge_count, 2);
208 assert_eq!(within.node_count, 3, "node 3 is the cost of within-way chains");
209 assert_eq!(within.edge_count, 4);
210 // Both keep every original vertex, so nothing about the road's drawn shape
211 // changes: the extra node is a routing cost, not a geometry loss.
212 assert_eq!(legacy.raw_node_count, within.raw_node_count);
213 assert_eq!(legacy.raw_edge_count, within.raw_edge_count);
214 }
215
216 #[test]
217 fn the_within_way_path_agrees_with_the_reference_path_on_a_single_way() {
218 // With one way there is no cross-way merge to lose, so the two paths must
219 // produce byte-identical output. That is what makes the comparison above a
220 // measurement of the regression rather than of an unrelated difference.
221 let nodes = line_nodes(&[1, 2, 3, 4, 5, 6]);
222 let ways: &[(i64, &[i64])] = &[(100, &[1, 2, 3, 4, 5, 6])];
223 let (pbf, dir) = testpbf::write_shape_sample("chain_same", &nodes, ways);
224 let a = dir.join("legacy");
225 let b = dir.join("within");
226 build(&pbf, &a).unwrap();
227 build_with(
228 &pbf,
229 &b,
230 within_opts(),
231 )
232 .unwrap();
233 for f in [
234 "metadata.bin",
235 "nodes.bin",
236 "edges.bin",
237 "lanes.bin",
238 "road_names.bin",
239 "intermediate.bin",
240 ] {
241 assert_eq!(
242 std::fs::read(a.join(f)).unwrap(),
243 std::fs::read(b.join(f)).unwrap(),
244 "{f} differs between the two collapse paths"
245 );
246 }
247 }
248
249 #[test]
250 fn the_shared_fixture_is_byte_identical_on_both_paths() {
251 // Nothing in this fixture can be merged across a way boundary: node 4 is
252 // an endpoint of both Main St and the service road, and node 2 has three
253 // incidences. So the two paths must agree byte for byte here — which makes
254 // this a check on one-way orientation, lane masks, reverse-geometry flags
255 // and stop reconnection all at once, since a within-way walk reaches all of
256 // them by different code than `compact` does.
257 let (pbf_path, dir) = testpbf::write_sample("chain_fixture");
258 let a = dir.join("legacy");
259 let b = dir.join("within");
260 let legacy = build(&pbf_path, &a).unwrap();
261 let within = build_with(
262 &pbf_path,
263 &b,
264 within_opts(),
265 )
266 .unwrap();
267 for f in [
268 "metadata.bin",
269 "nodes.bin",
270 "edges.bin",
271 "lanes.bin",
272 "road_names.bin",
273 "intermediate.bin",
274 ] {
275 assert_eq!(
276 std::fs::read(a.join(f)).unwrap(),
277 std::fs::read(b.join(f)).unwrap(),
278 "{f} differs between the two collapse paths"
279 );
280 }
281 assert_eq!(legacy.node_count, within.node_count);
282 assert_eq!(legacy.raw_edge_count, within.raw_edge_count);
283 assert_eq!(legacy.geometry_edges, within.geometry_edges);
284 assert_eq!(legacy.reversed_edges, within.reversed_edges);
285 assert_eq!(within.reconnected_stops, 1);
286 let o = read_outputs(&b);
287 assert_eq!(local_of(&o, 3), None, "node 3 is interior to Main St");
288 assert_eq!(o.names, b"Main St\0Test Stop\0".to_vec());
289 }
290
291 #[test]
292 fn two_within_way_runs_are_byte_identical() {
293 let (pbf_path, dir_a) = testpbf::write_sample("chain_det_a");
294 let (_, dir_b) = testpbf::write_sample("chain_det_b");
295 let opts = within_opts();
296 build_with(&pbf_path, &dir_a, opts.clone()).unwrap();
297 build_with(&pbf_path, &dir_b, opts).unwrap();
298 for f in [
299 "metadata.bin",
300 "nodes.bin",
301 "edges.bin",
302 "lanes.bin",
303 "road_names.bin",
304 "intermediate.bin",
305 ] {
306 assert_eq!(
307 std::fs::read(dir_a.join(f)).unwrap(),
308 std::fs::read(dir_b.join(f)).unwrap(),
309 "{f} differs between runs"
310 );
311 }
312 }
313
314 #[test]
315 fn a_file_with_no_routable_ways_produces_an_empty_graph() {
316 // Nothing marks the node bitset, so the dense address space is empty and
317 // there is no largest marked id to size a rank index against. Every count
318 // has to come out zero rather than underflowing on the way there.
319 let (pbf, dir) = testpbf::write_shape_sample("empty_graph", &line_nodes(&[1, 2, 3]), &[]);
320 for opts in [Options::default(), within_opts()] {
321 let out = dir.join(format!("w{}", opts.within_way_chains));
322 let stats = build_with(&pbf, &out, opts).unwrap();
323 assert_eq!(stats.raw_node_count, 0);
324 assert_eq!(stats.node_count, 0);
325 assert_eq!(stats.edge_count, 0);
326 assert_eq!(stats.lcc_size, 0);
327 let o = read_outputs(&out);
328 // The smallest tables `graph.rs` can read zero edges through: one rank
329 // entry, no presence bytes at all, one coarse entry, one within-block
330 // entry and the `u64 G` trailer; plus `nodes.bin`'s trailing sentinel and
331 // a lane index holding only its own header and sentinel.
332 assert_eq!(o.nodes.len(), 12);
333 // `edges.bin` is not empty even with no edges: the escape block index and
334 // the name rank index each carry their final entry, which are the totals
335 // the reader cross-checks `escape_count` and `named_edges` against. Four
336 // bytes of "no escapes", padding, then eight of "no names".
337 assert_eq!(o.edges.len() as u64, EdgeFile::total_bytes(0, 0, 0));
338 assert_eq!(o.edges.len(), 4 + 4 + 8);
339 assert!(o.edges.iter().all(|b| *b == 0), "every count is zero");
340 assert_eq!(stats.escape_count, 0);
341 assert_eq!(stats.named_edges, 0);
342 assert_eq!(o.inter.len(), 8 + 8 + 2 + 8, "rank, coarse, within, G");
343 assert_eq!(o.inter.len() as u64, GeomFile::trailer_bytes(0, 0));
344 assert_eq!(o.lanes.len(), 4 + 8);
345 assert_eq!(lane_index(&o).0, vec![(u32::MAX, 0)]);
346 assert!(o.names.is_empty());
347 }
348 }
349
350 #[test]
351 fn a_region_build_drops_the_nodes_of_filtered_ways() {
352 // The 2.47B-node bug: the region filter removed ways but degree-0
353 // leftovers survived via `degree != 2`, so every world road-node landed
354 // in `nodes.bin` with no edge addressing it. Two disjoint line ways, a
355 // bbox covering only the first: the second way's nodes must not survive.
356 let nodes = vec![
357 (1, 370_000_000, -1_220_000_000),
358 (2, 370_010_000, -1_220_000_000),
359 (3, 370_020_000, -1_220_000_000),
360 (11, 400_000_000, -1_000_000_000),
361 (12, 400_010_000, -1_000_000_000),
362 (13, 400_020_000, -1_000_000_000),
363 ];
364 let ways: &[(i64, &[i64])] = &[(100, &[1, 2, 3]), (101, &[11, 12, 13])];
365 let (pbf, dir) = testpbf::write_shape_sample("region_drop", &nodes, ways);
366 let bbox = crate::bbox::BBox {
367 min_lon: -123.0,
368 min_lat: 36.0,
369 max_lon: -121.0,
370 max_lat: 38.0,
371 };
372 for opts in [
373 Options { bbox: Some(bbox), ..Options::default() },
374 Options { bbox: Some(bbox), within_way_chains: true, ..Options::default() },
375 ] {
376 let out = dir.join(format!("w{}", opts.within_way_chains));
377 let stats = build_with(&pbf, &out, opts).unwrap();
378 assert_eq!(stats.node_count, 2, "only the kept way's ends survive");
379 assert_eq!(stats.edge_count, 2);
380 let o = read_outputs(&out);
381 assert_eq!(node_count(&o), 2);
382 for i in 0..2 {
383 let (lat, lon, _) = node_at(&o, i);
384 assert!((370_000_000..=370_020_000).contains(&lat), "stray node at {lat},{lon}");
385 }
386 }
387 }
388
389 // ---------------------------------------------------------------------
390 // edges.bin narrowing: the boundaries no real extract contains
391 // ---------------------------------------------------------------------
392
393 fn tmp_edge(source: u32, target: u32, dist_mm: u32) -> TmpEdge {
394 TmpEdge {
395 source,
396 target,
397 dist_mm,
398 name_offset: NO_NAME,
399 type_: 1,
400 speed_limit: 50,
401 lane_off: NO_LANES,
402 lane_count: 0,
403 chain: NO_CHAIN,
404 chain_rev: false,
405 pts_start: 0,
406 pts_len: 0,
407 }
408 }
409
410 /// Push `spec` — `(source, target, dist_mm)` — through the real [`EdgeFile`] and
411 /// read every record back through the mirror of `graph.rs`'s decode.
412 ///
413 /// The delta encoding's boundaries are unreachable from a PBF fixture: putting
414 /// two nodes exactly 32,768 apart in Morton order would mean choosing
415 /// coordinates for 32,767 nodes in between. So the encoder and the decoder are
416 /// exercised as a pair directly, which is also where the off-by-one would be.
417 type EdgeRoundtrip = (Vec<(u32, u32, u32, u8, u8)>, Vec<u8>, u64);
418
419 fn roundtrip_edges(
420 tag: &str,
421 spec: &[(u32, u32, u32)],
422 ) -> EdgeRoundtrip {
423 let dir = std::env::temp_dir().join(format!("osm_ingest_edges_{tag}"));
424 let _ = std::fs::remove_dir_all(&dir);
425 std::fs::create_dir_all(&dir).unwrap();
426 let count = spec.len() as u64;
427 let mut f = EdgeFile::create(&dir, "edges.bin", count).unwrap();
428 for (source, target, dist) in spec {
429 f.push(&tmp_edge(*source, *target, *dist), 1).unwrap();
430 }
431 let escapes = f.escapes.len() as u64;
432 let total = f.finish(count).unwrap();
433 let bytes = std::fs::read(dir.join("edges.bin")).unwrap();
434 assert_eq!(bytes.len() as u64, total, "finish() lied about the length");
435 // v7: the record array is a ZBLK section unpacking to exactly the
436 // pushed records; the escapes/names tail follows it. (The v6
437 // `total_bytes` formula no longer applies — the records' length is
438 // data-dependent.)
439 let blocked = tilecodec::blocked::Blocked::parse(&bytes)
440 .expect("the record array is a blocked section");
441 assert_eq!(blocked.unpacked_len(), count * EDGE_REC_BYTES);
442 assert_eq!(blocked.record_len(), EDGE_REC_BYTES as usize);
443 let e = Edges::new(&bytes, count, escapes);
444 // The block index's last entry is the row total, which is what the reader
445 // cross-checks `escape_count` against.
446 let blocks = count.div_ceil(ESCAPE_BLOCK) + 1;
447 assert_eq!(
448 u64::from(e.escape_first(blocks - 1)),
449 escapes,
450 "the block index total disagrees with the row count"
451 );
452 let decoded = spec
453 .iter()
454 .enumerate()
455 .map(|(i, (source, _, _))| e.get(*source, i as u64))
456 .collect();
457 (decoded, bytes, escapes)
458 }
459
460 #[test]
461 fn every_target_delta_boundary_round_trips() {
462 // Far enough from zero that every delta below is a representable u32 target.
463 let source = 1_000_000u32;
464 let deltas: [i64; 11] = [0, 1, -1, 32766, -32766, 32767, -32767, 32768, -32768, -32769, 40000];
465 let spec: Vec<(u32, u32, u32)> = deltas
466 .iter()
467 .map(|d| (source, (i64::from(source) + d) as u32, 1234))
468 .collect();
469 let (decoded, _, escapes) = roundtrip_edges("deltas", &spec);
470 for (i, d) in deltas.iter().enumerate() {
471 assert_eq!(decoded[i].0, spec[i].1, "delta {d} did not round-trip");
472 assert_eq!(decoded[i].1, 1234, "delta {d} disturbed dist_mm");
473 }
474 // ±32767 fit. ±32768, −32769 and +40000 do not — and −32768 is `i16::MIN`,
475 // which is the sentinel, so it escapes even though its magnitude would fit.
476 // That reservation is what keeps the representable range symmetric.
477 assert_eq!(escapes, 4, "expected 32768, -32768, -32769 and 40000 to escape");
478 }
479
480 #[test]
481 fn every_dist_mm_boundary_round_trips() {
482 let source = 5u32;
483 let dists = [0u32, 1, 0xFF_FFFE, 0xFF_FFFF, 0x100_0000, u32::MAX];
484 let spec: Vec<(u32, u32, u32)> =
485 dists.iter().map(|d| (source, source + 1, *d)).collect();
486 let (decoded, _, escapes) = roundtrip_edges("dists", &spec);
487 for (i, d) in dists.iter().enumerate() {
488 assert_eq!(decoded[i].1, *d, "dist {d} did not round-trip");
489 assert_eq!(decoded[i].0, source + 1, "dist {d} disturbed the target");
490 }
491 // 0xFFFFFE is the largest a u24 can hold and be a value; 0xFFFFFF is the
492 // sentinel, so it escapes despite fitting. The escape keeps every distance
493 // *exact* — the alternative considered was centimetres, which needs no table
494 // but quantises all 1.07 G edges.
495 assert_eq!(escapes, 3);
496 }