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

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

tilespill.rs451 lines · 21.0 KiBRaw
1//! On-disk scratch for one zoom's tile chunks: the missing half of an external sort.
2//!
3//! [`crate::tiler`]'s map phase produces one `BTreeMap<(tile, layer), BodyLayer>` per chunk and its
4//! reduce k-way merges them. Those per-chunk maps already *are* the sorted runs of an external sort
5//! -- produced free, as a side effect of clipping -- and `Merged` already *is* its merge phase. The
6//! only piece missing was the disk in between, and holding it in memory instead is what put a
7//! north-america z14 at 53 GB resident and would put a planet z14 near 244 GB.
8//!
9//! This module is that disk. A worker hands a finished chunk to [`ChunkSpill::write_chunk`] and gets
10//! back a [`ChunkRef`]; the merge opens a [`ChunkReader`] per ref and walks them exactly as it
11//! walked the maps. Peak becomes `O(threads) + O(READ_BUDGET)` rather than `O(extract)`.
12//!
13//! Modelled on `tile_build::spill`, and the conventions are that module's: manual little-endian
14//! encode and decode, a zero-filled reserved tail so a field can be added without moving the ones
15//! already there, a length that is a pure function of the header so a reader validates before it
16//! allocates, counts cross-checked against the file's own length, and `Drop` cleanup so a run that
17//! dies mid-planet cannot strand a hundred gigabytes.
18//!
19//! # The format
20//!
21//! One chunk is a plain sequential stream of entries in `BTreeMap::into_iter` order -- ascending
22//! `(tile_id, layer_id)` -- with **no index**. The merge is strictly forward-only per stream, so an
23//! index would be bytes nothing reads.
24//!
25//! ```text
26//! 0..8 u64 tile_id
27//! 8..12 u32 features
28//! 12..16 u32 parts
29//! 16..20 u32 coords
30//! 20..21 u8 layer_id
31//! 21..24 reserved, zero
32//! 24..28 u32 names (label strings in this entry's table)
33//! 28..32 u32 ids (feature ids in this entry's table: 0, or one per feature)
34//! 32.. packed features (23 B), then parts (10 B), then coords (4 B), then ids (8 B),
35//! then names (u32 length + UTF-8 bytes each)
36//! ```
37//!
38//! The id count took the second reserved word, which is what that word was for. Ids sit inside
39//! the fixed arenas rather than after the names so [`payload_bytes`] stays a pure function of the
40//! header — a reader still validates the whole fixed run before it allocates any of it.
41//!
42//! Packed field by field rather than cast wholesale from the in-memory struct. `body::Feature` is
43//! `kind`, `kind_detail`, `geom_type`, `flags`, `parts_offset`, `part_count` -- fourteen bytes of
44//! payload in a sixteen-byte struct with no `#[repr(C)]`, so a bulk cast would be both unsound and
45//! dependent on the host's layout. Fourteen bytes is also less to write.
46//!
47//! Names ride per entry (not per chunk or per zoom) so the merge never holds more than one
48//! entry's strings at a time: a tile's labels are dozens of strings, a zoom's are millions.
49//!
50//! # Reading with a budget, not a constant
51//!
52//! The merge holds one cursor per chunk: about 5,700 at a north-america z14 and about 27,000 at a
53//! planet one. A fixed per-reader buffer is the wrong shape at both ends -- generous at 5,700, ruin
54//! at 27,000. [`read_window_bytes`] divides a total [`READ_BUDGET`] by the stream count instead, so
55//! the sum is a flat ceiling until the [`MIN_WINDOW`] floor takes over; the floor exists because a
56//! read smaller than it costs more in syscalls than it saves in memory, and at the stream counts a
57//! real build reaches the budget is still what binds.
58//!
59//! One pass, not a cascade. A cascading merge -- merge runs in groups, then merge the results -- is
60//! available and order-preserving, and it is the escape hatch if the merge thread's decode turns out
61//! to be the cost. It was not taken because it doubles I/O and doubles peak disk to buy memory that
62//! [`read_window_bytes`] already bounds.
63//!
64//! # Random reads
65//!
66//! Thousands of interleaved forward cursors is a fine access pattern on NVMe and a poor one on
67//! spinning media. [`READ_BUDGET`] is the dial: a larger window makes each stream's reads longer and
68//! rarer at the cost of resident bytes.
69
70use std::collections::BTreeMap;
71use std::fs::File;
72use std::path::PathBuf;
73use std::sync::atomic::{AtomicU64, Ordering};
74use std::sync::Mutex;
75
76use tilecodec::mamaps::body::{
77 BuildingAttrs, Carriageway, Feature as BodyFeature, Layer as BodyLayer, Part,
78 consts::CARRIAGEWAY_RECORD_LEN,
79};
80use tilecodec::proto::{err, Error, Result};
81
82use crate::tiler::ChunkEntry;
83
84/// Bytes of fixed header before one entry's arenas.
85pub const ENTRY_HEADER_BYTES: usize = 32;
86
87/// Packed width of one [`BodyFeature`] in the spill: kind, kind_detail, geom_type, flags,
88/// name_idx, parts_offset, part_count, transit_color, transit_ordinal, transit_lanes,
89/// transit_taper, lane_count. Twenty-four, exactly the body's 24-byte record: the fields are
90/// the codec's own, so the scratch format never lags the codec by a version.
91const FEATURE_BYTES: usize = 24;
92/// Packed width of one [`Part`] in the spill: coord_start, point_count, winding. Ten — the
93/// body's 12-byte entry carries a reserved half-word the scratch format does not need.
94const PART_BYTES: usize = 10;
95/// Packed width of one `(i16, i16)` coordinate.
96const COORD_BYTES: usize = 4;
97/// Packed width of one feature id. Fixed rather than varint for the same reason the body's id
98/// table is: unsorted OSM ids have no ordering to delta against.
99const ID_BYTES: usize = 8;
100
101/// Packed width of one [`BuildingAttrs`] in the spill: height, min_height, roof_height (u16 each),
102/// roof_shape, roof_direction, roof_orientation (u8 each), building_colour, roof_colour (u32
103/// each). Seventeen — no alignment padding, unlike the body's 20-byte on-disk record.
104const BUILDING_BYTES: usize = 17;
105
106/// An entry longer than this is corruption, not a large tile layer. A tile-layer is capped at 65,535
107/// features by the body format, so the largest plausible entry is orders of magnitude below this.
108const MAX_ENTRY_BYTES: u64 = 1 << 30;
109
110/// Bytes the whole merge may hold in read windows, divided across its streams.
111///
112/// Small against the old 256 MiB on purpose: the merge holds one cursor per chunk (~27 k at a
113/// planet z14), and each cursor's window is live beside the batch above and the encode workers.
114/// 256 MiB of cursors on top of a ~GB batch is what a 512 KiB allocation failure looks like on
115/// a box with ~50 GB of commit headroom. 64 MiB still reads in 16 KiB+ windows at 4 k streams
116/// (the floor binds long before the budget does at planet scale), so the extra syscalls are
117/// noise against the decode.
118pub const READ_BUDGET: usize = 64 << 20;
119/// Smallest read window. Below this the syscall costs more than the memory saves.
120///
121/// Halved alongside the budget: at a planet z14's ~27 k streams the window formula divides the
122/// budget by the stream count and clamps to this floor, so the floor *is* the total
123/// (`streams x MIN_WINDOW`). 8 KiB keeps that total at ~216 MB instead of ~432 MB, still a
124/// reasonable read size off NVMe or the page cache, and the window-identity test pins that the
125/// size is not observable in the archive.
126pub const MIN_WINDOW: usize = 8 << 10;
127/// Largest read window. A stream is forward-only, so beyond this a longer window is only read-ahead
128/// the page cache would have done anyway.
129pub const MAX_WINDOW: usize = 1 << 20;
130
131/// How many bytes each of `streams` concurrent readers may buffer.
132///
133/// **Not observable in the output.** A reader yields the same entries in the same order whatever its
134/// window is, which is what `the_archive_is_identical_however_the_read_window_is_sized` holds this
135/// to; the window is a memory/syscall trade and nothing else.
136pub fn read_window_bytes(streams: usize) -> usize {
137 let forced = WINDOW_OVERRIDE.load(Ordering::Relaxed);
138 if forced > 0 {
139 return forced;
140 }
141 window_for(streams)
142}
143
144fn window_for(streams: usize) -> usize {
145 (READ_BUDGET / streams.max(1)).clamp(MIN_WINDOW, MAX_WINDOW)
146}
147
148/// A window forced by a test, or zero for the budget. Zero rather than an `Option`, because this is
149/// read on the merge's own path and a build never sets it.
150static WINDOW_OVERRIDE: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
151
152/// Pin the read window, or release it with zero. Tests only: the window has to be forcible for the
153/// claim that it is not observable to be worth anything.
154#[cfg(test)]
155pub fn set_read_window(bytes: usize) {
156 WINDOW_OVERRIDE.store(bytes, Ordering::Relaxed);
157}
158
159/// Where one chunk's bytes live in a [`ChunkSpill`].
160#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
161pub struct ChunkRef {
162 pub at: u64,
163 pub len: u64,
164 pub entries: u64,
165}
166
167/// One zoom's chunks, in one file — or in anonymous memory.
168///
169/// `&self` throughout, so every worker writes through it and every reader reads through it -- the
170/// same discipline as `tile_build::spill::NormalizedChunks`, and for the same reason: one handle,
171/// many threads, positional I/O and no shared cursor.
172///
173/// Anonymous twin: [`create_anon`](Self::create_anon) stages the same chunks in
174/// pagefile-backed memory. Same offsets, same bytes, no
175/// file. The merge reads through the same [`ChunkReader`] either way.
176pub struct ChunkSpill {
177 /// `None` only while dropping, where the handle has to close before the file can be unlinked or
178 /// Windows refuses the delete. Always `None` on the anon path (no handle at all).
179 file: Option<File>,
180 anon: Option<std::sync::Mutex<tile_build::anon::AnonStore>>,
181 path: PathBuf,
182 /// The next free byte, and so also the total reserved. Reserved under the commit lock
183 /// ([`Self::write`], always `write` before `at`), so reservation order is completion order
184 /// and the file offset advances monotonically — one sequential chunk after another.
185 at: Mutex<u64>,
186 /// Serialises whole-chunk commits (reserve + write) so the file offset advances
187 /// monotonically: reservation order == completion order, one large sequential write
188 /// per chunk, no interleaved 1 MB pieces from N workers. Always taken before `at`.
189 write: Mutex<()>,
190 written: AtomicU64,
191 written_entries: AtomicU64,
192 read: AtomicU64,
193 read_entries: AtomicU64,
194}
195
196impl ChunkSpill {
197 /// Create the scratch file, truncating whatever a killed run left at the path.
198 ///
199 /// Read *and* write on one handle, because that is the whole shape of this module: the workers
200 /// write positionally through it and the merge reads positionally through it, and a second
201 /// handle would be a second file description with nothing to gain.
202 pub fn create(path: impl Into<PathBuf>) -> Result<ChunkSpill> {
203 let path = path.into();
204 let file = std::fs::OpenOptions::new()
205 .read(true)
206 .write(true)
207 .create(true)
208 .truncate(true)
209 .open(&path)
210 .map_err(|e| Error(format!("cannot create {}: {e}", path.display())))?;
211 Ok(ChunkSpill {
212 file: Some(file),
213 anon: None,
214 path,
215 at: Mutex::new(0),
216 write: Mutex::new(()),
217 written: AtomicU64::new(0),
218 written_entries: AtomicU64::new(0),
219 read: AtomicU64::new(0),
220 read_entries: AtomicU64::new(0),
221 })
222 }
223
224 /// Anonymous twin
225
226 /// Anonymous twin of [`create`](Self::create): same chunks and offsets in
227 /// pagefile-backed memory, no file. `path` names nothing — it only rides
228 /// along for error messages and the `check_books` accounting.
229 pub fn create_anon(path: impl Into<PathBuf>) -> Result<ChunkSpill> {
230 Self::create_planned(path, osm_ingest::mem::SpillPlan::Anon)
231 }
232
233 /// Create with an explicit staging plan. See [`osm_ingest::mem::SpillPlan::decide`]: the
234 /// budget gate picks `File` when anon commit does not fit, and `File` stages through the
235 /// scratch path (truncated like [`create`](Self::create), removed on drop). Same chunks,
236 /// same offsets, same bytes -- the backend never changes a hash.
237 pub fn create_planned(path: impl Into<PathBuf>, plan: osm_ingest::mem::SpillPlan) -> Result<ChunkSpill> {
238 match plan {
239 osm_ingest::mem::SpillPlan::Anon => Ok(ChunkSpill {
240 file: None,
241 anon: Some(std::sync::Mutex::new(tile_build::anon::AnonStore::new())),
242 path: path.into(),
243 at: Mutex::new(0),
244 write: Mutex::new(()),
245 written: AtomicU64::new(0),
246 written_entries: AtomicU64::new(0),
247 read: AtomicU64::new(0),
248 read_entries: AtomicU64::new(0),
249 }),
250 osm_ingest::mem::SpillPlan::File => Self::create(path),
251 }
252 }
253
254 /// Whether this spill stages in anonymous memory rather than a file.
255 pub fn is_anon(&self) -> bool {
256 self.anon.is_some()
257 }
258
259 fn file(&self) -> &File {
260 self.file.as_ref().expect("the tile chunk spill outlives its readers and writers")
261 }
262
263 /// Write one finished chunk and say where it went.
264 ///
265 /// Takes the map **by value** and encodes out of `into_iter`, so the map shrinks as it is
266 /// written instead of being copied whole into a buffer beside itself.
267 ///
268 /// Encode happens outside any lock, in parallel across workers. The commit — reserving the
269 /// byte range and writing it — holds the `write` lock for one sequential write per chunk.
270 /// Reservation order is therefore completion order and the file offset advances
271 /// monotonically: no interleaved 1 MB pieces from N workers sharing one file offset space,
272 /// which is what turned N parallel positional fills into random-write interleaving on
273 /// spinning disks (and page-cache churn everywhere). The merge sorts chunks by their read
274 /// index, never by file position, so the layout change is not observable in the archive.
275 pub fn write_chunk(&self, map: BTreeMap<(u64, u8), ChunkEntry>) -> Result<ChunkRef> {
276 let entries = map.len() as u64;
277 let mut len = 0u64;
278 for ((_, layer_id), entry) in &map {
279 if *layer_id != entry.layer.layer_id {
280 // The merge keys its heap on the map key and reads `layer_id` off the layer it
281 // yields, so the two disagreeing would mean the round trip had to preserve both. It
282 // is one field on disk because in this generator they are one field.
283 return err(format!(
284 "a tile chunk entry is keyed on layer {layer_id} but carries layer {}",
285 entry.layer.layer_id
286 ));
287 }
288 len += entry_bytes(entry)?;
289 }
290
291 // Encoded before the commit lock, so N workers still clip and encode in parallel and
292 // only the disk write itself is serial. Sized exactly: `len` above is the encoded
293 // length, so this is one allocation per chunk rather than a growing buffer.
294 let mut buf: Vec<u8> = Vec::with_capacity(len as usize);
295 for ((tile, layer_id), layer) in map {
296 encode_entry(tile, layer_id, &layer, &mut buf);
297 }
298 debug_assert_eq!(buf.len() as u64, len, "the encoded chunk must match its reservation");
299
300 // One commit per chunk: reserve and write under the same lock, so the file sees whole
301 // sequential chunks in reservation order. Always `write` before `at`.
302 let _commit = self.write.lock().expect("the tile chunk spill's commit lock");
303 let at = {
304 let mut next = self.at.lock().expect("the tile chunk spill's cursor");
305 let at = *next;
306 *next += len;
307 at
308 };
309
310 let cursor = at + self.flush(&mut buf, at)?;
311
312 if cursor != at + len {
313 return err(format!(
314 "a tile chunk reserved {len} byte(s) and wrote {}",
315 cursor - at
316 ));
317 }
318 self.written.fetch_add(len, Ordering::Relaxed);
319 self.written_entries.fetch_add(entries, Ordering::Relaxed);
320 Ok(ChunkRef { at, len, entries })
321 }
322
323 /// Write `buf` at `offset` and clear it. Returns what it wrote.
324 fn flush(&self, buf: &mut Vec<u8>, offset: u64) -> Result<u64> {
325 if buf.is_empty() {
326 return Ok(0);
327 }
328 match (&self.file, &self.anon) {
329 (Some(f), None) => write_all_at(f, buf, offset)
330 .map_err(|e| Error(format!("writing {}: {e}", self.path.display())))?,
331 (None, Some(a)) => {
332 let mut store = a.lock().expect("the anon tile chunk spill");
333 // Positional: the cursor reservation above hands each chunk a
334 // back-to-back range, flushed here in pieces. `write_at`
335 // refuses gaps (a lost chunk) but accepts piece-wise fills.
336 store.write_at(offset, buf).map_err(|e| {
337 Error(format!("staging anon tile chunk: {e}"))
338 })?;
339 }
340 _ => return err("a tile chunk spill has no backend".to_string()),
341 }
342 let n = buf.len() as u64;
343 buf.clear();
344 Ok(n)
345 }
346
347 /// A forward cursor over one chunk, buffering `window` bytes at a time.
348 pub fn reader(&self, chunk: &ChunkRef, window: usize) -> ChunkReader<'_> {
349 ChunkReader {
350 spill: self,
351 at: chunk.at,
352 end: chunk.at + chunk.len,
353 left: chunk.entries,
354 buf: Vec::new(),
355 used: 0,
356 window: window.max(ENTRY_HEADER_BYTES),
357 spare: None,
358 exact_end: true,
359 }
360 }
361
362 /// Reserved, written, on disk and read back must all agree.
363 ///
364 /// `tile_build::spill::BucketSet::seal`'s triple entry, for the same reason: a chunk that
365 /// quietly lost entries would produce an archive with holes in it and nothing downstream could
366 /// tell. Called once the merge has drained every reader. On the anon path "on disk" is the
367 /// store's committed length — same check, no file.
368 pub fn check_books(&self) -> Result<()> {
369 let reserved = *self.at.lock().expect("the tile chunk spill's cursor");
370 let written = self.written.load(Ordering::Relaxed);
371 if reserved != written {
372 return err(format!(
373 "{} reserved {reserved} byte(s) and wrote {written}",
374 self.path.display()
375 ));
376 }
377 let staged = match (&self.file, &self.anon) {
378 (Some(_), None) => std::fs::metadata(&self.path)
379 .map_err(|e| Error(format!("cannot stat {}: {e}", self.path.display())))?
380 .len(),
381 (None, Some(a)) => a.lock().expect("the anon tile chunk spill").len(),
382 _ => return err("a tile chunk spill has no backend".to_string()),
383 };
384 if staged != written {
385 return err(format!(
386 "{} stages {staged} byte(s) but {written} were written to it",
387 self.path.display()
388 ));
389 }
390 let read = self.read.load(Ordering::Relaxed);
391 if read != written {
392 return err(format!(
393 "{} wrote {written} byte(s) and read back {read}",
394 self.path.display()
395 ));
396 }
397 let pushed = self.written_entries.load(Ordering::Relaxed);
398 let pulled = self.read_entries.load(Ordering::Relaxed);
399 if pushed != pulled {
400 return err(format!(
401 "{} wrote {pushed} entr(ies) and read back {pulled}",
402 self.path.display()
403 ));
404 }
405 Ok(())
406 }
407}
408
409impl Drop for ChunkSpill {
410 fn drop(&mut self) {
411 // The handle first, or Windows refuses the delete. Anon path holds no
412 // handle and no file: nothing to do, the mapping frees with the store.
413 self.file = None;
414 if self.anon.is_none() {
415 let _ = std::fs::remove_file(&self.path);
416 }
417 }
418}
419
420/// A forward-only cursor over one chunk's byte range.
421///
422/// Reads through `&ChunkSpill`, so every cursor in a merge shares one file handle.
423pub struct ChunkReader<'a> {
424 spill: &'a ChunkSpill,
425 /// Disk offset of the first byte not yet in `buf`.
426 at: u64,
427 /// One past the chunk's last byte.
428 end: u64,
429 /// Entries the header said were written and this cursor has not yielded.
430 left: u64,
431 buf: Vec<u8>,
432 /// How much of `buf` has been yielded.
433 used: usize,
434 window: usize,
435 /// A recycled entry's emptied arenas, handed back by the merge after it drains an entry into
436 /// its accumulator. `decode` reuses these buffers instead of allocating four fresh `Vec`s per
437 /// entry — the decode is on the serial merge thread, so its allocator churn is Amdahl time.
438 /// `None` until the merge returns one; a decoded entry is byte-identical whether it was built
439 /// from a recycled arena or a fresh one, because the contents are written the same way.
440 spare: Option<ChunkEntry>,
441 /// Whether this cursor runs to the chunk's last byte. A range worker's
442 /// segment ends mid-chunk (the next range owns what follows), so only a
443 /// cursor that does reach the end enforces the no-trailing-bytes check —
444 /// any other segment legitimately stops with unread bytes after it.
445 exact_end: bool,
446}
447
448include!("tilespill_part1.rs");
449include!("tilespill_part2.rs");
450include!("tilespill_part3.rs");
451include!("tilespill_part4.rs");