// --- pool-built records ------------------------------------------------------------------------ // // The materialise drains used to build every spill record on the one serial thread: the props // list (a `String` per key), `encode_props`, the record header, and -- per 64 features -- a DEFLATE // frame. On California that was 19.0 s of a 26.6 s `materialise-ways`; on the planet, ~1.1 B ways, // it was the bulk of a 30-40 minute single-core phase. Everything up to the record bytes is a pure // function of one feature, so it now runs on the pool ([`PreRecord`]) and the serial thread only // appends ([`Sink::push_pre`]); the frames compress in batches on the pool inside the writer. // // The props builders below are the bodies `push_named` / `push_road` / `push_building` always had, // moved out so both paths run the very same code. Same props, same `encode_props`, same header: // the same bytes. /// `push_named`'s props: the packed class, then the name and the tagged id when present. fn fill_named( props: &mut Vec<(String, Value)>, class: &Class, name: Option<&str>, id: u64, ) -> Result<()> { props[0].1 = Value::Uint(pack(class)?); props.truncate(1); if let Some(name) = name.filter(|n| !n.is_empty()) { props.push((NAME_KEY.to_string(), Value::String(name.to_string()))); } if id != tilecodec::mamaps::body::ID_NONE { if !crate::extract::tracks_ids(class) { return err(format!( "layer {} carries a feature id, which only places, poi and a boundaries region shape may", class.layer, )); } props.push((ID_KEY.to_string(), Value::Uint(id))); } Ok(()) } /// `push_road`'s props, including its refusal of a road with nothing to carry. fn fill_road( props: &mut Vec<(String, Value)>, class: &Class, name: Option<&str>, lane_count: u8, turn_fwd: &[u16], turn_bwd: &[u16], carriageway: Carriageway, ) -> Result<()> { if name.is_none() && lane_count == 0 && turn_fwd.is_empty() && turn_bwd.is_empty() && carriageway.is_empty() { return err("a road pushed with no lane data".to_string()); } props[0].1 = Value::Uint(pack(class)?); props.truncate(1); if let Some(name) = name.filter(|n| !n.is_empty()) { props.push((NAME_KEY.to_string(), Value::String(name.to_string()))); } if lane_count > 0 { props.push((LANE_COUNT_KEY.to_string(), Value::Uint(lane_count as u64))); } if !turn_fwd.is_empty() { props.push((TURN_FWD_KEY.to_string(), Value::String(osm_ingest::roads::pack_lanes(turn_fwd)))); } if !turn_bwd.is_empty() { props.push((TURN_BWD_KEY.to_string(), Value::String(osm_ingest::roads::pack_lanes(turn_bwd)))); } if !carriageway.is_empty() { props.push((CARRIAGEWAY_KEY.to_string(), Value::Uint(pack_carriageway(carriageway)))); } Ok(()) } /// `push_building`'s props: class, optional name, then the three packed S3DB words. fn fill_building( props: &mut Vec<(String, Value)>, class: &Class, name: Option<&str>, attrs: BuildingAttrs, ) -> Result<()> { props[0].1 = Value::Uint(pack(class)?); props.truncate(1); if let Some(name) = name.filter(|n| !n.is_empty()) { props.push((NAME_KEY.to_string(), Value::String(name.to_string()))); } let (a, b, c) = pack_building(&attrs); props.push((BLD_A_KEY.to_string(), Value::Uint(a))); props.push((BLD_B_KEY.to_string(), Value::Uint(b))); props.push((BLD_C_KEY.to_string(), Value::Uint(c))); Ok(()) } /// One feature's spill record, built off the serial thread. /// /// Carries what [`Sink::write_record`] needs beyond the bytes -- the geometry kind and bounds for /// the writer's summary, the e7 box for the sink's bbox, the class's `min_zoom` for the chunk /// index -- so [`Sink::push_pre`] repeats `write_record`'s bookkeeping exactly. pub struct PreRecord { rec: Vec, kind: GeomKind, bounds: Option, ebbx: Option<(i32, i32, i32, i32)>, min_zoom: u8, } impl PreRecord { /// What [`Sink::push_named`] would stage. pub fn named( class: &Class, geometry: &EncodedGeom, name: Option<&str>, id: u64, ) -> Result { let mut props = vec![(CLASS_KEY.to_string(), Value::Uint(0))]; fill_named(&mut props, class, name, id)?; Self::build(class, geometry, &props) } /// What [`Sink::push_road`] would stage. #[allow(clippy::too_many_arguments)] pub fn road( class: &Class, geometry: &EncodedGeom, name: Option<&str>, lane_count: u8, turn_fwd: &[u16], turn_bwd: &[u16], carriageway: Carriageway, ) -> Result { let mut props = vec![(CLASS_KEY.to_string(), Value::Uint(0))]; fill_road(&mut props, class, name, lane_count, turn_fwd, turn_bwd, carriageway)?; Self::build(class, geometry, &props) } /// What [`Sink::push_building`] would stage. pub fn building( class: &Class, geometry: &EncodedGeom, name: Option<&str>, attrs: BuildingAttrs, ) -> Result { let mut props = vec![(CLASS_KEY.to_string(), Value::Uint(0))]; fill_building(&mut props, class, name, attrs)?; Self::build(class, geometry, &props) } fn build(class: &Class, geometry: &EncodedGeom, props: &[(String, Value)]) -> Result { let mut rec = Vec::with_capacity(64 + geometry.bytes.len()); tile_build::spill::encode_normalized_record(geometry.kind, &geometry.bytes, props, &mut rec) .map_err(|e| osm_ingest::proto::Error(e.to_string()))?; Ok(PreRecord { rec, kind: geometry.kind, bounds: geometry.bounds, ebbx: geometry.ebbx, min_zoom: class.min_zoom, }) } } /// Many pool-built records in one buffer, for [`Sink::push_run`]: what the materialise drains /// used to push one `PreRecord` at a time. Built on the pool (one per ways block, per junction /// group), so the serial thread does one call per run instead of per-record bookkeeping -- on the /// planet ~1.1 B records, which was the floor under `materialise-ways` (195 s, all of it drain). #[derive(Default)] pub struct RecordRun { bytes: Vec, ends: Vec, min_zoom: Vec, first_kind: Option, bounds: Option, ebbx: Option<(i32, i32, i32, i32)>, } impl RecordRun { /// Append one record, folding its facts exactly as `Sink::push_pre` would one at a time. pub fn add(&mut self, record: PreRecord) { if self.bytes.is_empty() && self.ends.is_empty() { self.bytes = record.rec; } else { self.bytes.extend_from_slice(&record.rec); } self.ends.push(self.bytes.len()); self.min_zoom.push(record.min_zoom); if self.first_kind.is_none() { self.first_kind = Some(record.kind); } self.bounds = match (self.bounds, record.bounds) { (None, b) => b, (a, None) => a, (Some(a), Some(b)) => Some(Rect { min_x: a.min_x.min(b.min_x), min_y: a.min_y.min(b.min_y), max_x: a.max_x.max(b.max_x), max_y: a.max_y.max(b.max_y), }), }; if let Some((x0, y0, x1, y1)) = record.ebbx { self.ebbx = Some(match self.ebbx { None => (x0, y0, x1, y1), Some(e) => (e.0.min(x0), e.1.min(y0), e.2.max(x1), e.3.max(y1)), }); } } pub fn len(&self) -> usize { self.ends.len() } } impl Sink { /// Append a whole [`RecordRun`]: the same writer bytes, chunk minimums, count and bounding box /// as `push_pre` on each of its records in order. The chunk minimums close on the same /// 64-record boundaries; the box and the summary folds are min/max, so folding a run first /// changes nothing. pub fn push_run(&mut self, run: RecordRun) -> Result<()> { let RecordRun { bytes, ends, min_zoom, first_kind, bounds, ebbx } = run; if ends.is_empty() { return Ok(()); } self.writer .push_run(bytes, &ends, first_kind, bounds) .map_err(|e| osm_ingest::proto::Error(e.to_string()))?; let per = NORM_CHUNK_FEATURES as usize; let mut rest = &min_zoom[..]; while !rest.is_empty() { let room = per - (self.count % NORM_CHUNK_FEATURES) as usize; let take = room.min(rest.len()); let m = rest[..take].iter().copied().min().expect("non-empty"); self.filling = self.filling.min(m); self.count += take as u64; if self.count % NORM_CHUNK_FEATURES == 0 { self.chunk_mins.push(self.filling); self.filling = u8::MAX; } rest = &rest[take..]; } self.grow_bounds(ebbx); Ok(()) } /// Append a pool-built record: [`write_record`](Self::write_record) with the encoding already /// done. Same writer call, same chunk-min, count and bbox bookkeeping, in the same order. pub fn push_pre(&mut self, record: &PreRecord) -> Result<()> { self.writer .push_record(record.kind, &record.rec, record.bounds) .map_err(|e| osm_ingest::proto::Error(e.to_string()))?; self.filling = self.filling.min(record.min_zoom); self.count += 1; if self.count % NORM_CHUNK_FEATURES == 0 { self.chunk_mins.push(self.filling); self.filling = u8::MAX; } self.grow_bounds(record.ebbx); Ok(()) } } // --- the ways spill, in blocks --------------------------------------------------------------------- // // The ways spill is one varint stream whose ids are delta-coded from record to record, so it could // only ever be read by one cursor -- and it is read twice (lane inheritance, materialise), 1.1 B // records on the planet, with every way decoded on one thread: 6 min and 30-40 min phases running // at 4-6 of 192 cores. And it was *written* by pass 1's serial drain, record by record, which is // what held pass 1 to ~4 cores for 4m40s. // // The stream is unchanged, byte for byte. What is new is an index over it: every // [`WAY_BLOCK_WAYS`]-ish run of records is a [`WayBlockLoc`] -- its byte range plus the id the // first record's delta is taken from -- so any run decodes on its own. Pass 1's workers encode // their chunk's ways into [`WayBlock`]s (the record bytes with the first id left open), the drain // only patches that one varint and appends, and the two readers decode blocks across the pool // ([`WayBlocks`]) and consume them in block order, which is spill order. /// Ways per index entry, at most. Small enough that a planet pass decodes ~280 k blocks across the /// pool with even load; large enough that the index is a few MB. pub const WAY_BLOCK_WAYS: u64 = 4096; /// One run of the ways spill that decodes on its own. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct WayBlockLoc { /// Byte offset of the run's first record in the spill. offset: u64, /// Bytes in the run. len: u64, /// The id the first record's delta is taken from: the previous record's id, or zero. start_last_id: i64, /// Records in the run. ways: u64, } impl WayBlockLoc { pub fn ways(&self) -> u64 { self.ways } } /// A run of way records encoded off the serial thread, for [`WaySink::push_block`]. /// /// Exactly the bytes [`WaySink::push`] would write for the same ways, except that the first /// record's id delta is left open (it is relative to whatever the sink saw last, which a worker /// cannot know): the block stores that varint as the absolute id and remembers its length, and the /// sink re-encodes just that varint. pub struct WayBlock { bytes: Vec, /// Length of the first record's id varint at the head of `bytes`. head_len: usize, first_id: i64, last_id: i64, count: u64, refs: u64, max_ref: i64, } impl Default for WayBlock { fn default() -> Self { Self::new() } } impl WayBlock { pub fn new() -> WayBlock { WayBlock { bytes: Vec::new(), head_len: 0, first_id: 0, last_id: 0, count: 0, refs: 0, max_ref: 0 } } /// Ways encoded so far. pub fn len(&self) -> u64 { self.count } #[allow(dead_code)] pub fn is_empty(&self) -> bool { self.count == 0 } /// Encode one way. Same arguments, same ordering rule and same record bytes as /// [`WaySink::push`]. #[allow(clippy::too_many_arguments)] pub fn push( &mut self, id: i64, class: &Class, refs: &[i64], name: Option<&str>, lane_count: u8, turn_fwd: &[u16], turn_bwd: &[u16], carriageway: Carriageway, building: Option, ) -> Result<()> { if self.count > 0 && id <= self.last_id { return err(unsorted_ways(id, self.last_id)); } if self.count == 0 { put_svarint(&mut self.bytes, id); self.head_len = self.bytes.len(); self.first_id = id; } else { put_svarint(&mut self.bytes, id.wrapping_sub(self.last_id)); } let max_ref = encode_way_tail( &mut self.bytes, class, refs, name, lane_count, turn_fwd, turn_bwd, carriageway, building, )?; self.max_ref = self.max_ref.max(max_ref); self.last_id = id; self.count += 1; self.refs += refs.len() as u64; Ok(()) } } /// The error a non-advancing way id gets, from the sink and from a block alike. fn unsorted_ways(id: i64, last_id: i64) -> String { format!( "way {id} arrived after way {last_id}, so this PBF is not sorted by way id and the \ sequential ways spill cannot be used for it", ) } include!("store_part6_s1.rs");