Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / osm_ingest / src / graph_build_part11.rs
graph_build_part11.rs431 lines · 18.3 KiBRaw
| 1 | // ---- the parallel write-write pipeline ----------------------------------- |
| 2 | // |
| 3 | // Re-landed per the TODO(write-pipe) checklist: `bake_batch` is unit-tested on |
| 4 | // synthetic buffers (`graph_build_part10.rs`) for opener count == node span and |
| 5 | // opener edge_ptr == base + run offset, and the pool + in-order drain below sit |
| 6 | // behind that test. The framing bug that sank the first attempt was in |
| 7 | // `bake_batch`: it opened only the nodes up to its last edge's source, so the |
| 8 | // edgeless nodes at the END of a batch (and every node of an edgeless batch) |
| 9 | // never got a record. The "12x" reading was the gate's own message, which |
| 10 | // printed the unpacked BYTE count next to the expected RECORD count — so a |
| 11 | // slightly short nodes.bin read as twelve times too long. |
| 12 | // |
| 13 | // Shape: each round's node range is cut into fixed batches of |
| 14 | // [`WRITE_BATCH_NODES`] nodes. A batch is a pure function of the sorted round |
| 15 | // buffer, its node span and its absolute first edge index, so the pool bakes |
| 16 | // batches in any order; the main thread drains them strictly in batch order, |
| 17 | // which reproduces the serial byte sequence exactly. Baking a wave of batches |
| 18 | // overlaps with draining the previous wave (double buffering), and the two |
| 19 | // zstd-blocked streams compress whole 4096-record blocks on the pool |
| 20 | // ([`ParBlocked`]) instead of one block at a time on the drain thread. |
| 21 | |
| 22 | /// Nodes per bake batch. A constant rather than a function of the thread |
| 23 | /// count, although nothing in the output depends on it: batches drain in |
| 24 | /// order, and a batch's bytes are exactly what the serial loop produced for |
| 25 | /// its span. |
| 26 | const WRITE_BATCH_NODES: u32 = 4096; |
| 27 | |
| 28 | /// Batches baked per wave, per pool thread. A wave is what the drain consumes |
| 29 | /// while the next one bakes, so it bounds the bytes in flight to two waves. |
| 30 | const WAVE_BATCHES_PER_THREAD: usize = 4; |
| 31 | |
| 32 | /// Whole blocks a [`ParBlocked`] stages before compressing them on the pool. |
| 33 | /// 256 blocks is 12 MiB of node records or 7 MiB of edge records per |
| 34 | /// parallel flush, which also makes each scratch-file append that large. |
| 35 | const PAR_BLOCKS: usize = 256; |
| 36 | |
| 37 | /// A [`tilecodec::blocked::BlockedStreamWriter`] whose full blocks are |
| 38 | /// compressed on the pool, behind the drain rather than inside it. |
| 39 | /// |
| 40 | /// Records stage here until [`PAR_BLOCKS`] whole blocks are waiting; that |
| 41 | /// group is handed to the pool to compress ([`tilecodec::blocked::compress_block`] |
| 42 | /// is a pure function of one block) and the drain carries on. Finished groups |
| 43 | /// are collected strictly in the order they were handed off and their frames |
| 44 | /// go to the writer in that order, so the section is exactly what pushing every |
| 45 | /// record through the writer produces. The tail that never fills a block goes |
| 46 | /// through the writer's own `push`, so `finish` frames it exactly as before. |
| 47 | struct ParBlocked { |
| 48 | record_len: usize, |
| 49 | w: tilecodec::blocked::BlockedStreamWriter, |
| 50 | staged: Vec<u8>, |
| 51 | block_bytes: usize, |
| 52 | /// Groups handed to the pool, oldest first. |
| 53 | inflight: std::collections::VecDeque<std::sync::mpsc::Receiver<Vec<Vec<u8>>>>, |
| 54 | } |
| 55 | |
| 56 | /// Compressed groups a [`ParBlocked`] may have outstanding before the drain |
| 57 | /// waits for the oldest: bounds the staged bytes in flight. |
| 58 | const PAR_INFLIGHT: usize = 8; |
| 59 | |
| 60 | impl ParBlocked { |
| 61 | fn create(record_len: usize, scratch: &Path) -> std::io::Result<ParBlocked> { |
| 62 | // planet5 graph v9: every block column-transformed (ZBLK flag), so curve-sorted node |
| 63 | // coordinates and monotone edge pointers compress as small deltas (nodes 3.40 -> 1.92 GB). |
| 64 | let w = tilecodec::blocked::BlockedStreamWriter::create(record_len, scratch)?.with_columns(); |
| 65 | let block_bytes = w.block_bytes(); |
| 66 | Ok(ParBlocked { |
| 67 | record_len, |
| 68 | w, |
| 69 | staged: Vec::with_capacity(block_bytes * PAR_BLOCKS * 2), |
| 70 | block_bytes, |
| 71 | inflight: std::collections::VecDeque::new(), |
| 72 | }) |
| 73 | } |
| 74 | |
| 75 | /// Append whole records. |
| 76 | #[inline] |
| 77 | fn push(&mut self, records: &[u8]) -> std::io::Result<()> { |
| 78 | self.staged.extend_from_slice(records); |
| 79 | if self.staged.len() >= self.block_bytes * PAR_BLOCKS { |
| 80 | self.hand_off(); |
| 81 | self.collect(false)?; |
| 82 | } |
| 83 | Ok(()) |
| 84 | } |
| 85 | |
| 86 | /// Hand every whole staged block to the pool as one group; keep the |
| 87 | /// partial tail staged. |
| 88 | fn hand_off(&mut self) { |
| 89 | let full = self.staged.len() / self.block_bytes * self.block_bytes; |
| 90 | if full == 0 { |
| 91 | return; |
| 92 | } |
| 93 | let tail = self.staged[full..].to_vec(); |
| 94 | let mut group = std::mem::replace(&mut self.staged, Vec::with_capacity(self.block_bytes * PAR_BLOCKS * 2)); |
| 95 | group.truncate(full); |
| 96 | self.staged.extend_from_slice(&tail); |
| 97 | let bb = self.block_bytes; |
| 98 | let rl = self.record_len; |
| 99 | let (tx, rx) = std::sync::mpsc::sync_channel(1); |
| 100 | par::spawn(move || { |
| 101 | let frames: Vec<Vec<u8>> = group |
| 102 | .par_chunks(bb) |
| 103 | .map(|b| tilecodec::blocked::compress_block_columns(b, rl)) |
| 104 | .collect(); |
| 105 | let _ = tx.send(frames); |
| 106 | }); |
| 107 | self.inflight.push_back(rx); |
| 108 | } |
| 109 | |
| 110 | /// Pass finished groups to the writer, oldest first: every ready one, plus |
| 111 | /// — when too many are outstanding, or `all` — waiting for the oldest. |
| 112 | fn collect(&mut self, all: bool) -> std::io::Result<()> { |
| 113 | while let Some(rx) = self.inflight.front() { |
| 114 | let must_wait = all || self.inflight.len() > PAR_INFLIGHT; |
| 115 | let frames = if must_wait { |
| 116 | rx.recv().map_err(|_| std::io::Error::other("a block compressor died"))? |
| 117 | } else { |
| 118 | match rx.try_recv() { |
| 119 | Ok(f) => f, |
| 120 | Err(std::sync::mpsc::TryRecvError::Empty) => break, |
| 121 | Err(std::sync::mpsc::TryRecvError::Disconnected) => { |
| 122 | return Err(std::io::Error::other("a block compressor died")); |
| 123 | } |
| 124 | } |
| 125 | }; |
| 126 | self.inflight.pop_front(); |
| 127 | self.w.push_frames(&frames)?; |
| 128 | } |
| 129 | Ok(()) |
| 130 | } |
| 131 | |
| 132 | /// Finish the section straight into `out` (see |
| 133 | /// [`tilecodec::blocked::BlockedStreamWriter::finish_into`]). Returns its |
| 134 | /// length. |
| 135 | fn finish_into<W: Write>(mut self, out: &mut W) -> std::io::Result<u64> { |
| 136 | self.hand_off(); |
| 137 | self.collect(true)?; |
| 138 | let tail = std::mem::take(&mut self.staged); |
| 139 | self.w.push(&tail)?; |
| 140 | self.w.finish_into(out) |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | /// One baked write batch: every byte the serial loop would have produced for |
| 145 | /// one span of nodes, staged per output stream. |
| 146 | /// |
| 147 | /// Positional: `node_recs` holds one 12-byte record per node of the span |
| 148 | /// (edgeless ones included) with its ABSOLUTE `edge_ptr`; every per-edge side |
| 149 | /// table is keyed by the edge's offset within the batch, which the drain turns |
| 150 | /// into an absolute index by adding the batch's base. Nothing in here depends |
| 151 | /// on any other batch, which is what lets the pool bake them in any order. |
| 152 | #[derive(Default)] |
| 153 | struct BakedBatch { |
| 154 | /// Node records, 12 B each, one per node of the span, in node order. |
| 155 | node_recs: Vec<u8>, |
| 156 | /// Edges in the batch. |
| 157 | edge_count: u64, |
| 158 | /// Edge records, 7 B each, already narrowed (escape sentinels in place). |
| 159 | edge_recs: Vec<u8>, |
| 160 | /// `(edge offset, target, dist_mm)` for each escaped edge, ascending. |
| 161 | escapes: Vec<(u32, u32, u32)>, |
| 162 | /// `(edge offset, name_offset)` for each named edge, ascending. |
| 163 | names: Vec<(u32, u32)>, |
| 164 | /// Encoded interior polylines of the storing edges, concatenated in order. |
| 165 | geom: Vec<u8>, |
| 166 | /// `(edge offset, blob length)` per storing edge, ascending. |
| 167 | geom_runs: Vec<(u32, u32)>, |
| 168 | /// Lane masks (`u16` LE) of the lane-bearing edges, concatenated in order. |
| 169 | lanes: Vec<u8>, |
| 170 | /// `(edge offset, byte length)` per lane-bearing edge, ascending. |
| 171 | lane_runs: Vec<(u32, u32)>, |
| 172 | /// The census over this batch's nodes and edges. Sums and maxima only, so |
| 173 | /// merging batch censuses in any order equals the serial census. |
| 174 | census: Census, |
| 175 | geometry_edges: u64, |
| 176 | reversed_edges: u64, |
| 177 | } |
| 178 | |
| 179 | impl BakedBatch { |
| 180 | /// Nodes in the batch's span. |
| 181 | #[cfg(test)] |
| 182 | fn node_count(&self) -> usize { |
| 183 | self.node_recs.len() / 12 |
| 184 | } |
| 185 | |
| 186 | /// Node record `i` of the span as `(lat_e7, lon_e7, edge_ptr)`. |
| 187 | #[cfg(test)] |
| 188 | fn opener(&self, i: usize) -> (i32, i32, u32) { |
| 189 | let r = &self.node_recs[i * 12..i * 12 + 12]; |
| 190 | ( |
| 191 | i32::from_le_bytes(r[0..4].try_into().expect("4 bytes")), |
| 192 | i32::from_le_bytes(r[4..8].try_into().expect("4 bytes")), |
| 193 | u32::from_le_bytes(r[8..12].try_into().expect("4 bytes")), |
| 194 | ) |
| 195 | } |
| 196 | } |
| 197 | |
| 198 | impl Census { |
| 199 | /// Fold another census in. Every field is a count or a maximum, so this is |
| 200 | /// order-independent and equals recording both sets of items into one. |
| 201 | fn merge(&mut self, o: &Census) { |
| 202 | for (a, b) in self.delta_bits.iter_mut().zip(o.delta_bits.iter()) { |
| 203 | *a += *b; |
| 204 | } |
| 205 | self.delta_escapes += o.delta_escapes; |
| 206 | self.dist_escapes += o.dist_escapes; |
| 207 | self.escapes += o.escapes; |
| 208 | self.max_delta = self.max_delta.max(o.max_delta); |
| 209 | self.max_dist_mm = self.max_dist_mm.max(o.max_dist_mm); |
| 210 | self.max_degree = self.max_degree.max(o.max_degree); |
| 211 | self.degree_zero_nodes += o.degree_zero_nodes; |
| 212 | self.named_edges += o.named_edges; |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | /// Bake one write batch: the node span `first_node..end_node`, whose edges are |
| 217 | /// exactly `edges` (a source-sorted slice of the round buffer), with the |
| 218 | /// batch's first edge at absolute index `batch_edge_base`. |
| 219 | /// |
| 220 | /// Walks the SPAN, not the edges — the serial loop's own shape — so every node |
| 221 | /// opens exactly once whether or not it has edges, and each opener's |
| 222 | /// `edge_ptr` is the base plus the edges before it in the batch. Per edge it |
| 223 | /// mirrors the serial body exactly: census, twin-check-before-read, polyline |
| 224 | /// read + reverse + `geom::fits` + `assert_endpoints` + encode, the narrowing |
| 225 | /// of `EdgeFile::push`, name and lanes. |
| 226 | /// |
| 227 | /// Pure over shared tables (`node_coords`, `lane_pool`, `csr`, `synth`, the |
| 228 | /// `chains.pts` mapping): safe across the pool. Fallible only like the serial |
| 229 | /// loop was — a truncated `chains.pts` fails the build rather than shortening |
| 230 | /// it — and the drain reports the first failure in batch order. |
| 231 | #[allow(clippy::too_many_arguments)] |
| 232 | fn bake_batch( |
| 233 | edges: &[TmpEdge], |
| 234 | first_node: u32, |
| 235 | end_node: u32, |
| 236 | batch_edge_base: u64, |
| 237 | node_coords: &[geom::Pt], |
| 238 | lane_pool: &[u16], |
| 239 | csr: &Csr, |
| 240 | synth: &[Synth], |
| 241 | points: &crate::mem::Mapped, |
| 242 | ) -> Result<BakedBatch> { |
| 243 | let span = (end_node - first_node) as usize; |
| 244 | let mut b = BakedBatch { |
| 245 | node_recs: Vec::with_capacity(span * 12), |
| 246 | edge_recs: Vec::with_capacity(edges.len() * EDGE_REC_BYTES as usize), |
| 247 | ..BakedBatch::default() |
| 248 | }; |
| 249 | let mut scratch: Vec<geom::Pt> = Vec::new(); |
| 250 | let mut cursor = 0usize; |
| 251 | for v in first_node..end_node { |
| 252 | let node = node_coords[v as usize]; |
| 253 | let edge_ptr = batch_edge_base + cursor as u64; |
| 254 | b.node_recs.extend_from_slice(&node.0.to_le_bytes()); |
| 255 | b.node_recs.extend_from_slice(&node.1.to_le_bytes()); |
| 256 | b.node_recs.extend_from_slice(&(edge_ptr as u32).to_le_bytes()); |
| 257 | let degree_base = cursor; |
| 258 | while cursor < edges.len() && edges[cursor].source == v { |
| 259 | let e = &edges[cursor]; |
| 260 | let local = cursor as u32; |
| 261 | let named = e.name_offset != NO_NAME; |
| 262 | b.census.edge(e.source, e.target, e.dist_mm, named); |
| 263 | |
| 264 | // --- geometry --- |
| 265 | let mut type_ = e.type_; |
| 266 | // A two-point chain is just the chord between the edge's own |
| 267 | // endpoints, and under the interior-only encoding that is what an |
| 268 | // absent blob already means, so storing it would cost a presence |
| 269 | // bit to say nothing — and a read to find that out. |
| 270 | if e.chain != NO_CHAIN && e.pts_len >= 3 { |
| 271 | if e.chain_rev |
| 272 | && e.source != e.target |
| 273 | && twin_is_unique(csr, synth, e.source, e.target) |
| 274 | { |
| 275 | type_ |= REVERSE_GEOMETRY_FLAG; |
| 276 | b.reversed_edges += 1; |
| 277 | } else { |
| 278 | // Only now is the polyline needed: this is the only random |
| 279 | // read in the writer, so every edge that defers to its twin |
| 280 | // is one read saved. Shared mapping, no lock. |
| 281 | chains::PointReader::read_shared(points, e.pts_start, e.pts_len, &mut scratch)?; |
| 282 | if e.chain_rev { |
| 283 | scratch.reverse(); |
| 284 | } |
| 285 | assert!( |
| 286 | geom::fits(&scratch), |
| 287 | "chain of {} points cannot be encoded; the collapse should \ |
| 288 | have split it", |
| 289 | scratch.len() |
| 290 | ); |
| 291 | // The blob holds only the interior, so the reader rebuilds |
| 292 | // both ends out of `nodes.bin`. |
| 293 | assert_endpoints(&scratch, node_coords, e.source, e.target, e.chain); |
| 294 | let before = b.geom.len(); |
| 295 | let n = geom::encode(&scratch, &mut b.geom); |
| 296 | debug_assert_eq!(n as usize, geom::encoded_points(&scratch) as usize); |
| 297 | b.geom_runs.push((local, (b.geom.len() - before) as u32)); |
| 298 | b.geometry_edges += 1; |
| 299 | } |
| 300 | } |
| 301 | |
| 302 | // --- the edge record: `EdgeFile::push`'s narrowing, verbatim --- |
| 303 | let (delta, dist) = match target_delta(e.source, e.target) { |
| 304 | Some(d) if e.dist_mm < DIST_MM_ESCAPE => (d, e.dist_mm), |
| 305 | _ => { |
| 306 | b.escapes.push((local, e.target, e.dist_mm)); |
| 307 | (TARGET_DELTA_ESCAPE, DIST_MM_ESCAPE) |
| 308 | } |
| 309 | }; |
| 310 | let mut rec = [0u8; EDGE_REC_BYTES as usize]; |
| 311 | rec[0..2].copy_from_slice(&delta.to_le_bytes()); |
| 312 | rec[2..5].copy_from_slice(&dist.to_le_bytes()[..3]); |
| 313 | rec[5] = type_; |
| 314 | rec[6] = e.speed_limit; |
| 315 | b.edge_recs.extend_from_slice(&rec); |
| 316 | if named { |
| 317 | b.names.push((local, e.name_offset)); |
| 318 | } |
| 319 | |
| 320 | // --- lanes --- |
| 321 | if e.lane_count > 0 && e.lane_off != NO_LANES { |
| 322 | let start = e.lane_off as usize; |
| 323 | let before = b.lanes.len(); |
| 324 | for m in &lane_pool[start..start + e.lane_count as usize] { |
| 325 | b.lanes.extend_from_slice(&m.to_le_bytes()); |
| 326 | } |
| 327 | b.lane_runs.push((local, (b.lanes.len() - before) as u32)); |
| 328 | } |
| 329 | cursor += 1; |
| 330 | } |
| 331 | b.census.node((cursor - degree_base) as u32); |
| 332 | } |
| 333 | // Every edge handed to the batch must belong to a node of its span: an edge |
| 334 | // left over here would silently vanish from the pack. |
| 335 | if cursor != edges.len() { |
| 336 | return Err(Error(format!( |
| 337 | "write batch over node(s) {first_node}..{end_node} left {} edge(s) unbaked \ |
| 338 | (first stray source {})", |
| 339 | edges.len() - cursor, |
| 340 | edges[cursor].source |
| 341 | ))); |
| 342 | } |
| 343 | b.edge_count = edges.len() as u64; |
| 344 | Ok(b) |
| 345 | } |
| 346 | |
| 347 | /// Everything the in-order drain appends to. |
| 348 | struct WriteSinks<'a> { |
| 349 | nodes: &'a mut ParBlocked, |
| 350 | edges: &'a mut EdgeFile, |
| 351 | inter: &'a mut GeomFile, |
| 352 | lanes: &'a mut LaneFile, |
| 353 | census: &'a mut Census, |
| 354 | geometry_edges: &'a mut u64, |
| 355 | reversed_edges: &'a mut u64, |
| 356 | } |
| 357 | |
| 358 | /// Append one baked batch, whose first edge is absolute index `base`. |
| 359 | /// |
| 360 | /// Strictly positional, and the only writer into the streams: node records, |
| 361 | /// edge records, escape rows, name bits, presence bits and offsets, polyline |
| 362 | /// bytes and lane runs all go out exactly as the serial loop emitted them. |
| 363 | fn drain_batch(s: &mut WriteSinks, b: &BakedBatch, base: u64) -> Result<()> { |
| 364 | debug_assert_eq!(s.edges.pushed, base, "batches drained out of order"); |
| 365 | s.nodes |
| 366 | .push(&b.node_recs) |
| 367 | .map_err(|e| Error(format!("cannot stage node record: {e}")))?; |
| 368 | s.edges.push_baked(b, base)?; |
| 369 | s.inter.store_batch(base, b)?; |
| 370 | let mut at = 0usize; |
| 371 | for &(local, len) in &b.lane_runs { |
| 372 | s.lanes.push(base + u64::from(local), &b.lanes[at..at + len as usize])?; |
| 373 | at += len as usize; |
| 374 | } |
| 375 | s.census.merge(&b.census); |
| 376 | *s.geometry_edges += b.geometry_edges; |
| 377 | *s.reversed_edges += b.reversed_edges; |
| 378 | Ok(()) |
| 379 | } |
| 380 | |
| 381 | impl EdgeFile { |
| 382 | /// Append a baked batch's records and side tables, its first edge being |
| 383 | /// absolute index `base`. Same rows, bits and offsets as calling |
| 384 | /// `EdgeFile::push` once per edge. |
| 385 | fn push_baked(&mut self, b: &BakedBatch, base: u64) -> Result<()> { |
| 386 | for &(local, target, dist) in &b.escapes { |
| 387 | let idx = cap_u32("escaped edge index", base + u64::from(local))?; |
| 388 | self.escapes.push((idx, target, dist)); |
| 389 | } |
| 390 | self.blocked |
| 391 | .push(&b.edge_recs) |
| 392 | .map_err(|e| Error(format!("cannot stage edge record: {e}")))?; |
| 393 | for &(local, off) in &b.names { |
| 394 | self.named.set(base + u64::from(local)); |
| 395 | self.name_offsets.push(off); |
| 396 | } |
| 397 | self.pushed += b.edge_count; |
| 398 | Ok(()) |
| 399 | } |
| 400 | } |
| 401 | |
| 402 | impl GeomFile { |
| 403 | /// Append a baked batch: presence bits, offset entries and polyline bytes |
| 404 | /// for its storing edges, a skip for every other edge. Same state as the |
| 405 | /// serial sequence of `GeomFile::store` / `GeomFile::skip` calls, with |
| 406 | /// the batch's blob going out as one write. |
| 407 | fn store_batch(&mut self, base: u64, b: &BakedBatch) -> Result<()> { |
| 408 | for &(local, len) in &b.geom_runs { |
| 409 | debug_assert!(len > 0, "an interior-only blob of no bytes is the chord"); |
| 410 | self.pushed = base + u64::from(local); |
| 411 | self.present.set(self.pushed); |
| 412 | self.push_entry(); |
| 413 | self.blob_len += u64::from(len); |
| 414 | self.stored += 1; |
| 415 | } |
| 416 | self.out.write_all(&b.geom).map_err(io_err)?; |
| 417 | self.pushed = base + b.edge_count; |
| 418 | Ok(()) |
| 419 | } |
| 420 | } |
| 421 | |
| 422 | /// Chains per parallel scan/gather chunk in the writer. Fixed, so chunking |
| 423 | /// cannot depend on the thread count (nor could it change the output: chunks |
| 424 | /// concatenate in order). |
| 425 | const SCAN_CHUNK: usize = 1 << 16; |
| 426 | |
| 427 | /// Buffer for the writer's sequential output streams: large appends, since on |
| 428 | /// a compress-force filesystem every extent costs CPU. |
| 429 | const WRITE_BUF_BYTES: usize = 8 << 20; |
| 430 | |
| 431 | include!("graph_build_part11_s1.rs"); |