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

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

graph_build_part4.rs475 lines · 19.6 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 out: BufWriter::new(create(&path)?),
112 path,
113 blob_len: 0,
114 present: PresenceBitmap::new(edge_count),
115 coarse: Vec::new(),
116 within: Vec::new(),
117 block_base: 0,
118 pushed: 0,
119 stored: 0,
120 })
121 }
122
123 /// This edge stores no polyline. Its presence bit stays clear and it owns no
124 /// offset at all, which is the whole point of the bitmap.
125 fn skip(&mut self) {
126 self.pushed += 1;
127 }
128
129 /// Record `bytes` as this edge's polyline. Called once per storing edge, in
130 /// ascending edge index, because the rounds ascend and each round writes its
131 /// edges in index order.
132 fn store(&mut self, bytes: &[u8]) -> Result<()> {
133 debug_assert!(
134 !bytes.is_empty(),
135 "an interior-only blob of no bytes is the chord, which needs no presence bit"
136 );
137 self.present.set(self.pushed);
138 self.push_entry();
139 self.out.write_all(bytes).map_err(io_err)?;
140 self.blob_len += bytes.len() as u64;
141 self.stored += 1;
142 self.pushed += 1;
143 Ok(())
144 }
145
146 /// One `(coarse?, within)` pair for geometry index `self.stored`.
147 fn push_entry(&mut self) {
148 if self.stored.is_multiple_of(INTERMEDIATE_BLOCK) {
149 self.block_base = self.blob_len;
150 self.coarse.push(self.blob_len);
151 }
152 let within = self.blob_len - self.block_base;
153 assert!(
154 within <= u64::from(u16::MAX),
155 "block starting at geometry edge {} spans {within} bytes, past the {} a u16 offset \
156 can address; a per-edge blob should be at most {} bytes",
157 self.stored - self.stored % INTERMEDIATE_BLOCK,
158 u16::MAX,
159 4 * (geom::MAX_POINTS - 2)
160 );
161 self.within.push(within as u16);
162 }
163
164 /// Append the sentinel entry and the whole trailer. Returns the finished
165 /// file's size.
166 fn finish(mut self, edge_count: u64) -> Result<u64> {
167 if self.pushed != edge_count {
168 return Err(Error(format!(
169 "{} describes {} edge(s), not the {edge_count} written",
170 self.path.display(),
171 self.pushed
172 )));
173 }
174 self.push_entry();
175 // `coarse` is sized by `div_ceil`, so when `G` is not a multiple of the
176 // block size it holds one slot past the last block the sentinel touched.
177 // Filling it keeps the table exactly the length the reader computes.
178 if !self.stored.is_multiple_of(INTERMEDIATE_BLOCK) {
179 self.coarse.push(self.blob_len);
180 }
181
182 // The presence bitmap and its rank index, the same pair `edges.bin`'s names
183 // use. The rank total is `G`, which is what lets the reader cross-check the
184 // two halves of the trailer against each other.
185 let total = self.present.write(&mut self.out)?;
186 debug_assert_eq!(total, self.stored, "the presence bitmap disagrees with G");
187 for c in &self.coarse {
188 self.out.write_all(&c.to_le_bytes()).map_err(io_err)?;
189 }
190 for w in &self.within {
191 self.out.write_all(&w.to_le_bytes()).map_err(io_err)?;
192 }
193 self.out.write_all(&self.stored.to_le_bytes()).map_err(io_err)?;
194 self.out.flush().map_err(io_err)?;
195
196 let want = self.blob_len + GeomFile::trailer_bytes(edge_count, self.stored);
197 let got = std::fs::metadata(&self.path)
198 .map_err(|e| Error(format!("cannot stat {}: {e}", self.path.display())))?
199 .len();
200 if got != want {
201 return Err(Error(format!(
202 "{} came out {got} byte(s) long, not the {want} the reader will compute",
203 self.path.display()
204 )));
205 }
206 Ok(want)
207 }
208}
209
210/// A presence bitmap over the directed edges, built in memory and written with a
211/// rank index in front of it.
212///
213/// The writer half of `graph.rs`'s `EdgeBitmap`, and an on-disk contract with it:
214///
215/// ```text
216/// [ u64 rank[E.div_ceil(512) + 1] ] set bits before each 64-byte block, total appended
217/// [ u8 present[E.div_ceil(8)] ] one bit per directed edge
218/// ```
219///
220/// Used twice, for the same reason the reader's is: `intermediate.bin`'s stored
221/// polylines and `edges.bin`'s names are both per-edge fields most edges do not have.
222struct PresenceBitmap {
223 bits: Vec<u8>,
224 /// Bits set so far, i.e. the length of the side table this indexes.
225 set: u64,
226}
227
228impl PresenceBitmap {
229 /// Byte size of the rank index plus the bitmap for `edge_count` edges. The reader
230 /// sizes them the same way.
231 fn bytes(edge_count: u64) -> u64 {
232 (edge_count.div_ceil(RANK_BLOCK_BITS) + 1) * 8 + edge_count.div_ceil(8)
233 }
234
235 fn new(edge_count: u64) -> PresenceBitmap {
236 PresenceBitmap {
237 bits: vec![0u8; edge_count.div_ceil(8) as usize],
238 set: 0,
239 }
240 }
241
242 /// Mark edge `idx` as having one. Must be called in ascending `idx`, which every
243 /// caller satisfies because the rounds ascend and each round writes its edges in
244 /// index order.
245 fn set(&mut self, idx: u64) {
246 debug_assert!(
247 self.bits[(idx / 8) as usize] & (1u8 << (idx % 8)) == 0,
248 "edge {idx} was already marked"
249 );
250 self.bits[(idx / 8) as usize] |= 1u8 << (idx % 8);
251 self.set += 1;
252 }
253
254 /// Write the rank index then the bitmap. Returns the number of set bits, which is
255 /// the rank index's appended total and the length the side table must have.
256 fn write<W: Write>(&self, out: &mut W) -> Result<u64> {
257 // Set bits before each block, with the total appended. That total is what
258 // lets the reader tie the index to the table it indexes.
259 let blocks = self.bits.len().div_ceil(RANK_BLOCK_BYTES);
260 let mut total = 0u64;
261 for b in 0..blocks {
262 out.write_all(&total.to_le_bytes()).map_err(io_err)?;
263 let start = b * RANK_BLOCK_BYTES;
264 let end = (start + RANK_BLOCK_BYTES).min(self.bits.len());
265 total += self.bits[start..end]
266 .iter()
267 .map(|byte| u64::from(byte.count_ones()))
268 .sum::<u64>();
269 }
270 out.write_all(&total.to_le_bytes()).map_err(io_err)?;
271 out.write_all(&self.bits).map_err(io_err)?;
272 debug_assert_eq!(total, self.set, "the bitmap disagrees with its own counter");
273 Ok(total)
274 }
275}
276
277/// `edges.bin`, in five sections (v7: the record array is blocked):
278///
279/// ```text
280/// [ ZBLK records[E] ] 7 B each, blocked zstd (see
281/// `tilecodec::blocked`); v6 is raw E*7
282/// [ pad to SECTION_ALIGN ]
283/// [ u32 escape_first[E.div_ceil(1024) + 1] ] first escape row of each block
284/// [ { u32 edge_idx, u32 target, u32 dist_mm } x escapes ] ascending by edge_idx
285/// [ pad to SECTION_ALIGN ]
286/// [ u64 name rank[E.div_ceil(512) + 1] ][ u8 name present[E.div_ceil(8)] ]
287/// [ u32 name_off[named_edges] ] indexed by rank in the bitmap
288/// ```
289///
290/// `target` is a signed delta from the edge's own source, which is affordable only
291/// because the nodes are sorted by a space-filling curve: 99.699% of California's
292/// deltas fit an `i16`. `dist_mm` is a `u24`, exact below 16.78 km, which is
293/// 99.999% of edges. Either field's sentinel means *both* come from one escape row,
294/// so the reader takes one branch and the table stays single.
295///
296/// `name_offset` is sparse rather than a field, because two thirds of edges have no
297/// name — 62.3% of California's, 68.9% of Europe's — and it is read when an
298/// instruction is emitted, never in the A* relaxation.
299///
300/// # Why the tables come last, and why they fit in memory
301///
302/// Neither the escape count nor the named-edge count is known until the final round
303/// has run, so a reserved prefix cannot be sized. The blocked record array is
304/// likewise data-dependent in length, so — unlike the v6 fixed stride — the
305/// reader cannot compute offsets from `metadata.bin`'s counts alone: it parses
306/// the ZBLK header for the records' end, then the escapes and names exactly as
307/// before. The escape rows accumulate in memory — 39 MB at planet scale against
308/// `edges.bin`'s 8.6 GB — as do the name offsets (1.6 GB, the largest of them)
309/// and the bitmap (134 MB).
310struct EdgeFile {
311 path: PathBuf,
312 /// Blocked record staging: 7 B records stream here (one block in memory,
313 /// frames to scratch), finished into the file head at [`EdgeFile::finish`].
314 blocked: tilecodec::blocked::BlockedStreamWriter,
315 /// `(edge_idx, target, dist_mm)` for the edges a record cannot hold, in
316 /// ascending `edge_idx` — which is the order they are pushed in, because the
317 /// rounds ascend and each round writes its edges in index order.
318 escapes: Vec<(u32, u32, u32)>,
319 /// Which edges have a name, and the pool offsets of the ones that do, in the
320 /// same order.
321 named: PresenceBitmap,
322 name_offsets: Vec<u32>,
323 /// Directed edges written so far, which is the index the next call describes.
324 pushed: u64,
325}
326
327impl EdgeFile {
328 /// Byte size of the whole file. Only the v6 fixed-stride layout is
329 /// computable from counts; the v7 blocked layout is data-dependent, so
330 /// this covers the trailer and the reader parses the records' end out of
331 /// the ZBLK header instead.
332 fn total_bytes(edge_count: u64, escapes: u64, named: u64) -> u64 {
333 let rows = align_up(edge_count * EDGE_REC_BYTES, SECTION_ALIGN)
334 + (edge_count.div_ceil(ESCAPE_BLOCK) + 1) * 4
335 + escapes * 12;
336 align_up(rows, SECTION_ALIGN) + PresenceBitmap::bytes(edge_count) + named * 4
337 }
338
339 fn create(dir: &Path, name: &str, edge_count: u64) -> Result<EdgeFile> {
340 let path = dir.join(name);
341 let scratch = dir.join(format!("{name}.blocked.tmp"));
342 Ok(EdgeFile {
343 blocked: tilecodec::blocked::BlockedStreamWriter::create(EDGE_REC_BYTES as usize, &scratch)
344 .map_err(|e| Error(format!("cannot stage {}: {e}", scratch.display())))?,
345 path,
346 escapes: Vec::new(),
347 named: PresenceBitmap::new(edge_count),
348 name_offsets: Vec::new(),
349 pushed: 0,
350 })
351 }
352
353 /// Write one directed edge's record, escaping it if either field will not fit and
354 /// recording its name if it has one.
355 fn push(&mut self, e: &TmpEdge, type_: u8) -> Result<()> {
356 let (delta, dist) = match target_delta(e.source, e.target) {
357 Some(d) if e.dist_mm < DIST_MM_ESCAPE => (d, e.dist_mm),
358 // Both sentinels, not just the one that failed: the reader tests either,
359 // so writing both keeps the two tests in agreement whichever field a
360 // future caller happens to have in hand.
361 _ => {
362 let idx = cap_u32("escaped edge index", self.pushed)?;
363 self.escapes.push((idx, e.target, e.dist_mm));
364 (TARGET_DELTA_ESCAPE, DIST_MM_ESCAPE)
365 }
366 };
367 let mut rec = [0u8; EDGE_REC_BYTES as usize];
368 rec[0..2].copy_from_slice(&delta.to_le_bytes());
369 rec[2..5].copy_from_slice(&dist.to_le_bytes()[..3]);
370 rec[5] = type_;
371 rec[6] = e.speed_limit;
372 self.blocked
373 .push(&rec)
374 .map_err(|e| Error(format!("cannot stage edge record: {e}")))?;
375 if e.name_offset != NO_NAME {
376 self.named.set(self.pushed);
377 self.name_offsets.push(e.name_offset);
378 }
379 self.pushed += 1;
380 Ok(())
381 }
382
383 /// Finish the blocked records into the file head, then pad and append the
384 /// block index, the escape rows, the name bitmap and the name offsets.
385 /// Returns the finished file's size.
386 fn finish(self, edge_count: u64) -> Result<u64> {
387 if self.pushed != edge_count {
388 return Err(Error(format!(
389 "{} holds {} edge(s), not the {edge_count} the pack is sized for",
390 self.path.display(),
391 self.pushed
392 )));
393 }
394 let EdgeFile { path, blocked, escapes, named, name_offsets, pushed: _ } = self;
395 let records = blocked
396 .finish()
397 .map_err(|e| Error(format!("cannot finish {}: {e}", path.display())))?;
398 // Sanity: the blocked section must unpack to exactly the pushed records.
399 let parsed = tilecodec::blocked::Blocked::parse(&records).map_err(|e| {
400 Error(format!("freshly blocked {} does not parse: {e}", path.display()))
401 })?;
402 if parsed.unpacked_len() != edge_count * EDGE_REC_BYTES {
403 return Err(Error(format!(
404 "{} unpacks to {} byte(s), not {edge_count} 7-byte records",
405 path.display(),
406 parsed.unpacked_len()
407 )));
408 }
409 let mut out = BufWriter::new(create(&path)?);
410 out.write_all(&records).map_err(io_err)?;
411 let mut at = records.len() as u64;
412 at = pad_to(&mut out, &path, at)?;
413
414 // `escape_first[b]` is the index of the first row in block `b`, i.e. the
415 // count of rows below `b * ESCAPE_BLOCK`. The rows ascend, so one walk over
416 // them fills the whole array, and the final entry is the row total — which is
417 // what lets the reader tie the index to the section it indexes.
418 let blocks = edge_count.div_ceil(ESCAPE_BLOCK) + 1;
419 let mut row = 0usize;
420 for b in 0..blocks {
421 let limit = b * ESCAPE_BLOCK;
422 while row < escapes.len() && u64::from(escapes[row].0) < limit {
423 row += 1;
424 }
425 out.write_all(&(row as u32).to_le_bytes()).map_err(io_err)?;
426 }
427 if row != escapes.len() {
428 return Err(Error(format!(
429 "{}: the block index reached row {row} of {}, so a row is past the \
430 last block",
431 path.display(),
432 escapes.len()
433 )));
434 }
435 at += blocks * 4;
436
437 for (idx, target, dist_mm) in &escapes {
438 out.write_all(&idx.to_le_bytes()).map_err(io_err)?;
439 out.write_all(&target.to_le_bytes()).map_err(io_err)?;
440 out.write_all(&dist_mm.to_le_bytes()).map_err(io_err)?;
441 }
442 at += escapes.len() as u64 * 12;
443 at = pad_to(&mut out, &path, at)?;
444
445 let named = named.write(&mut out)?;
446 if named != name_offsets.len() as u64 {
447 return Err(Error(format!(
448 "{}: the name bitmap has {named} bit(s) set but {} offset(s) were \
449 collected",
450 path.display(),
451 name_offsets.len()
452 )));
453 }
454 for off in &name_offsets {
455 out.write_all(&off.to_le_bytes()).map_err(io_err)?;
456 }
457 out.flush().map_err(io_err)?;
458
459 let got = std::fs::metadata(&path)
460 .map_err(|e| Error(format!("cannot stat {}: {e}", path.display())))?
461 .len();
462 Ok(got)
463 }
464}
465
466/// Write zeroes up to the next section boundary, returning the new offset.
467///
468/// Free function (not a method): [`EdgeFile::finish`] destructures `self`
469/// before the trailer, so there is no receiver left to hang it on.
470fn pad_to(out: &mut BufWriter<File>, path: &Path, at: u64) -> Result<u64> {
471 let aligned = align_up(at, SECTION_ALIGN);
472 let zeroes = [0u8; SECTION_ALIGN as usize];
473 out.write_all(&zeroes[..(aligned - at) as usize]).map_err(io_err)?;
474 Ok(aligned)
475}