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

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

tilespill.rs227 lines · 11.5 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
76#[cfg(test)]
77use tilecodec::mamaps::body::Layer as BodyLayer;
78use tilecodec::mamaps::body::{
79 consts::CARRIAGEWAY_RECORD_LEN, BuildingAttrs, Carriageway, Feature as BodyFeature, Part,
80};
81use tilecodec::proto::{err, Error, Result};
82
83use crate::tiler::ChunkEntry;
84
85/// Bytes of fixed header before one entry's arenas.
86pub const ENTRY_HEADER_BYTES: usize = 32;
87
88/// Packed width of one [`BodyFeature`] in the spill: kind, kind_detail, geom_type, flags,
89/// name_idx, parts_offset, part_count, transit_color, transit_ordinal, transit_lanes,
90/// transit_taper, lane_count. Twenty-four, exactly the body's 24-byte record: the fields are
91/// the codec's own, so the scratch format never lags the codec by a version.
92const FEATURE_BYTES: usize = 24;
93/// Packed width of one [`Part`] in the spill: coord_start, point_count, winding. Ten — the
94/// body's 12-byte entry carries a reserved half-word the scratch format does not need.
95const PART_BYTES: usize = 10;
96/// Packed width of one `(i16, i16)` coordinate.
97const COORD_BYTES: usize = 4;
98/// Packed width of one feature id. Fixed rather than varint for the same reason the body's id
99/// table is: unsorted OSM ids have no ordering to delta against.
100const ID_BYTES: usize = 8;
101
102/// Packed width of one [`BuildingAttrs`] in the spill: height, min_height, roof_height (u16 each),
103/// roof_shape, roof_direction, roof_orientation (u8 each), building_colour, roof_colour (u32
104/// each). Seventeen — no alignment padding, unlike the body's 20-byte on-disk record.
105const BUILDING_BYTES: usize = 17;
106
107/// An entry longer than this is corruption, not a large tile layer. A tile-layer is capped at 65,535
108/// features by the body format, so the largest plausible entry is orders of magnitude below this.
109const MAX_ENTRY_BYTES: u64 = 1 << 30;
110
111/// Bytes the whole merge may hold in read windows, divided across its streams.
112///
113/// Small against the old 256 MiB on purpose: the merge holds one cursor per chunk (~27 k at a
114/// planet z14), and each cursor's window is live beside the batch above and the encode workers.
115/// 256 MiB of cursors on top of a ~GB batch is what a 512 KiB allocation failure looks like on
116/// a box with ~50 GB of commit headroom. 64 MiB still reads in 16 KiB+ windows at 4 k streams
117/// (the floor binds long before the budget does at planet scale), so the extra syscalls are
118/// noise against the decode.
119pub const READ_BUDGET: usize = 64 << 20;
120/// Smallest read window. Below this the syscall costs more than the memory saves.
121///
122/// Halved alongside the budget: at a planet z14's ~27 k streams the window formula divides the
123/// budget by the stream count and clamps to this floor, so the floor *is* the total
124/// (`streams x MIN_WINDOW`). 8 KiB keeps that total at ~216 MB instead of ~432 MB, still a
125/// reasonable read size off NVMe or the page cache, and the window-identity test pins that the
126/// size is not observable in the archive.
127pub const MIN_WINDOW: usize = 8 << 10;
128/// Largest read window. A stream is forward-only, so beyond this a longer window is only read-ahead
129/// the page cache would have done anyway.
130pub const MAX_WINDOW: usize = 1 << 20;
131
132/// How many bytes each of `streams` concurrent readers may buffer.
133///
134/// **Not observable in the output.** A reader yields the same entries in the same order whatever its
135/// window is, which is what `the_archive_is_identical_however_the_read_window_is_sized` holds this
136/// to; the window is a memory/syscall trade and nothing else.
137pub fn read_window_bytes(streams: usize) -> usize {
138 let forced = WINDOW_OVERRIDE.load(Ordering::Relaxed);
139 if forced > 0 {
140 return forced;
141 }
142 window_for(streams)
143}
144
145fn window_for(streams: usize) -> usize {
146 (READ_BUDGET / streams.max(1)).clamp(MIN_WINDOW, MAX_WINDOW)
147}
148
149/// A window forced by a test, or zero for the budget. Zero rather than an `Option`, because this is
150/// read on the merge's own path and a build never sets it.
151static WINDOW_OVERRIDE: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
152
153/// Pin the read window, or release it with zero. Tests only: the window has to be forcible for the
154/// claim that it is not observable to be worth anything.
155#[cfg(test)]
156pub fn set_read_window(bytes: usize) {
157 WINDOW_OVERRIDE.store(bytes, Ordering::Relaxed);
158}
159
160/// Tile runs recorded per chunk, keyed by `(chunk_start, chunk_len)`.
161type TileRunIndex = Vec<((u64, u64), Vec<TileRun>)>;
162
163/// Where one chunk's bytes live in a [`ChunkSpill`].
164#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
165pub struct ChunkRef {
166 pub at: u64,
167 pub len: u64,
168 pub entries: u64,
169}
170
171/// One zoom's chunks, in one file — or in anonymous memory.
172///
173/// `&self` throughout, so every worker writes through it and every reader reads through it -- the
174/// same discipline as `tile_build::spill::NormalizedChunks`, and for the same reason: one handle,
175/// many threads, positional I/O and no shared cursor.
176///
177/// Anonymous staging (via [`create_planned`](Self::create_planned)) stages the same chunks in
178/// pagefile-backed memory. Same offsets, same bytes, no
179/// file. The merge reads through the same [`ChunkReader`] either way.
180pub struct ChunkSpill {
181 /// The scratch file's name was removed right after creation (Unix): see [`Self::create`].
182 unlinked: bool,
183 /// `None` only while dropping, where the handle has to close before the file can be unlinked or
184 /// Windows refuses the delete. Always `None` on the anon path (no handle at all).
185 file: Option<File>,
186 anon: Option<std::sync::Mutex<tile_build::anon::AnonStore>>,
187 path: PathBuf,
188 /// The next free byte, and so also the total reserved. Reserved under the commit lock
189 /// ([`Self::write`], always `write` before `at`), so reservation order is completion order
190 /// and the file offset advances monotonically — one sequential chunk after another.
191 at: Mutex<u64>,
192 /// Serialises whole-chunk commits (reserve + write) so the file offset advances
193 /// monotonically: reservation order == completion order, one large sequential write
194 /// per chunk, no interleaved 1 MB pieces from N workers. Always taken before `at`.
195 write: Mutex<()>,
196 written: AtomicU64,
197 written_entries: AtomicU64,
198 read: AtomicU64,
199 read_entries: AtomicU64,
200 /// Per written chunk (keyed by its start offset and length -- an empty chunk shares its start
201 /// with the next one): its tile runs, recorded by `write_chunk` from
202 /// the map it encoded. What the merge planner reads instead of skip-walking every chunk back
203 /// off disk (twice per zoom: 78 s of the Nov 10 planet build, z14 alone 47 s).
204 runs: Mutex<TileRunIndex>,
205}
206
207/// One tile's entries within one chunk, as `write_chunk` laid them down. Narrow on purpose: a
208/// planet z14 records tens of millions of these, so offsets are relative to the chunk and counts
209/// are `u32` (a chunk is a few MB); a chunk that would overflow one is simply not indexed and the
210/// planner walks it.
211#[derive(Debug, Clone, Copy, PartialEq, Eq)]
212pub struct TileRun {
213 pub tile: u64,
214 /// Summed merge cost (features + coordinates) of the run's entries: what
215 /// [`ChunkReader::skip_entry`] reports for each.
216 pub cost: u32,
217 /// Offset of the run's first entry from the chunk's start.
218 pub rel_offset: u32,
219 /// Entries in the chunk before this run.
220 pub before: u32,
221}
222
223include!("tilespill_s1.rs");
224include!("tilespill_part1.rs");
225include!("tilespill_part2.rs");
226include!("tilespill_part3.rs");
227include!("tilespill_part4.rs");