/// Pass 2: refs of every relation member way. Moved whole from `extract`. fn load_member_ways( input: &Path, blobs: &[pbf::BlobLoc], blob_kinds: &[u8], relations: &[Relation], ) -> Result { // --- pass 2: the refs of every relation member way ------------------------------------ // // **Every** member, not just the ones pass 1 did not classify. A relation reaches its members by // id, in the order it lists them, which is the one random access in this stage and the one thing // a sequential spill file cannot serve. So the members — and only the members — stay resident, // and that is what lets the other several million classified ways go to disk. California has // 63 156 relations, so this table is small next to the one it replaces; planet has 8.4 M, so // it is a sorted vector rather than a hash map (see [`MemberWays`]). let wanted: Vec = { let mut wanted: Vec = relations .iter() .flat_map(|r| r.members.iter().map(|(id, _)| *id)) .collect(); wanted.sort_unstable(); wanted.dedup(); wanted }; let mut members = MemberWays::empty(); if !wanted.is_empty() { let (chunks, _) = pbf::run_pass( input, blobs, Some(blob_kinds), KIND_WAYS, "Pass 2: member ways", Vec::<(i64, Vec)>::new, |state, block| { let mut kinds = 0u8; visit_block(block, KIND_WAYS, &mut kinds, &mut |el| { if let Element::Way(way) = el { if wanted.binary_search(&way.id).is_ok() { state.push((way.id, way.refs.to_vec())); } } Ok(()) })?; Ok(kinds) }, )?; // Chunks arrive in file order and ways are sorted by id, so concatenation is sorted as // long as no way id appears in two chunks (ids are unique in the PBF). Sortedness is // asserted, not assumed: `MemberWays::build` sorts anyway, which is also what absorbs // the (impossible in practice) duplicate across chunks. let all: Vec<(i64, Vec)> = chunks.into_iter().flatten().collect(); members = MemberWays::build(all); } Ok(members) } /// Relation member ways by id: the one random access in stage A. /// /// A `HashMap>` costs ~48 B overhead per entry plus the hasher's table slack -- /// at planet's 8.4 M member ways that is hundreds of MB beside the ref bytes themselves. This is /// a sorted `Vec` with binary search instead: lookups are `O(log n)` rather than `O(1)`, but a /// lookup is followed by cloning a ref vec and resolving every ref through the coordinate table, /// so the search is noise next to the use. Built sorted once; every reader shares the shape. pub struct MemberWays { entries: Vec<(i64, Vec)>, } impl MemberWays { fn empty() -> MemberWays { MemberWays { entries: Vec::new() } } /// Build from `(way id, refs)` pairs in any order. Sorts by id; a duplicated id keeps its /// first occurrence (ids are unique in the PBF, so this is defence, not logic). fn build(mut all: Vec<(i64, Vec)>) -> MemberWays { all.sort_by_key(|(id, _)| *id); all.dedup_by_key(|(id, _)| *id); MemberWays { entries: all } } /// The refs of member way `id`, or `None` if pass 2 never saw it (an extract cut it away). pub fn get(&self, id: i64) -> Option<&Vec> { self.entries .binary_search_by_key(&id, |(id, _)| *id) .ok() .map(|at| &self.entries[at].1) } /// Every member's refs, for the ref collectors (order irrelevant: both collectors only add). pub fn values(&self) -> impl Iterator> { self.entries.iter().map(|(_, refs)| refs) } /// How many member ways are held. #[cfg(test)] pub fn len(&self) -> usize { self.entries.len() } #[cfg(test)] pub fn is_empty(&self) -> bool { self.entries.is_empty() } #[cfg(test)] pub fn from_map(map: HashMap>) -> MemberWays { MemberWays::build(map.into_iter().collect()) } } #[cfg(test)] mod member_ways_tests { use super::*; /// The whole contract: lookups answer like the map, whatever order the pairs arrived in, and /// a duplicated id keeps its first occurrence. #[test] fn lookups_match_the_map_regardless_of_input_order() { let table = MemberWays::build(vec![ (9, vec![10_000, 9_999]), (1, vec![7, 8]), (9, vec![1, 2, 3]), (5, vec![]), ]); assert_eq!(table.len(), 3, "the duplicate id is absorbed"); assert_eq!(table.get(1), Some(&vec![7, 8])); assert_eq!(table.get(5), Some(&vec![]), "an empty ref list is still a member"); assert_eq!(table.get(9), Some(&vec![10_000, 9_999]), "first occurrence wins"); assert_eq!(table.get(2), None, "not a member at all"); assert_eq!(table.get(-1), None, "negative ids never resolve"); assert_eq!(table.get(i64::MAX), None, "past the end"); // `values` covers every entry exactly once, for the ref collectors. let mut seen: Vec = table.values().flatten().copied().collect(); seen.sort_unstable(); assert_eq!(seen, vec![7, 8, 9_999, 10_000]); assert!(MemberWays::empty().is_empty(), "empty is empty"); } } /// Pass 3: id index plus resolved coordinates, with `places`/`poi` label nodes classified and /// spilled in the same pass. Grew the sink, select and layers params when pass 4 was folded in. /// /// `region` filters `poi` label NODES to the bbox. `places` nodes are always /// kept. Ways and relations are filtered later at materialise time, where the /// resolved coordinates are in hand. #[allow(clippy::too_many_arguments)] fn build_resolved_table( input: &Path, blobs: &[pbf::BlobLoc], blob_kinds: &[u8], members: &MemberWays, needed: NeededBits, select: &Select, layers: Layers, region: Option<&osm_ingest::bbox::BBox>, sink: &mut Sink, stats: &mut Stats, timer: &mut crate::timing::PhaseTimer, ) -> Result { // The fused bitset already holds every classified way's refs (set in pass // 1's drain); member ways join here. No ways-spill re-scan: the refs were // decoded and in hand where they were set. let mut needed = needed; for refs in members.values() { for &id in refs { needed.set_growable(id)?; } } // Small extracts take the exact vector; planet-scale takes the bitset the // words move straight into. The threshold now counts distinct ids (the old // one counted duplicates), which only moves borderline extracts toward the // vector path — whose input arrives sorted-unique, so its sort is trivial. let table = if needed.len() <= REFS_IN_MEMORY { let ids: Vec = needed.ids().collect(); timer.switch("id-index"); NodeLocations::new(ids)? } else { timer.switch("id-index"); // The bitset's words move into the rank index directly (`from_bitset`), // not through `ids()`: walking them out as ids and re-setting them // would hold two ~1.5 GB words arrays at once. let (words, count) = needed.into_words(); NodeLocations::from_bitset(words, count)? }; timer.switch("coords-resolve"); stats.nodes_needed = table.len() as u64; // The node region is the bulk of a planet PBF, so it is inflated once: the coordinate resolve // and the label-node classification share this pass. `classify` runs in the block visitor across // the pool and is pure -- it is exactly what the old pass 4 body did per node -- and the labels // it returns are drained to the sink **in chunk order**, ahead of every way and relation, which // is the order pass 4 spilled them in and what keeps the archive byte-identical. // // Only label layers are consulted: a node is never a road, a lake or a building, so running the // full schema over 2 B nodes would pay the tag scan for nothing. // // The region filter drops `poi` label nodes outside the bbox here. `places` // nodes are always kept — a region build still names its countries. A `poi` // node carries its own coordinates, so no location table is needed. let classify = |node: &NodeView| { if !select.matches(|k| node.tags.get_str(k)) { return None; } // A node no label claimed may still be road furniture. Safety is asked only here, in the // node pass, so a way or relation can never land in the point-only `safety` layer. let class = schema::classify(&node.tags, false, layers) .filter(|c| is_label(c.layer)) .or_else(|| schema::safety::classify(&node.tags))?; let safety = class.layer == tilecodec::mamaps::dict::LAYER_SAFETY; if (safety || class.layer == tilecodec::mamaps::dict::LAYER_POI) && !osm_ingest::bbox::keep_e7(region, node.lat_e7, node.lon_e7) { return None; } let name = schema::display_name(&node.tags, class.layer); Some(( class, node.lon_e7 as f64 * 1e-7, node.lat_e7 as f64 * 1e-7, name, if safety { tilecodec::mamaps::body::ID_NONE } else { tagged_id(node.id, ELEMENT_NODE) }, )) }; let drain = |hits: Vec<(Class, f64, f64, Option, u64)>| -> Result<()> { for (class, lon, lat, name, id) in hits { let encoded = crate::store::EncodedGeom::live(&Geometry::Points(vec![(lon, lat)]))?; sink.push_named(&class, &encoded, name.as_deref(), id)?; stats.features += 1; stats.nodes_classified += 1; } Ok(()) }; let table = resolve_nodes_with(input, blobs, blob_kinds, "Pass 3: nodes", table, classify, drain)?; Ok(table) } /// The region bbox expanded for the lane join, in degrees. /// /// A recipient is at most 50 m long (`lanefill::MAX_STUB_M`, enforced again in `push`), /// and a donor must share an endpoint node with it — so the shared node sits within ~50 m /// of the recipient, and any donor that can pair with a kept recipient touches the bbox /// expanded by a small margin. 0.1° (~11 km) is two orders of magnitude past the ~100 m /// worst case (a 50 m recipient straddling the border sharing its far endpoint), so the /// fringe keeps every pair materialise can consult while dropping the rest of the planet. /// `None` (world) disables the filter: every way can pair, everything resolves. fn expanded_fringe(region: &osm_ingest::bbox::BBox) -> osm_ingest::bbox::BBox { const MARGIN_DEG: f64 = 0.1; osm_ingest::bbox::BBox { min_lon: (region.min_lon - MARGIN_DEG).max(-180.0), min_lat: (region.min_lat - MARGIN_DEG).max(-90.0), max_lon: (region.max_lon + MARGIN_DEG).min(180.0), max_lat: (region.max_lat + MARGIN_DEG).min(90.0), } } /// Whether the resolved line touches the fringe box. `None` (world) is always true. fn fringe_touches( fringe: Option<&osm_ingest::bbox::BBox>, line: &[(f64, f64)], ) -> bool { let Some(fringe) = fringe else { return true; }; line.iter().any(|&(lon, lat)| fringe.contains(lon, lat)) } #[cfg(test)] mod fringe_tests { use super::*; fn california() -> osm_ingest::bbox::BBox { osm_ingest::bbox::BBox { min_lon: -124.5, min_lat: 32.5, max_lon: -114.0, max_lat: 42.0, } } #[test] fn the_fringe_is_the_bbox_expanded_a_hair_in_every_direction() { let fringe = expanded_fringe(&california()); assert!((fringe.min_lon - (-124.6)).abs() < 1e-9); assert!((fringe.min_lat - 32.4).abs() < 1e-9); assert!((fringe.max_lon - (-113.9)).abs() < 1e-9); assert!((fringe.max_lat - 42.1).abs() < 1e-9); } #[test] fn the_fringe_clamps_at_the_world_edges() { let world = osm_ingest::bbox::BBox { min_lon: -180.0, min_lat: -90.0, max_lon: 180.0, max_lat: 90.0, }; assert_eq!(expanded_fringe(&world), world, "clamped, not wrapped"); } #[test] fn world_keeps_everything_and_the_fringe_keeps_only_what_touches() { let fringe = expanded_fringe(&california()); let inside = vec![(-122.4, 37.8)]; let straddling = vec![(-124.55, 39.0)]; let far = vec![(-100.0, 40.0)]; assert!(fringe_touches(None, &far), "world disables the filter"); assert!(fringe_touches(Some(&fringe), &inside)); assert!( fringe_touches(Some(&fringe), &straddling), "a border-straddling recipient is within the margin", ); assert!(!fringe_touches(Some(&fringe), &far), "Nevada never pairs with California"); assert!( !fringe_touches(Some(&fringe), &[]), "a way with no resolved geometry joins nothing", ); } /// The soundness case: a ≤50 m recipient straddling the border and its donor's /// endpoint at their shared node — both within the margin, so the pair survives. #[test] fn a_border_pair_survives_the_fringe() { let fringe = expanded_fringe(&california()); // Recipient crossing the western edge; shared node 20 m outside. let recipient = vec![(-124.52, 39.0), (-124.4999, 39.0)]; // Donor running outward from the shared node. let donor = vec![(-124.52, 39.0), (-124.53, 39.001)]; assert!(fringe_touches(Some(&fringe), &recipient)); assert!(fringe_touches(Some(&fringe), &donor)); } } include!("extract_part2_s1.rs");