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

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

graph_build_part4.rs481 lines · 19.9 KiBRaw
1/// The endpoint guarantee `intermediate.bin`'s interior-only encoding rests on: a
2/// chain's first and last points are the coordinates of its first and last node.
3///
4/// True by construction, since both come from the same `node_coords` array, but
5/// never checked before v3 — and the reader now *depends* on it, because it rebuilds
6/// both ends out of `nodes.bin`. If this ever stopped holding, the failure would be
7/// a silently wrong polyline on device rather than a failed build.
8fn assert_endpoints(
9 chain: &[geom::Pt],
10 node_coords: &[geom::Pt],
11 source: u32,
12 target: u32,
13 ci: u32,
14) {
15 assert_eq!(
16 chain[0], node_coords[source as usize],
17 "chain {ci} starts off its source node {source}"
18 );
19 assert_eq!(
20 chain[chain.len() - 1], node_coords[target as usize],
21 "chain {ci} ends off its target node {target}"
22 );
23}
24
25/// One directed edge of a chain, in final id space.
26fn chain_edge(c: &chains::ChainRec, ci: u32, source: u32, target: u32, rev: bool) -> TmpEdge {
27 TmpEdge {
28 source,
29 target,
30 dist_mm: c.dist_mm,
31 name_offset: c.name_offset,
32 type_: c.type_,
33 speed_limit: c.speed_limit,
34 lane_off: if rev { c.bwd_lane_off } else { c.fwd_lane_off },
35 lane_count: if rev { c.bwd_lane_count } else { c.fwd_lane_count },
36 chain: ci,
37 chain_rev: rev,
38 pts_start: c.pts_start,
39 pts_len: c.pts_len,
40 }
41}
42
43/// `intermediate.bin`: the polyline blob at offset 0, then everything needed to
44/// index it as a **trailer**.
45///
46/// ```text
47/// [ blob ]
48/// [ u64 rank[E.div_ceil(512) + 1] ] set bits before each 64-byte block, total appended
49/// [ u8 present[E.div_ceil(8)] ] one bit per directed edge
50/// [ u64 coarse[G.div_ceil(32) + 1] ] G = the edges that store a polyline
51/// [ u16 within[G + 1] ]
52/// [ u64 G ] fixed-size trailer
53/// ```
54///
55/// `off(g) = coarse[g / 32] + within[g]` for the *g*-th geometry edge, where
56/// `g = rank(idx)`; entry *g* runs to `off(g + 1)`, so the sentinel gives the last
57/// edge its length and the blob its total.
58///
59/// # Why the offsets describe geometry edges, not edges
60///
61/// 70.4% of a planet's directed edges store no polyline at all (measured on
62/// Europe: 110,807,665 of 374,856,290 store one), and under v2 each of them still
63/// owned a `u16` and a repeated coarse `u64`. A presence bitmap costs one bit per
64/// edge and makes "absent" an explicit, free test, which takes 0.87 GB of tables
65/// where v2 needed 2.42 GB. It also tightens the `u16` bound rather than loosening
66/// it: every entry in a block is now a real blob, where before most were
67/// zero-length.
68///
69/// # Why the tables come last
70///
71/// `G` is not known until the final round has run, so a reserved prefix cannot be
72/// sized. Streaming the blob to scratch and copying it back \u2014 what [`LaneFile`]
73/// does, which is free for 13 MB \u2014 would be ~23 GB of extra I/O here. A trailer
74/// instead makes the whole file append-only with **no scratch file at all**: write
75/// the blob as it is encoded, then append the tables and `G`. That is strictly
76/// less I/O than v2, which copied a 2.4 GB prefix back.
77///
78/// The tables are held in memory rather than spilled, which is 0.87 GB at planet
79/// scale against the blob's 7.63 GB.
80struct GeomFile {
81 path: PathBuf,
82 out: BufWriter<File>,
83 blob_len: u64,
84 /// One bit per directed edge, sized up front from the edge count.
85 present: PresenceBitmap,
86 coarse: Vec<u64>,
87 within: Vec<u16>,
88 /// Blob offset of the first geometry edge in the block being filled, i.e. the
89 /// coarse entry the `u16`s are currently relative to.
90 block_base: u64,
91 /// Directed edges seen so far, which is the index the next call describes.
92 pushed: u64,
93 /// Geometry edges so far, i.e. `G` once the file is complete.
94 stored: u64,
95}
96
97impl GeomFile {
98 /// Byte size of the trailer for `edge_count` directed edges of which
99 /// `geometry_edges` store a polyline. The reader sizes it the same way, from
100 /// `edges.bin`'s length and the final `u64`.
101 fn trailer_bytes(edge_count: u64, geometry_edges: u64) -> u64 {
102 PresenceBitmap::bytes(edge_count)
103 + (geometry_edges.div_ceil(INTERMEDIATE_BLOCK) + 1) * 8
104 + (geometry_edges + 1) * 2
105 + 8
106 }
107
108 fn create(dir: &Path, name: &str, edge_count: u64) -> Result<GeomFile> {
109 let path = dir.join(name);
110 Ok(GeomFile {
111 // Large appends: the drain hands over one batch's blobs at a time, and
112 // on a compress-force filesystem every extent costs CPU.
113 out: BufWriter::with_capacity(WRITE_BUF_BYTES, create(&path)?),
114 path,
115 blob_len: 0,
116 present: PresenceBitmap::new(edge_count),
117 coarse: Vec::new(),
118 within: Vec::new(),
119 block_base: 0,
120 pushed: 0,
121 stored: 0,
122 })
123 }
124
125 /// This edge stores no polyline. Its presence bit stays clear and it owns no
126 /// offset at all, which is the whole point of the bitmap.
127 #[cfg(test)]
128 fn skip(&mut self) {
129 self.pushed += 1;
130 }
131
132 /// Record `bytes` as this edge's polyline. Called once per storing edge, in
133 /// ascending edge index, because the rounds ascend and each round writes its
134 /// edges in index order.
135 #[cfg(test)]
136 fn store(&mut self, bytes: &[u8]) -> Result<()> {
137 debug_assert!(
138 !bytes.is_empty(),
139 "an interior-only blob of no bytes is the chord, which needs no presence bit"
140 );
141 self.present.set(self.pushed);
142 self.push_entry();
143 self.out.write_all(bytes).map_err(io_err)?;
144 self.blob_len += bytes.len() as u64;
145 self.stored += 1;
146 self.pushed += 1;
147 Ok(())
148 }
149
150 /// One `(coarse?, within)` pair for geometry index `self.stored`.
151 fn push_entry(&mut self) {
152 if self.stored % INTERMEDIATE_BLOCK == 0 {
153 self.block_base = self.blob_len;
154 self.coarse.push(self.blob_len);
155 }
156 let within = self.blob_len - self.block_base;
157 assert!(
158 within <= u64::from(u16::MAX),
159 "block starting at geometry edge {} spans {within} bytes, past the {} a u16 offset \
160 can address; a per-edge blob should be at most {} bytes",
161 self.stored - self.stored % INTERMEDIATE_BLOCK,
162 u16::MAX,
163 4 * (geom::MAX_POINTS - 2)
164 );
165 self.within.push(within as u16);
166 }
167
168 /// Append the sentinel entry and the whole trailer. Returns the finished
169 /// file's size.
170 fn finish(mut self, edge_count: u64) -> Result<u64> {
171 if self.pushed != edge_count {
172 return Err(Error(format!(
173 "{} describes {} edge(s), not the {edge_count} written",
174 self.path.display(),
175 self.pushed
176 )));
177 }
178 self.push_entry();
179 // `coarse` is sized by `div_ceil`, so when `G` is not a multiple of the
180 // block size it holds one slot past the last block the sentinel touched.
181 // Filling it keeps the table exactly the length the reader computes.
182 if self.stored % INTERMEDIATE_BLOCK != 0 {
183 self.coarse.push(self.blob_len);
184 }
185
186 // The presence bitmap and its rank index, the same pair `edges.bin`'s names
187 // use. The rank total is `G`, which is what lets the reader cross-check the
188 // two halves of the trailer against each other.
189 let total = self.present.write(&mut self.out)?;
190 debug_assert_eq!(total, self.stored, "the presence bitmap disagrees with G");
191 for c in &self.coarse {
192 self.out.write_all(&c.to_le_bytes()).map_err(io_err)?;
193 }
194 for w in &self.within {
195 self.out.write_all(&w.to_le_bytes()).map_err(io_err)?;
196 }
197 self.out.write_all(&self.stored.to_le_bytes()).map_err(io_err)?;
198 self.out.flush().map_err(io_err)?;
199
200 let want = self.blob_len + GeomFile::trailer_bytes(edge_count, self.stored);
201 let got = std::fs::metadata(&self.path)
202 .map_err(|e| Error(format!("cannot stat {}: {e}", self.path.display())))?
203 .len();
204 if got != want {
205 return Err(Error(format!(
206 "{} came out {got} byte(s) long, not the {want} the reader will compute",
207 self.path.display()
208 )));
209 }
210 Ok(want)
211 }
212}
213
214/// A presence bitmap over the directed edges, built in memory and written with a
215/// rank index in front of it.
216///
217/// The writer half of `graph.rs`'s `EdgeBitmap`, and an on-disk contract with it:
218///
219/// ```text
220/// [ u64 rank[E.div_ceil(512) + 1] ] set bits before each 64-byte block, total appended
221/// [ u8 present[E.div_ceil(8)] ] one bit per directed edge
222/// ```
223///
224/// Used twice, for the same reason the reader's is: `intermediate.bin`'s stored
225/// polylines and `edges.bin`'s names are both per-edge fields most edges do not have.
226struct PresenceBitmap {
227 bits: Vec<u8>,
228 /// Bits set so far, i.e. the length of the side table this indexes.
229 set: u64,
230}
231
232impl PresenceBitmap {
233 /// Byte size of the rank index plus the bitmap for `edge_count` edges. The reader
234 /// sizes them the same way.
235 fn bytes(edge_count: u64) -> u64 {
236 (edge_count.div_ceil(RANK_BLOCK_BITS) + 1) * 8 + edge_count.div_ceil(8)
237 }
238
239 fn new(edge_count: u64) -> PresenceBitmap {
240 PresenceBitmap {
241 bits: vec![0u8; edge_count.div_ceil(8) as usize],
242 set: 0,
243 }
244 }
245
246 /// Mark edge `idx` as having one. Must be called in ascending `idx`, which every
247 /// caller satisfies because the rounds ascend and each round writes its edges in
248 /// index order.
249 fn set(&mut self, idx: u64) {
250 debug_assert!(
251 self.bits[(idx / 8) as usize] & (1u8 << (idx % 8)) == 0,
252 "edge {idx} was already marked"
253 );
254 self.bits[(idx / 8) as usize] |= 1u8 << (idx % 8);
255 self.set += 1;
256 }
257
258 /// Write the rank index then the bitmap. Returns the number of set bits, which is
259 /// the rank index's appended total and the length the side table must have.
260 fn write<W: Write>(&self, out: &mut W) -> Result<u64> {
261 // Set bits before each block, with the total appended. That total is what
262 // lets the reader tie the index to the table it indexes.
263 let blocks = self.bits.len().div_ceil(RANK_BLOCK_BYTES);
264 let mut total = 0u64;
265 for b in 0..blocks {
266 out.write_all(&total.to_le_bytes()).map_err(io_err)?;
267 let start = b * RANK_BLOCK_BYTES;
268 let end = (start + RANK_BLOCK_BYTES).min(self.bits.len());
269 total += self.bits[start..end]
270 .iter()
271 .map(|byte| u64::from(byte.count_ones()))
272 .sum::<u64>();
273 }
274 out.write_all(&total.to_le_bytes()).map_err(io_err)?;
275 out.write_all(&self.bits).map_err(io_err)?;
276 debug_assert_eq!(total, self.set, "the bitmap disagrees with its own counter");
277 Ok(total)
278 }
279}
280
281/// `edges.bin`, in five sections (v7: the record array is blocked):
282///
283/// ```text
284/// [ ZBLK records[E] ] 7 B each, blocked zstd (see
285/// `tilecodec::blocked`); v6 is raw E*7
286/// [ pad to SECTION_ALIGN ]
287/// [ u32 escape_first[E.div_ceil(1024) + 1] ] first escape row of each block
288/// [ { u32 edge_idx, u32 target, u32 dist_mm } x escapes ] ascending by edge_idx
289/// [ pad to SECTION_ALIGN ]
290/// [ u64 name rank[E.div_ceil(512) + 1] ][ u8 name present[E.div_ceil(8)] ]
291/// [ u32 name_off[named_edges] ] indexed by rank in the bitmap
292/// ```
293///
294/// `target` is a signed delta from the edge's own source, which is affordable only
295/// because the nodes are sorted by a space-filling curve: 99.699% of California's
296/// deltas fit an `i16`. `dist_mm` is a `u24`, exact below 16.78 km, which is
297/// 99.999% of edges. Either field's sentinel means *both* come from one escape row,
298/// so the reader takes one branch and the table stays single.
299///
300/// `name_offset` is sparse rather than a field, because two thirds of edges have no
301/// name — 62.3% of California's, 68.9% of Europe's — and it is read when an
302/// instruction is emitted, never in the A* relaxation.
303///
304/// # Why the tables come last, and why they fit in memory
305///
306/// Neither the escape count nor the named-edge count is known until the final round
307/// has run, so a reserved prefix cannot be sized. The blocked record array is
308/// likewise data-dependent in length, so — unlike the v6 fixed stride — the
309/// reader cannot compute offsets from `metadata.bin`'s counts alone: it parses
310/// the ZBLK header for the records' end, then the escapes and names exactly as
311/// before. The escape rows accumulate in memory — 39 MB at planet scale against
312/// `edges.bin`'s 8.6 GB — as do the name offsets (1.6 GB, the largest of them)
313/// and the bitmap (134 MB).
314struct EdgeFile {
315 path: PathBuf,
316 /// Blocked record staging: 7 B records stream here (one block in memory,
317 /// frames to scratch), finished into the file head at [`EdgeFile::finish`].
318 blocked: ParBlocked,
319 /// `(edge_idx, target, dist_mm)` for the edges a record cannot hold, in
320 /// ascending `edge_idx` — which is the order they are pushed in, because the
321 /// rounds ascend and each round writes its edges in index order.
322 escapes: Vec<(u32, u32, u32)>,
323 /// Which edges have a name, and the pool offsets of the ones that do, in the
324 /// same order.
325 named: PresenceBitmap,
326 name_offsets: Vec<u32>,
327 /// Directed edges written so far, which is the index the next call describes.
328 pushed: u64,
329}
330
331impl EdgeFile {
332 /// Byte size of the whole file. Only the v6 fixed-stride layout is
333 /// computable from counts; the v7 blocked layout is data-dependent, so
334 /// this covers the trailer and the reader parses the records' end out of
335 /// the ZBLK header instead.
336 #[cfg(test)]
337 fn total_bytes(edge_count: u64, escapes: u64, named: u64) -> u64 {
338 let rows = align_up(edge_count * EDGE_REC_BYTES, SECTION_ALIGN)
339 + (edge_count.div_ceil(ESCAPE_BLOCK) + 1) * 4
340 + escapes * 12;
341 align_up(rows, SECTION_ALIGN) + PresenceBitmap::bytes(edge_count) + named * 4
342 }
343
344 fn create(dir: &Path, name: &str, edge_count: u64) -> Result<EdgeFile> {
345 let path = dir.join(name);
346 let scratch = dir.join(format!("{name}.blocked.tmp"));
347 Ok(EdgeFile {
348 blocked: ParBlocked::create(EDGE_REC_BYTES as usize, &scratch)
349 .map_err(|e| Error(format!("cannot stage {}: {e}", scratch.display())))?,
350 path,
351 escapes: Vec::new(),
352 named: PresenceBitmap::new(edge_count),
353 name_offsets: Vec::new(),
354 pushed: 0,
355 })
356 }
357
358 /// Write one directed edge's record, escaping it if either field will not fit and
359 /// recording its name if it has one.
360 #[cfg(test)]
361 fn push(&mut self, e: &TmpEdge, type_: u8) -> Result<()> {
362 let (delta, dist) = match target_delta(e.source, e.target) {
363 Some(d) if e.dist_mm < DIST_MM_ESCAPE => (d, e.dist_mm),
364 // Both sentinels, not just the one that failed: the reader tests either,
365 // so writing both keeps the two tests in agreement whichever field a
366 // future caller happens to have in hand.
367 _ => {
368 let idx = cap_u32("escaped edge index", self.pushed)?;
369 self.escapes.push((idx, e.target, e.dist_mm));
370 (TARGET_DELTA_ESCAPE, DIST_MM_ESCAPE)
371 }
372 };
373 let mut rec = [0u8; EDGE_REC_BYTES as usize];
374 rec[0..2].copy_from_slice(&delta.to_le_bytes());
375 rec[2..5].copy_from_slice(&dist.to_le_bytes()[..3]);
376 rec[5] = type_;
377 rec[6] = e.speed_limit;
378 self.blocked
379 .push(&rec)
380 .map_err(|e| Error(format!("cannot stage edge record: {e}")))?;
381 if e.name_offset != NO_NAME {
382 self.named.set(self.pushed);
383 self.name_offsets.push(e.name_offset);
384 }
385 self.pushed += 1;
386 Ok(())
387 }
388
389 /// Finish the blocked records into the file head, then pad and append the
390 /// block index, the escape rows, the name bitmap and the name offsets.
391 /// Returns the finished file's size.
392 fn finish(self, edge_count: u64) -> Result<u64> {
393 if self.pushed != edge_count {
394 return Err(Error(format!(
395 "{} holds {} edge(s), not the {edge_count} the pack is sized for",
396 self.path.display(),
397 self.pushed
398 )));
399 }
400 let EdgeFile { path, blocked, escapes, named, name_offsets, pushed: _ } = self;
401 // The record section streams straight into the file head; the sanity
402 // parse reads it back through a mapping once the file is complete.
403 let mut out = BufWriter::with_capacity(WRITE_BUF_BYTES, create(&path)?);
404 let mut at = blocked
405 .finish_into(&mut out)
406 .map_err(|e| Error(format!("cannot finish {}: {e}", path.display())))?;
407 at = pad_to(&mut out, at)?;
408
409 // `escape_first[b]` is the index of the first row in block `b`, i.e. the
410 // count of rows below `b * ESCAPE_BLOCK`. The rows ascend, so one walk over
411 // them fills the whole array, and the final entry is the row total — which is
412 // what lets the reader tie the index to the section it indexes.
413 let blocks = edge_count.div_ceil(ESCAPE_BLOCK) + 1;
414 let mut row = 0usize;
415 for b in 0..blocks {
416 let limit = b * ESCAPE_BLOCK;
417 while row < escapes.len() && u64::from(escapes[row].0) < limit {
418 row += 1;
419 }
420 out.write_all(&(row as u32).to_le_bytes()).map_err(io_err)?;
421 }
422 if row != escapes.len() {
423 return Err(Error(format!(
424 "{}: the block index reached row {row} of {}, so a row is past the \
425 last block",
426 path.display(),
427 escapes.len()
428 )));
429 }
430 at += blocks * 4;
431
432 for (idx, target, dist_mm) in &escapes {
433 out.write_all(&idx.to_le_bytes()).map_err(io_err)?;
434 out.write_all(&target.to_le_bytes()).map_err(io_err)?;
435 out.write_all(&dist_mm.to_le_bytes()).map_err(io_err)?;
436 }
437 at += escapes.len() as u64 * 12;
438 pad_to(&mut out, at)?;
439
440 let named = named.write(&mut out)?;
441 if named != name_offsets.len() as u64 {
442 return Err(Error(format!(
443 "{}: the name bitmap has {named} bit(s) set but {} offset(s) were \
444 collected",
445 path.display(),
446 name_offsets.len()
447 )));
448 }
449 for off in &name_offsets {
450 out.write_all(&off.to_le_bytes()).map_err(io_err)?;
451 }
452 out.flush().map_err(io_err)?;
453 drop(out);
454
455 // Sanity: the blocked section must unpack to exactly the pushed records.
456 let map = crate::mem::Mapped::open(&path).map_err(Error)?;
457 let parsed = tilecodec::blocked::Blocked::parse(&map).map_err(|e| {
458 Error(format!("freshly blocked {} does not parse: {e}", path.display()))
459 })?;
460 if parsed.unpacked_len() != edge_count * EDGE_REC_BYTES {
461 return Err(Error(format!(
462 "{} unpacks to {} byte(s), not {edge_count} 7-byte records",
463 path.display(),
464 parsed.unpacked_len()
465 )));
466 }
467 let got = map.len() as u64;
468 Ok(got)
469 }
470}
471
472/// Write zeroes up to the next section boundary, returning the new offset.
473///
474/// Free function (not a method): [`EdgeFile::finish`] destructures `self`
475/// before the trailer, so there is no receiver left to hang it on.
476fn pad_to(out: &mut BufWriter<File>, at: u64) -> Result<u64> {
477 let aligned = align_up(at, SECTION_ALIGN);
478 let zeroes = [0u8; SECTION_ALIGN as usize];
479 out.write_all(&zeroes[..(aligned - at) as usize]).map_err(io_err)?;
480 Ok(aligned)
481}