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

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

graph_build_part3_s1.rs389 lines · 16.3 KiBRaw
1/// Write the pack in `rounds` source-partitioned rounds.
2///
3/// # Why rounds, and not computed offsets
4///
5/// The obvious alternative is to compute each edge's index and `pwrite` it into
6/// place. That is sound for `edges.bin` — fixed 14-byte records in a pre-sized
7/// file — but wrong for the two blob files. The reader derives a polyline's length
8/// from the next offset entry and a lane run's from the next index entry, so
9/// `intermediate.bin` and `lanes.bin` are forced into edge-index order with
10/// monotonic offsets, and writing a blob at a computed offset would mean knowing
11/// every earlier blob's length first: a per-edge length array, a prefix sum and a
12/// second encode pass.
13///
14/// Partitioning by source instead makes every write an append. Each round takes a
15/// contiguous range of final node ids, scans the chain spill for the edges whose
16/// *source* falls in that range, sorts that buffer, and writes both blobs, the
17/// presence bitmap, the offset tables, `edges.bin` and `nodes.bin` sequentially.
18/// Offsets come out monotonic by construction, `nodes.bin`'s running edge counter
19/// works because the rounds ascend, and the `(source, target)` grouping the reader
20/// and [`twin_is_unique`] depend on is restored within each round.
21///
22/// The cost is `rounds` sequential reads of the spill instead of one.
23#[allow(clippy::too_many_arguments)]
24fn write_graph(
25 out_dir: &Path,
26 node_coords: &[geom::Pt],
27 spill: &chains::Spill,
28 lane_pool: &[u16],
29 csr: &Csr,
30 synth: &[Synth],
31 ids: &FinalIds,
32 rounds: u32,
33 dem: Option<&crate::dem::Dem>,
34 timer: &mut crate::timing::PhaseTimer,
35) -> Result<Written> {
36 let kept = node_coords.len() as u32;
37 let edge_count = csr.edge_count() + synth.len() as u64;
38 // `nodes.bin`'s `edge_ptr` is a `u32`, so an edge count past that ceiling would
39 // wrap and point a node at another node's edge range.
40 cap_u32("directed edge", edge_count)?;
41 println!("Writing {edge_count} edge(s) in {rounds} round(s)...");
42 let chain_total = spill.chain_count()?;
43
44 let mut nodes_blocked = ParBlocked::create(12, &out_dir.join("nodes.blocked.tmp"))
45 .map_err(|e| Error(format!("cannot stage nodes.bin: {e}")))?;
46 let mut edges_out = EdgeFile::create(out_dir, "edges.bin", edge_count)?;
47
48 // `intermediate.bin` puts its blob at offset 0 and everything that indexes it
49 // in a trailer, so it is written strictly forwards with no scratch file at all
50 // (see [`GeomFile`]). `lanes.bin` is sparse and so cannot size its index up
51 // front; its blob streams to scratch instead and the index is written in front
52 // of it.
53 let mut inter = GeomFile::create(out_dir, "intermediate.bin", edge_count)?;
54 let mut lanes = LaneFile::create(out_dir, "lanes.bin")?;
55
56 let mut buffer: Vec<TmpEdge> = Vec::new();
57 let points = spill.points()?;
58 let pmap = chains::points_map(&points);
59 let mut edge_ptr: u64 = 0;
60 let mut geometry_edges: u64 = 0;
61 let mut reversed_edges: u64 = 0;
62 let mut census = Census::default();
63 // One assignment scan instead of one scan per round: every chain's round
64 // is a pure function of its endpoints' final ids, so a single pass over
65 // the mapped headers records each chain's index per round and every round
66 // gathers only its chains. Chain order within a round is ascending index —
67 // the order the old per-round scan visited — so the buffer, the sort, and
68 // everything downstream are identical.
69 //
70 // Parallel: fixed contiguous chunks of chain indices, each producing its
71 // own per-round lists, concatenated in chunk order — so every list is still
72 // ascending and identical to the serial scan's.
73 timer.switch("write-scan");
74 let headers = spill.headers_mapped()?;
75 let chain_total_now = headers.len()?;
76 if chain_total_now != chain_total {
77 return Err(Error(format!(
78 "chains.hdr holds {chain_total_now} chain(s), expected {chain_total}"
79 )));
80 }
81 let round_lo = |round: u32| (u64::from(kept) * u64::from(round) / u64::from(rounds)) as u32;
82 let by_round: Vec<Vec<u32>> = {
83 let n_chunks = (chain_total as usize).div_ceil(SCAN_CHUNK);
84 let chunk_ids: Vec<usize> = (0..n_chunks).collect();
85 let parts: Vec<Result<Vec<Vec<u32>>>> = par::map_chunks(&chunk_ids, 1, |_, ch| {
86 let c0 = (ch[0] * SCAN_CHUNK) as u64;
87 let c1 = (c0 + SCAN_CHUNK as u64).min(chain_total);
88 let mut mine: Vec<Vec<u32>> = vec![Vec::new(); rounds as usize];
89 for ci in c0..c1 {
90 let c = headers.get(ci)?;
91 let (a, b) = (ids.get(c.first), ids.get(c.last));
92 // A chain enters a round when the old scan would have buffered an
93 // edge for it there: source endpoint in range, or (two-way) target
94 // endpoint in range. One entry per qualifying round — a chain whose
95 // endpoints straddle a boundary is gathered twice, once per round,
96 // exactly as the old scan buffered it twice.
97 for round in 0..rounds {
98 let (lo, hi) = (round_lo(round), round_lo(round + 1));
99 if (lo..hi).contains(&a) || (!c.oneway && (lo..hi).contains(&b)) {
100 mine[round as usize].push(ci as u32);
101 }
102 }
103 }
104 Ok(mine)
105 });
106 let mut by_round: Vec<Vec<u32>> = vec![Vec::new(); rounds as usize];
107 let mut sizes = vec![0usize; rounds as usize];
108 for p in parts.iter().filter_map(|p| p.as_ref().ok()) {
109 for (r, v) in p.iter().enumerate() {
110 sizes[r] += v.len();
111 }
112 }
113 for (r, v) in by_round.iter_mut().enumerate() {
114 v.reserve_exact(sizes[r]);
115 }
116 for p in parts {
117 for (r, v) in p?.into_iter().enumerate() {
118 by_round[r].extend_from_slice(&v);
119 }
120 }
121 by_round
122 };
123
124 for round in 0..rounds {
125 // Split by node count. Contiguous and ascending, so the four output streams
126 // stay append-only across the whole run.
127 let lo = round_lo(round);
128 let hi = round_lo(round + 1);
129 timer.switch("write-scan");
130
131 // Gather: this round's chains in ascending index order — the visit
132 // order of the old per-round scan. Parallel over fixed chunks of the
133 // round's list, concatenated in chunk order, so the buffer is the
134 // serial one element for element.
135 buffer.clear();
136 let gathered: Vec<Result<Vec<TmpEdge>>> =
137 par::map_chunks(&by_round[round as usize], SCAN_CHUNK, |_, chunk| {
138 let mut out = Vec::with_capacity(chunk.len() + chunk.len() / 2);
139 for &ci in chunk {
140 let c = headers.get(u64::from(ci))?;
141 let (a, b) = (ids.get(c.first), ids.get(c.last));
142 if (lo..hi).contains(&a) {
143 out.push(chain_edge(&c, ci, a, b, false));
144 }
145 if !c.oneway && (lo..hi).contains(&b) {
146 out.push(chain_edge(&c, ci, b, a, true));
147 }
148 }
149 Ok(out)
150 });
151 let synth_lo = synth.partition_point(|s| s.source < lo);
152 let synth_hi = synth.partition_point(|s| s.source < hi);
153 let gathered_len: usize = gathered.iter().map(|g| g.as_ref().map_or(0, Vec::len)).sum();
154 buffer.reserve_exact(gathered_len + (synth_hi - synth_lo));
155 for g in gathered {
156 buffer.extend_from_slice(&g?);
157 }
158 for s in &synth[synth_lo..synth_hi] {
159 buffer.push(TmpEdge {
160 source: s.source,
161 target: s.target,
162 dist_mm: s.dist_mm,
163 name_offset: NO_NAME,
164 type_: RECONNECT_TYPE,
165 speed_limit: RECONNECT_SPEED,
166 lane_off: NO_LANES,
167 lane_count: 0,
168 chain: NO_CHAIN,
169 chain_rev: false,
170 pts_start: 0,
171 pts_len: 0,
172 });
173 }
174
175 // The CSR already knows how many edges this range owns. Checking against it
176 // catches both an edge landing in the wrong round and an edge whose source
177 // is not a surviving node — which is what the old
178 // `assert_eq!(cursor, edges.len())` was for, now checked per round and
179 // before anything is written rather than after everything is.
180 let expected = csr.edge_ptr[hi as usize] - csr.edge_ptr[lo as usize]
181 + (synth_hi - synth_lo) as u64;
182 if buffer.len() as u64 != expected {
183 return Err(Error(format!(
184 "round {round} covering node(s) {lo}..{hi} collected {} edge(s), \
185 but the edge index says {expected}",
186 buffer.len()
187 )));
188 }
189
190 // Grouped by source for the reader, then by target so a node's parallel
191 // edges are adjacent, then by chain so the order is total.
192 //
193 // This was a STABLE sort on `(source, target, chain)` over a buffer built
194 // in chain order. The only elements that key leaves tied and that still
195 // differ are the two directions of a two-way self-loop chain — same
196 // source, target and chain — which the gather emits forward
197 // (`chain_rev == false`) first. Appending `chain_rev` to the key breaks
198 // exactly that tie the same way, and anything still tied is a
199 // byte-identical duplicate (a repeated connector), whose relative order
200 // cannot show. So the order is total over distinguishable elements and an
201 // UNSTABLE parallel in-place sort yields the stable sort's sequence — with
202 // no merge buffer, which at planet scale would be another 17 GB.
203 par::install(|| {
204 buffer.par_sort_unstable_by_key(|e| (e.source, e.target, e.chain, e.chain_rev))
205 });
206
207 // --- write-write: parallel bake, in-order drain ------------------------
208 timer.switch("write-write");
209 write_round(
210 &buffer,
211 lo,
212 hi,
213 edge_ptr,
214 node_coords,
215 lane_pool,
216 csr,
217 synth,
218 pmap,
219 &mut WriteSinks {
220 nodes: &mut nodes_blocked,
221 edges: &mut edges_out,
222 inter: &mut inter,
223 lanes: &mut lanes,
224 census: &mut census,
225 geometry_edges: &mut geometry_edges,
226 reversed_edges: &mut reversed_edges,
227 },
228 round,
229 rounds,
230 )?;
231 edge_ptr += buffer.len() as u64;
232 }
233 drop(buffer);
234
235 if edge_ptr != edge_count {
236 return Err(Error(format!(
237 "wrote {edge_ptr} edge(s) into a file sized for {edge_count}"
238 )));
239 }
240 finish_pack(
241 out_dir,
242 kept,
243 edge_count,
244 edge_ptr,
245 geometry_edges,
246 reversed_edges,
247 nodes_blocked,
248 edges_out,
249 inter,
250 lanes,
251 census,
252 node_coords,
253 dem,
254 )
255}
256
257/// Finish the four output streams and the metadata: the tail of `write_graph`
258/// after the last round drains. Unchanged from the serial loop — the drain
259/// above stages identical bytes, so everything downstream (sentinel, sanity
260/// parses, metadata, elevation) is untouched.
261#[allow(clippy::too_many_arguments)]
262fn finish_pack(
263 out_dir: &Path,
264 kept: u32,
265 edge_count: u64,
266 edge_ptr: u64,
267 geometry_edges: u64,
268 reversed_edges: u64,
269 nodes_blocked: ParBlocked,
270 edges_out: EdgeFile,
271 inter: GeomFile,
272 lanes: LaneFile,
273 census: Census,
274 node_coords: &[geom::Pt],
275 dem: Option<&crate::dem::Dem>,
276) -> Result<Written> {
277 let mut nodes_blocked = nodes_blocked;
278 // Trailing sentinel so `graph.rs` can read node(v + 1).edge_ptr as the end of
279 // node v's edge range.
280 let mut sentinel = [0u8; 12];
281 sentinel[8..12].copy_from_slice(&(edge_ptr as u32).to_le_bytes());
282 nodes_blocked
283 .push(&sentinel)
284 .map_err(|e| Error(format!("cannot stage node sentinel: {e}")))?;
285 // Streamed straight into the file (no in-memory copy of the section),
286 // then checked against the mapped result.
287 {
288 let mut out = BufWriter::with_capacity(WRITE_BUF_BYTES, create(&out_dir.join("nodes.bin"))?);
289 nodes_blocked
290 .finish_into(&mut out)
291 .map_err(|e| Error(format!("cannot finish nodes.bin: {e}")))?;
292 out.flush().map_err(io_err)?;
293 }
294 let nodes_map = crate::mem::Mapped::open(&out_dir.join("nodes.bin")).map_err(Error)?;
295 // Sanity: the blocked section must unpack to exactly the pushed records.
296 let parsed = tilecodec::blocked::Blocked::parse(&nodes_map).map_err(|e| {
297 Error(format!(
298 "freshly blocked nodes.bin does not parse: {e}"
299 ))
300 })?;
301 // Sanity: the blocked section must unpack to exactly the pushed records.
302 if parsed.unpacked_len() != (u64::from(kept) + 1) * 12 {
303 return Err(Error(format!(
304 "nodes.bin unpacks to {} byte(s) ({} 12-byte record(s)), not the {} record(s) \
305 pushed ({} byte(s))",
306 parsed.unpacked_len(),
307 parsed.unpacked_len() / 12,
308 u64::from(kept) + 1,
309 (u64::from(kept) + 1) * 12
310 )));
311 }
312 drop(nodes_map);
313 let escape_count = edges_out.escapes.len() as u64;
314 let named_edges = edges_out.name_offsets.len() as u64;
315 let edges_bytes = edges_out.finish(edge_count)?;
316 let intermediate_bytes = inter.finish(edge_count)?;
317 lanes.finish()?;
318 finish_pack_tail(
319 out_dir,
320 kept,
321 edge_count,
322 escape_count,
323 named_edges,
324 node_coords,
325 dem,
326 )?;
327 Ok(Written {
328 edge_count,
329 geometry_edges,
330 reversed_edges,
331 intermediate_bytes,
332 edges_bytes,
333 escape_count,
334 named_edges,
335 census,
336 })
337}
338
339/// Metadata + elevation tail of `write_graph`, after every stream finishes.
340/// Split out so the round loop above reads as plan/bake/drain without the
341/// file-assembly tail inline. Byte-identical: moved whole, order untouched.
342#[allow(clippy::too_many_arguments)]
343fn finish_pack_tail(
344 out_dir: &Path,
345 kept: u32,
346 edge_count: u64,
347 escape_count: u64,
348 named_edges: u64,
349 node_coords: &[geom::Pt],
350 dem: Option<&crate::dem::Dem>,
351) -> Result<()> {
352 // metadata.bin's magic + version let the device refuse a pack directory
353 // holding files from two different vintages instead of misreading it, and its
354 // counts are what every other file's length is validated against.
355 let mut meta = create(&out_dir.join("metadata.bin"))?;
356 meta.write_all(&GRAPH_MAGIC.to_le_bytes()).map_err(io_err)?;
357 meta.write_all(&GRAPH_VERSION.to_le_bytes()).map_err(io_err)?;
358 meta.write_all(&u64::from(kept).to_le_bytes()).map_err(io_err)?;
359 meta.write_all(&edge_count.to_le_bytes()).map_err(io_err)?;
360 meta.write_all(&escape_count.to_le_bytes()).map_err(io_err)?;
361 meta.write_all(&named_edges.to_le_bytes()).map_err(io_err)?;
362 meta.flush().map_err(io_err)?;
363 // elevation.bin: `i16[node_count]` metres, one per node in final-id order — an OPTIONAL sidecar
364 // like road_names.bin/lanes.bin, so a build without a DEM simply omits it and the device reads
365 // every node's elevation as 0. `node_coords` is already indexed by final node id, so a single
366 // forward pass matches the order `nodes.bin` was written in. Blocked like
367 // nodes/edges under the v7 layout (magic-dispatched on read, so absence
368 // still reads as all-zero).
369 if let Some(dem) = dem {
370 let mut elev_blocked = tilecodec::blocked::BlockedStreamWriter::create(
371 2,
372 &out_dir.join("elevation.blocked.tmp"),
373 )
374 .map_err(|e| Error(format!("cannot stage elevation.bin: {e}")))?;
375 for &(lat_e7, lon_e7) in node_coords {
376 let lat = f64::from(lat_e7) * 1e-7;
377 let lon = f64::from(lon_e7) * 1e-7;
378 let metres = dem.sample_metres(lon, lat).unwrap_or(0);
379 elev_blocked
380 .push(&metres.to_le_bytes())
381 .map_err(|e| Error(format!("cannot stage elevation record: {e}")))?;
382 }
383 let elev_bytes = elev_blocked
384 .finish()
385 .map_err(|e| Error(format!("cannot finish elevation.bin: {e}")))?;
386 std::fs::write(out_dir.join("elevation.bin"), &elev_bytes).map_err(io_err)?;
387 }
388 Ok(())
389}