//! On-disk scratch for one zoom's tile chunks: the missing half of an external sort. //! //! [`crate::tiler`]'s map phase produces one `BTreeMap<(tile, layer), BodyLayer>` per chunk and its //! reduce k-way merges them. Those per-chunk maps already *are* the sorted runs of an external sort //! -- produced free, as a side effect of clipping -- and `Merged` already *is* its merge phase. The //! only piece missing was the disk in between, and holding it in memory instead is what put a //! north-america z14 at 53 GB resident and would put a planet z14 near 244 GB. //! //! This module is that disk. A worker hands a finished chunk to [`ChunkSpill::write_chunk`] and gets //! back a [`ChunkRef`]; the merge opens a [`ChunkReader`] per ref and walks them exactly as it //! walked the maps. Peak becomes `O(threads) + O(READ_BUDGET)` rather than `O(extract)`. //! //! Modelled on `tile_build::spill`, and the conventions are that module's: manual little-endian //! encode and decode, a zero-filled reserved tail so a field can be added without moving the ones //! already there, a length that is a pure function of the header so a reader validates before it //! allocates, counts cross-checked against the file's own length, and `Drop` cleanup so a run that //! dies mid-planet cannot strand a hundred gigabytes. //! //! # The format //! //! One chunk is a plain sequential stream of entries in `BTreeMap::into_iter` order -- ascending //! `(tile_id, layer_id)` -- with **no index**. The merge is strictly forward-only per stream, so an //! index would be bytes nothing reads. //! //! ```text //! 0..8 u64 tile_id //! 8..12 u32 features //! 12..16 u32 parts //! 16..20 u32 coords //! 20..21 u8 layer_id //! 21..24 reserved, zero //! 24..28 u32 names (label strings in this entry's table) //! 28..32 u32 ids (feature ids in this entry's table: 0, or one per feature) //! 32.. packed features (23 B), then parts (10 B), then coords (4 B), then ids (8 B), //! then names (u32 length + UTF-8 bytes each) //! ``` //! //! The id count took the second reserved word, which is what that word was for. Ids sit inside //! the fixed arenas rather than after the names so [`payload_bytes`] stays a pure function of the //! header — a reader still validates the whole fixed run before it allocates any of it. //! //! Packed field by field rather than cast wholesale from the in-memory struct. `body::Feature` is //! `kind`, `kind_detail`, `geom_type`, `flags`, `parts_offset`, `part_count` -- fourteen bytes of //! payload in a sixteen-byte struct with no `#[repr(C)]`, so a bulk cast would be both unsound and //! dependent on the host's layout. Fourteen bytes is also less to write. //! //! Names ride per entry (not per chunk or per zoom) so the merge never holds more than one //! entry's strings at a time: a tile's labels are dozens of strings, a zoom's are millions. //! //! # Reading with a budget, not a constant //! //! The merge holds one cursor per chunk: about 5,700 at a north-america z14 and about 27,000 at a //! planet one. A fixed per-reader buffer is the wrong shape at both ends -- generous at 5,700, ruin //! at 27,000. [`read_window_bytes`] divides a total [`READ_BUDGET`] by the stream count instead, so //! the sum is a flat ceiling until the [`MIN_WINDOW`] floor takes over; the floor exists because a //! read smaller than it costs more in syscalls than it saves in memory, and at the stream counts a //! real build reaches the budget is still what binds. //! //! One pass, not a cascade. A cascading merge -- merge runs in groups, then merge the results -- is //! available and order-preserving, and it is the escape hatch if the merge thread's decode turns out //! to be the cost. It was not taken because it doubles I/O and doubles peak disk to buy memory that //! [`read_window_bytes`] already bounds. //! //! # Random reads //! //! Thousands of interleaved forward cursors is a fine access pattern on NVMe and a poor one on //! spinning media. [`READ_BUDGET`] is the dial: a larger window makes each stream's reads longer and //! rarer at the cost of resident bytes. use std::collections::BTreeMap; use std::fs::File; use std::path::PathBuf; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Mutex; #[cfg(test)] use tilecodec::mamaps::body::Layer as BodyLayer; use tilecodec::mamaps::body::{ consts::CARRIAGEWAY_RECORD_LEN, BuildingAttrs, Carriageway, Feature as BodyFeature, Part, }; use tilecodec::proto::{err, Error, Result}; use crate::tiler::ChunkEntry; /// Bytes of fixed header before one entry's arenas. pub const ENTRY_HEADER_BYTES: usize = 32; /// Packed width of one [`BodyFeature`] in the spill: kind, kind_detail, geom_type, flags, /// name_idx, parts_offset, part_count, transit_color, transit_ordinal, transit_lanes, /// transit_taper, lane_count. Twenty-four, exactly the body's 24-byte record: the fields are /// the codec's own, so the scratch format never lags the codec by a version. const FEATURE_BYTES: usize = 24; /// Packed width of one [`Part`] in the spill: coord_start, point_count, winding. Ten — the /// body's 12-byte entry carries a reserved half-word the scratch format does not need. const PART_BYTES: usize = 10; /// Packed width of one `(i16, i16)` coordinate. const COORD_BYTES: usize = 4; /// Packed width of one feature id. Fixed rather than varint for the same reason the body's id /// table is: unsorted OSM ids have no ordering to delta against. const ID_BYTES: usize = 8; /// Packed width of one [`BuildingAttrs`] in the spill: height, min_height, roof_height (u16 each), /// roof_shape, roof_direction, roof_orientation (u8 each), building_colour, roof_colour (u32 /// each). Seventeen — no alignment padding, unlike the body's 20-byte on-disk record. const BUILDING_BYTES: usize = 17; /// An entry longer than this is corruption, not a large tile layer. A tile-layer is capped at 65,535 /// features by the body format, so the largest plausible entry is orders of magnitude below this. const MAX_ENTRY_BYTES: u64 = 1 << 30; /// Bytes the whole merge may hold in read windows, divided across its streams. /// /// Small against the old 256 MiB on purpose: the merge holds one cursor per chunk (~27 k at a /// planet z14), and each cursor's window is live beside the batch above and the encode workers. /// 256 MiB of cursors on top of a ~GB batch is what a 512 KiB allocation failure looks like on /// a box with ~50 GB of commit headroom. 64 MiB still reads in 16 KiB+ windows at 4 k streams /// (the floor binds long before the budget does at planet scale), so the extra syscalls are /// noise against the decode. pub const READ_BUDGET: usize = 64 << 20; /// Smallest read window. Below this the syscall costs more than the memory saves. /// /// Halved alongside the budget: at a planet z14's ~27 k streams the window formula divides the /// budget by the stream count and clamps to this floor, so the floor *is* the total /// (`streams x MIN_WINDOW`). 8 KiB keeps that total at ~216 MB instead of ~432 MB, still a /// reasonable read size off NVMe or the page cache, and the window-identity test pins that the /// size is not observable in the archive. pub const MIN_WINDOW: usize = 8 << 10; /// Largest read window. A stream is forward-only, so beyond this a longer window is only read-ahead /// the page cache would have done anyway. pub const MAX_WINDOW: usize = 1 << 20; /// How many bytes each of `streams` concurrent readers may buffer. /// /// **Not observable in the output.** A reader yields the same entries in the same order whatever its /// window is, which is what `the_archive_is_identical_however_the_read_window_is_sized` holds this /// to; the window is a memory/syscall trade and nothing else. pub fn read_window_bytes(streams: usize) -> usize { let forced = WINDOW_OVERRIDE.load(Ordering::Relaxed); if forced > 0 { return forced; } window_for(streams) } fn window_for(streams: usize) -> usize { (READ_BUDGET / streams.max(1)).clamp(MIN_WINDOW, MAX_WINDOW) } /// A window forced by a test, or zero for the budget. Zero rather than an `Option`, because this is /// read on the merge's own path and a build never sets it. static WINDOW_OVERRIDE: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); /// Pin the read window, or release it with zero. Tests only: the window has to be forcible for the /// claim that it is not observable to be worth anything. #[cfg(test)] pub fn set_read_window(bytes: usize) { WINDOW_OVERRIDE.store(bytes, Ordering::Relaxed); } /// Tile runs recorded per chunk, keyed by `(chunk_start, chunk_len)`. type TileRunIndex = Vec<((u64, u64), Vec)>; /// Where one chunk's bytes live in a [`ChunkSpill`]. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub struct ChunkRef { pub at: u64, pub len: u64, pub entries: u64, } /// One zoom's chunks, in one file — or in anonymous memory. /// /// `&self` throughout, so every worker writes through it and every reader reads through it -- the /// same discipline as `tile_build::spill::NormalizedChunks`, and for the same reason: one handle, /// many threads, positional I/O and no shared cursor. /// /// Anonymous staging (via [`create_planned`](Self::create_planned)) stages the same chunks in /// pagefile-backed memory. Same offsets, same bytes, no /// file. The merge reads through the same [`ChunkReader`] either way. pub struct ChunkSpill { /// The scratch file's name was removed right after creation (Unix): see [`Self::create`]. unlinked: bool, /// `None` only while dropping, where the handle has to close before the file can be unlinked or /// Windows refuses the delete. Always `None` on the anon path (no handle at all). file: Option, anon: Option>, path: PathBuf, /// The next free byte, and so also the total reserved. Reserved under the commit lock /// ([`Self::write`], always `write` before `at`), so reservation order is completion order /// and the file offset advances monotonically — one sequential chunk after another. at: Mutex, /// Serialises whole-chunk commits (reserve + write) so the file offset advances /// monotonically: reservation order == completion order, one large sequential write /// per chunk, no interleaved 1 MB pieces from N workers. Always taken before `at`. write: Mutex<()>, written: AtomicU64, written_entries: AtomicU64, read: AtomicU64, read_entries: AtomicU64, /// Per written chunk (keyed by its start offset and length -- an empty chunk shares its start /// with the next one): its tile runs, recorded by `write_chunk` from /// the map it encoded. What the merge planner reads instead of skip-walking every chunk back /// off disk (twice per zoom: 78 s of the Nov 10 planet build, z14 alone 47 s). runs: Mutex, } /// One tile's entries within one chunk, as `write_chunk` laid them down. Narrow on purpose: a /// planet z14 records tens of millions of these, so offsets are relative to the chunk and counts /// are `u32` (a chunk is a few MB); a chunk that would overflow one is simply not indexed and the /// planner walks it. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct TileRun { pub tile: u64, /// Summed merge cost (features + coordinates) of the run's entries: what /// [`ChunkReader::skip_entry`] reports for each. pub cost: u32, /// Offset of the run's first entry from the chunk's start. pub rel_offset: u32, /// Entries in the chunk before this run. pub before: u32, } include!("tilespill_s1.rs"); include!("tilespill_part1.rs"); include!("tilespill_part2.rs"); include!("tilespill_part3.rs"); include!("tilespill_part4.rs");