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

Modern-Apps.git / scripts / maps / mamaps_build / src / store_part3.rs

store_part3.rs518 lines · 24.7 KiBRaw
1/// Consecutive chunks one lane claims at a time.
2///
3/// **One, because dealing longer runs was tried and measured as nothing.** The reasoning for runs is
4/// good and the measurement does not support it: single-chunk round-robin means each of sixteen
5/// lanes walks the file in ~9 KB hops sixteen chunks apart, which is the pattern readahead exists to
6/// defeat, and the spill was moving at 643 MB/s on hardware that does several gigabytes. Dealing
7/// runs of 64 consecutive chunks — ~600 KB, a streaming read — changed north-america tiling from
8/// 807.0 s to 813.1 s and the reader from 292.6 s to 298.4 s. Noise, and slightly the wrong way.
9///
10/// So the reads were never the problem, and the throughput figure was measuring something else: the
11/// reader was not waiting on disk, it was busy discarding features (see [`ZoomReader::spawn`]). Kept
12/// as a named constant of 1 rather than deleted, because the shape of the partition is worth being
13/// explicit about and because the next person to look at a 643 MB/s number will have the same idea.
14const PREFETCH_RUN: usize = 1;
15
16/// Chunks one lane may run ahead by.
17///
18/// Bounds the prefetch at `prefetch_lanes() * (PREFETCH_DEPTH + 1) * 64` features — about 34 K at
19/// constants above, which is small against the 512 Ki *vertices* the tiler batches immediately
20/// downstream. Depth is here to absorb a slow chunk, not to buffer.
21const PREFETCH_DEPTH: usize = 32;
22
23/// Reads the chunks one zoom needs and seeks past the rest.
24pub struct ZoomReader {
25 /// One receiver per lane. Wanted-chunk `k` is decoded by lane `(k / PREFETCH_RUN) % lanes.len()`,
26 /// so walking the lanes a run at a time reproduces file order exactly. Empty when there is
27 /// nothing to read.
28 lanes: Vec<std::sync::mpsc::Receiver<Decoded>>,
29 /// Joined on drop, after the receivers are dropped: a lane blocked on a full channel exits when
30 /// its receiver goes, so the order of those two steps is what makes the join finite.
31 lanes_running: Vec<std::thread::JoinHandle<()>>,
32 /// Chunks taken so far, which is also what decides the lane to take the next one from.
33 at: usize,
34 total: usize,
35 records: Vec<Feature>,
36}
37
38impl Drop for ZoomReader {
39 fn drop(&mut self) {
40 // Receivers first. A lane parked on `send` to a full channel wakes with an error the moment
41 // its receiver is gone, and only then is the join below guaranteed to finish -- which
42 // matters on the error path, where the tiler abandons a zoom with every lane backed up.
43 self.lanes.clear();
44 for lane in self.lanes_running.drain(..) {
45 let _ = lane.join();
46 }
47 }
48}
49
50impl ZoomReader {
51 /// Start a lane per [`prefetch_lanes`] over `wanted`, dealt round-robin.
52 ///
53 /// # Why dedicated threads and not the pool
54 ///
55 /// This decode is 62.6 s of a 175 s us-west build, all of it on one thread, and
56 /// [`NormalizedChunks::read_into`] is an obvious candidate for the pool: it takes `&self`, reads
57 /// its own byte range positionally, and is pure. Decoding 512 chunks at a time across the pool
58 /// was tried and made the map phase **62% slower** — 102.4 s to 165.5 s — for byte-identical
59 /// output.
60 ///
61 /// The reason is what this reader is: it feeds the clipping workers through a channel. Handing
62 /// the refill to the same pool queues it *behind* the clipping tasks it exists to supply, so the
63 /// reader blocks waiting on a pool that is busy with work only the reader can extend. The
64 /// overlap between reading and clipping — the entire point of the arrangement — disappears, and
65 /// both halves get slower.
66 ///
67 /// So: threads of their own, outside the pool, which is what [`crate::tiler`] does for the
68 /// reader itself and for the same reason.
69 ///
70 /// # Why the lanes drop features rather than hand them over
71 ///
72 /// A feature below `z`'s own floor is dropped **here**, and that is not tidiness — it is most of
73 /// what this reader costs. The chunk index skips a chunk only when *every* feature in it is too
74 /// deep, and a chunk is 64 features in file order with no relationship between their
75 /// `min_zoom`s, so at a shallow zoom nearly every chunk survives the index while holding almost
76 /// nothing that zoom draws. z5 of north-america reads 590,002 chunks — 37.8 M features — to
77 /// produce 156 tiles.
78 ///
79 /// Left to the consumer, as it was, that is roughly **1.06 billion features across the build**
80 /// pulled one `next()` at a time and then discarded. No lane count fixes it, because it is not
81 /// the lanes' work: raising lanes from 4 to 16 took the reader 496.8 s to 292.6 s and then
82 /// stopped, and dealing sequential runs instead of strided chunks changed nothing at all. The
83 /// filter is per-feature and order-preserving, so moving it up here removes exactly the features
84 /// the tiler removed, in a place where sixteen threads share the cost.
85 ///
86 /// # Why the order cannot move
87 ///
88 /// Lane `j` takes wanted-chunks `j`, `j + n`, `j + 2n`, ... and a lane's own channel is FIFO, so
89 /// the `k`th chunk out of lane `k % n` is wanted-chunk `k`. Reading the lanes round-robin is
90 /// therefore the wanted list in order, which is the file in order, which is what the archive's
91 /// feature ordering rests on. Nothing here depends on which lane finishes first; a lane that
92 /// races ahead fills its channel and parks.
93 fn spawn(inner: NormalizedChunks, wanted: Vec<usize>, z: u8) -> Result<ZoomReader> {
94 let total = wanted.len();
95 if total == 0 {
96 return Ok(ZoomReader {
97 lanes: Vec::new(),
98 lanes_running: Vec::new(),
99 at: 0,
100 total: 0,
101 records: Vec::new(),
102 });
103 }
104 // One handle shared rather than one file open per lane: `read_into` is positional and
105 // documented to serve every thread from one handle.
106 let inner = std::sync::Arc::new(inner);
107 // No more lanes than there are runs to deal, or the tail lanes are threads started to do
108 // nothing.
109 let count = prefetch_lanes().min(total.div_ceil(PREFETCH_RUN));
110 let mut lanes = Vec::with_capacity(count);
111 let mut lanes_running = Vec::with_capacity(count);
112 for lane in 0..count {
113 let (send, receive) = std::sync::mpsc::sync_channel::<Decoded>(PREFETCH_DEPTH);
114 let inner = std::sync::Arc::clone(&inner);
115 // This lane's runs, flattened back into the chunks it will read: sequential within a
116 // run, which is the whole point of dealing runs rather than chunks.
117 let mine: Vec<usize> = wanted
118 .chunks(PREFETCH_RUN)
119 .skip(lane)
120 .step_by(count)
121 .flatten()
122 .copied()
123 .collect();
124 let running = std::thread::Builder::new()
125 .name(format!("mamaps-spill-{lane}"))
126 .spawn(move || {
127 // One byte buffer and one record buffer for the lane, reused across its
128 // chunks. What is sent is a third `Vec`, allocated per chunk -- one allocation
129 // per 64 features, against the per-feature geometry the decode allocates
130 // anyway.
131 let mut scratch = Vec::new();
132 let mut records = Vec::new();
133 for chunk in mine {
134 let decoded = inner
135 .read_into(chunk, &mut scratch, &mut records)
136 .map_err(|e| osm_ingest::proto::Error(e.to_string()))
137 // Reversed here rather than by the consumer, which takes from the
138 // back: same reason as everything else in this closure, it is work and
139 // it does not have to be the reader's.
140 .and_then(|()| {
141 let mut out = Vec::with_capacity(records.len());
142 for record in records.drain(..).rev() {
143 let feature = feature_of(record)?;
144 // The zoom window, applied where the work is spread. See this
145 // function's docs: at a shallow zoom this is nearly the whole
146 // Floor is the feature's own `min_zoom`; ceiling is the
147 // layer cap (`MAX_ZOOM_PER_LAYER`) — boundaries stop at
148 // z13, everything else tiles to the archive max.
149 if z >= feature.class.min_zoom
150 && z <= crate::schema::max_zoom_for_layer(feature.class.layer)
151 {
152 out.push(feature);
153 }
154 }
155 Ok(out)
156 });
157 // Stop on the first error: the consumer surfaces it and abandons the zoom,
158 // and carrying on would only queue work behind a build that is already
159 // failing.
160 let stop = decoded.is_err();
161 if send.send(decoded).is_err() || stop {
162 return;
163 }
164 }
165 })
166 .map_err(|e| {
167 osm_ingest::proto::Error(format!("cannot start spill prefetch lane {lane}: {e}"))
168 })?;
169 lanes.push(receive);
170 lanes_running.push(running);
171 }
172 Ok(ZoomReader { lanes, lanes_running, at: 0, total, records: Vec::new() })
173 }
174
175 /// How many spill chunks this zoom will read, and how many it has.
176 ///
177 /// Exposed so the tiler can show progress: the map phase is the longest in the build and was
178 /// silent for all of it, which on a continent is forty minutes of no output at all.
179 pub fn chunks(&self) -> (usize, usize) {
180 (self.at.min(self.total), self.total)
181 }
182
183 /// The next feature, or `None` once this zoom's chunks are exhausted.
184 pub fn next(&mut self) -> Result<Option<Feature>> {
185 loop {
186 // From the back, which is why the lane reversed the chunk before sending it.
187 if let Some(feature) = self.records.pop() {
188 return Ok(Some(feature));
189 }
190 if self.at >= self.total {
191 return Ok(None);
192 }
193 let lane = self.at % self.lanes.len();
194 self.at += 1;
195 // A lane that hung up before delivering all of its chunks panicked: it returns only
196 // after sending every one of them or after sending an error, and an error arrives as a
197 // value rather than a hangup.
198 let decoded = self.lanes[lane].recv().map_err(|_| {
199 osm_ingest::proto::Error(format!("spill prefetch lane {lane} stopped early"))
200 })?;
201 self.records = decoded?;
202 }
203 }
204}
205
206#[cfg_attr(not(test), allow(dead_code))]
207pub struct Reader {
208 inner: NormalizedReader,
209}
210
211impl Reader {
212 /// The next feature, or `None` at the end of the file.
213 ///
214 /// A record whose class property is missing or is not an integer is a corrupt file rather than a
215 /// feature to skip: everything in here was written by [`Sink::push`] one run ago, so anything
216 /// else means the file is not the one we wrote.
217 #[cfg_attr(not(test), allow(dead_code))]
218 pub fn next(&mut self) -> Result<Option<Feature>> {
219 let Some(record) =
220 self.inner.next().map_err(|e| osm_ingest::proto::Error(e.to_string()))?
221 else {
222 return Ok(None);
223 };
224 Ok(Some(feature_of(record)?))
225 }
226}
227
228/// Classified ways on disk: the second row of the table above, and the second thing stage A no
229/// longer holds.
230///
231/// # Why a file rather than the `HashMap<i64, Way>` this replaces
232///
233/// The map cost ~2.7 GB on California, nearly all of it node refs, and every read of it was
234/// sequential in ascending id order — [`crate::extract`] sorted the keys precisely so the archive
235/// would not depend on hash order. It was a map only because a relation reaches its member ways by
236/// id, in whatever order it lists them, and that one random access is served far more cheaply by
237/// keeping *only* the relation members resident: California has 63 156 relations against several
238/// million classified ways.
239///
240/// # Why nothing has to be sorted on the way back
241///
242/// A `.osm.pbf` stores ways sorted by id, and [`osm_ingest::pbf::run_pass_sink`] hands finished
243/// chunks to its sink in file order. Appending as pass 1 goes therefore produces a file already in
244/// the order materialisation wants, and the sort disappears along with the map.
245///
246/// [`push`] **enforces** that ordering rather than trusting it. An id that does not advance would
247/// silently reorder the archive, and a byte-identical rebuild is the only evidence this pipeline has
248/// that a change to stage A preserved its meaning — so a file that is not sorted is an error here,
249/// where it is one line of output, rather than a diff in a 655 MB archive.
250///
251/// # The encoding
252///
253/// One record per way, every field a varint, nothing aligned:
254///
255/// | field | encoding |
256/// |---|---|
257/// | id | zigzag varint of the gap from the previous record's id |
258/// | class | unsigned varint of [`pack`]'s integer |
259/// | ref count | unsigned varint |
260/// | refs | zigzag varint of each ref's gap from the one before it, the first from zero |
261/// | name | unsigned varint byte length, then that many UTF-8 bytes (zero when nameless) |
262/// | lane count | unsigned varint |
263/// | turn masks | a count then each `u16`, forward then backward |
264/// | carriageway | unsigned varint of the packed forward/backward/divider word |
265/// | building | a presence byte, then three packed varints when set |
266///
267/// Delta coding earns its keep rather than being a flourish. The refs are ~150 M ids on California
268/// and the file is read twice — once to collect the node ids pass 3 must resolve, once to build
269/// geometry — so a flat 8 bytes each would be 1.2 GB read twice. Consecutive nodes of a way were
270/// almost always created in one editing session and so have near-consecutive ids, which is exactly
271/// what a delta collapses to one or two bytes.
272///
273/// [`push`]: WaySink::push
274pub struct WaySink {
275 out: WayOut,
276 /// One record's bytes, reused. Several million records, so a `Vec` per record would be several
277 /// million allocations for a buffer that is dead a line later.
278 record: Vec<u8>,
279 last_id: i64,
280 count: u64,
281 refs: u64,
282 max_ref: i64,
283}
284
285/// Where a [`WaySink`] stages its bytes: a file, or anonymous memory.
286enum WayOut {
287 File(BufWriter<File>),
288 Anon(tile_build::anon::AnonStore),
289}
290
291impl WaySink {
292 pub fn create(path: &Path) -> Result<WaySink> {
293 let file = File::create(path)
294 .map_err(|e| Error(format!("cannot create {}: {e}", path.display())))?;
295 Ok(WaySink {
296 // A megabyte, because the writes are a few dozen bytes each and there are millions.
297 out: WayOut::File(BufWriter::with_capacity(1 << 20, file)),
298 record: Vec::new(),
299 last_id: 0,
300 count: 0,
301 refs: 0,
302 max_ref: 0,
303 })
304 }
305
306 /// Anonymous twin of [`create`](Self::create): same records in pagefile-backed
307 /// memory, no file. `path` names nothing — it only rides
308 /// along for error messages. Pair with [`WaySink::finish_anon`].
309 pub fn create_anon(path: &Path) -> Result<WaySink> {
310 Self::create_planned(path, osm_ingest::mem::SpillPlan::Anon)
311 }
312
313 /// Create with an explicit staging plan. See [`Sink::create_planned`]: the budget gate picks
314 /// `File` when anon commit does not fit, and `File` stages through the `.tmp` at `path`,
315 /// removed after materialise like every other scratch file. Pair with
316 /// [`finish_either`](Self::finish_either).
317 pub fn create_planned(path: &Path, plan: osm_ingest::mem::SpillPlan) -> Result<WaySink> {
318 let out = match plan {
319 osm_ingest::mem::SpillPlan::Anon => {
320 WayOut::Anon(tile_build::anon::AnonStore::new())
321 }
322 osm_ingest::mem::SpillPlan::File => {
323 eprintln!(" [stage A] ways spill -> {} (file backend: commit budget)", path.display());
324 let file = File::create(path)
325 .map_err(|e| Error(format!("cannot create {}: {e}", path.display())))?;
326 // A megabyte, because the writes are a few dozen bytes each and there are millions.
327 WayOut::File(BufWriter::with_capacity(1 << 20, file))
328 }
329 };
330 Ok(WaySink {
331 out,
332 record: Vec::new(),
333 last_id: 0,
334 count: 0,
335 refs: 0,
336 max_ref: 0,
337 })
338 }
339
340 /// Append one classified way. `id` must be greater than the previous call's.
341 ///
342 /// `name` is the display label for `places`/`poi` ways, `None` for every other layer. Written
343 /// as a length-prefixed string per record — zero bytes for the nameless, which is nearly all
344 /// of them. `lane_count`, `turn_fwd`, `turn_bwd` and `carriageway` are a road's lane count,
345 /// per-lane turn masks and directional split, empty for every other layer and for a road with
346 /// no lane tags; a handful of trailing varints per record, which the scratch file (removed
347 /// after materialise) affords.
348 #[allow(clippy::too_many_arguments)]
349 pub fn push(
350 &mut self,
351 id: i64,
352 class: &Class,
353 refs: &[i64],
354 name: Option<&str>,
355 lane_count: u8,
356 turn_fwd: &[u16],
357 turn_bwd: &[u16],
358 carriageway: Carriageway,
359 building: Option<BuildingAttrs>,
360 ) -> Result<()> {
361 if self.count > 0 && id <= self.last_id {
362 return err(format!(
363 "way {id} arrived after way {}, so this PBF is not sorted by way id and the \
364 sequential ways spill cannot be used for it",
365 self.last_id,
366 ));
367 }
368 self.record.clear();
369 put_svarint(&mut self.record, id.wrapping_sub(self.last_id));
370 put_uvarint(&mut self.record, pack(class)?);
371 put_uvarint(&mut self.record, refs.len() as u64);
372 let mut previous: i64 = 0;
373 for &node in refs {
374 put_svarint(&mut self.record, node.wrapping_sub(previous));
375 previous = node;
376 self.max_ref = self.max_ref.max(node);
377 }
378 match name.filter(|n| !n.is_empty()) {
379 Some(name) => {
380 put_uvarint(&mut self.record, name.len() as u64);
381 self.record.extend_from_slice(name.as_bytes());
382 }
383 None => put_uvarint(&mut self.record, 0),
384 }
385 put_uvarint(&mut self.record, lane_count as u64);
386 // The turn masks: a count then each u16, forward then backward. Zero counts for the
387 // overwhelming majority, which cost one byte each.
388 for masks in [turn_fwd, turn_bwd] {
389 put_uvarint(&mut self.record, masks.len() as u64);
390 for &m in masks {
391 put_uvarint(&mut self.record, m as u64);
392 }
393 }
394 // The directional split, as one packed varint. Zero — one byte — for the roads whose
395 // division was never surveyed, which is most of them.
396 put_uvarint(&mut self.record, pack_carriageway(carriageway));
397 // The building attributes: a presence byte, then the three packed words when present. A
398 // non-building writes one zero byte; a building — even one with no S3DB tags — writes its
399 // (usually all-zero) words so the tiler's side table stays dense-parallel to the layer.
400 match building {
401 Some(attrs) => {
402 put_uvarint(&mut self.record, 1);
403 let (a, b, c) = pack_building(&attrs);
404 put_uvarint(&mut self.record, a);
405 put_uvarint(&mut self.record, b);
406 put_uvarint(&mut self.record, c);
407 }
408 None => put_uvarint(&mut self.record, 0),
409 }
410 // Moved out rather than cloned: `out_write` takes `&mut self`, so `&self.record`
411 // cannot borrow across the call, and a per-way clone is a memcpy per record over
412 // millions of records. The buffer is restored below with its capacity intact, so the
413 // `clear` at the top of the next `push` still reuses the allocation.
414 let record = std::mem::take(&mut self.record);
415 let result = self.out_write(&record).map_err(|e| {
416 Error(format!("cannot write the ways spill: {e}"))
417 });
418 self.record = record;
419 result?;
420 self.last_id = id;
421 self.count += 1;
422 self.refs += refs.len() as u64;
423 Ok(())
424 }
425
426 fn out_write(&mut self, bytes: &[u8]) -> Result<()> {
427 match &mut self.out {
428 WayOut::File(f) => f.write_all(bytes).map_err(|e| {
429 Error(format!("cannot write the ways spill: {e}"))
430 }),
431 WayOut::Anon(a) => a.push(bytes).map(|_| ()).map_err(|e| {
432 Error(format!("cannot stage the ways spill: {e}"))
433 }),
434 }
435 }
436
437 /// Flush, and report how many ways were written, how many node refs they hold between them, and
438 /// the largest of those refs.
439 ///
440 /// None of the three is a statistic. [`crate::extract`] reads this file back to collect the node
441 /// ids pass 3 must resolve, and it picks between two ways of doing that on the ref count: below a
442 /// budget it sizes one exact vector (grown by extension a 200 M-id vector doubles into 2.1 GB of
443 /// capacity, and the realloc that gets it there holds the old and new allocations at once), and
444 /// above it sizes a bitset from `max_ref`. Both numbers are free here, where every ref is already
445 /// being walked to encode it, and neither is recoverable later without a second pass.
446 pub fn finish(mut self) -> Result<WayCounts> {
447 match &mut self.out {
448 WayOut::File(f) => f.flush().map_err(|e| Error(format!("cannot flush the ways spill: {e}")))?,
449 WayOut::Anon(a) => a.finish(),
450 }
451 Ok(WayCounts { ways: self.count, refs: self.refs, max_ref: self.max_ref })
452 }
453
454 /// Anonymous twin of [`finish`](Self::finish): seals the pagefile-backed
455 /// spill and hands back the counts plus the staged store. Errors on a
456 /// file-backed sink.
457 pub fn finish_anon(mut self) -> Result<(WayCounts, tile_build::anon::AnonStore)> {
458 match &mut self.out {
459 WayOut::File(_) => {
460 return err("finish_anon on a file-backed ways sink".to_string())
461 }
462 WayOut::Anon(a) => a.finish(),
463 }
464 let counts = WayCounts { ways: self.count, refs: self.refs, max_ref: self.max_ref };
465 match self.out {
466 WayOut::Anon(a) => Ok((counts, a)),
467 WayOut::File(_) => unreachable!("checked above"),
468 }
469 }
470
471 /// Seal, and hand back the counts plus the staged bytes on the anon plan or `None` on the
472 /// file plan (whose bytes live at the path the sink was created with). Unifies
473 /// [`finish`](Self::finish) and [`finish_anon`](Self::finish_anon) so callers that pick the
474 /// backend by budget seal without knowing which one they chose.
475 pub fn finish_either(mut self) -> Result<(WayCounts, Option<tile_build::anon::AnonStore>)> {
476 match &mut self.out {
477 WayOut::File(f) => f.flush().map_err(|e| Error(format!("cannot flush the ways spill: {e}")))?,
478 WayOut::Anon(a) => a.finish(),
479 }
480 let counts = WayCounts { ways: self.count, refs: self.refs, max_ref: self.max_ref };
481 match self.out {
482 WayOut::Anon(a) => Ok((counts, Some(a))),
483 WayOut::File(_) => Ok((counts, None)),
484 }
485 }
486}
487
488/// What a finished [`WaySink`] holds.
489pub struct WayCounts {
490 pub ways: u64,
491 /// Node refs summed over every way, duplicates included — a capacity, not a cardinality.
492 pub refs: u64,
493 /// The largest node ref written, or zero if none were. What a bitset over the id space is sized
494 /// from.
495 pub max_ref: i64,
496}
497
498/// Reads back what a [`WaySink`] wrote, in the order it was written.
499///
500/// File-backed ([`open`](Self::open)) or anonymous ([`open_anon`](Self::open_anon)):
501/// the record format is a sequential varint stream either way, so the reader is
502/// a cursor over bytes — a file cursor or a store offset. Same records, same order.
503pub struct WayReader {
504 inner: WayIn,
505 last_id: i64,
506 seen: u64,
507}
508
509/// Where a [`WayReader`] reads from.
510enum WayIn {
511 File(BufReader<File>),
512 Anon {
513 store: std::sync::Arc<tile_build::anon::AnonStore>,
514 at: u64,
515 buf: Vec<u8>,
516 used: usize,
517 },
518}