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

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

store.rs329 lines · 14.5 KiBRaw
1//! The feature store: classified features staged **outside the heap** rather than in memory.
2//!
3//! # Why this exists
4//!
5//! Measured on `california-latest.osm.pbf`, the generator peaked at 10.03 GB — so essentially
6//! none of it was the tiler. It was all stage A, where three
7//! large things were alive at once:
8//!
9//! | | California |
10//! |---|
11//! | materialised features, lon/lat `f64` | ~4.9 GB |
12//! | classified ways and their node refs | ~2.7 GB |
13//! | node id -> location table | ~2.5 GB |
14//!
15//! The features were the largest and the only one that did not have to be resident: nothing reads
16//! them until the tiler does, and the tiler reads them **once per zoom, in order**. So they are
17//! staged outside the heap -- anonymous pagefile memory when the commit budget allows (no `.tmp`
18//! files, nothing stranded on kill), a scratch file beside the output when it does not -- and the
19//! tiler streams them fifteen times instead of holding them fifteen times over. Which backend is
20//! the budget gate's decision ([`osm_ingest::mem::SpillPlan`]), made from the counts pass 1
21//! measured; same records either way, so the backend never changes a hash.
22//!
23//! # The format is `tile_build`'s, not a new one
24//!
25//! [`spill::NormalizedWriter`] already writes exactly this: a length-prefixed record per feature
26//! holding a lon/lat geometry and a property list. Reusing it means the encoding is already tested,
27//! already round-tripped, and already handles every geometry kind — and it costs one small
28//! indirection: the [`Class`] is packed into a single integer property. That is the plan's own
29//! suggestion, and it is why this module needed no format of its own.
30//!
31//! The one change since made to that format was made *there*, for both its consumers: the geometry
32//! is stored as `i32` e7 rather than `f64` degrees, halving the spill. Every coordinate `osm_ingest`
33//! produces is already an e7 integer, so this archive is byte-identical across that change; see
34//! [`spill::encode_geometry`].
35//!
36//! # The second table: classified ways
37//!
38//! [`WaySink`] and [`WayReader`] do the same for the ~2.7 GB row of that table, for the same reason
39//! and by a different route: a way's record is a handful of integers rather than a geometry, and it
40//! is read back in the order it was written, so it gets a format of its own rather than
41//! `NormalizedWriter`'s. Same backend choice as the features (anon or file, budget-gated); the
42//! spill is freed right after materialise, before the routing graph is loaded, so the two never
43//! peak together. See [`WaySink`] for why no sort is needed on the way back.
44//!
45//! # The third table: relation member ways
46//!
47//! Neither spill serves the one random access in stage A: a relation reaches its member ways by
48//! id, in the order it lists them. So the members -- and only the members -- stay resident, in a
49//! sorted vector ([`MemberWays`](crate::extract::MemberWays)) rather than a hash map: at planet's
50//! 8.4 M member ways the map's per-entry overhead is hundreds of MB beside the ref bytes. Freed
51//! with the coordinate table after materialise, before the externals.
52
53use std::fs::File;
54#[cfg(test)]
55use std::io::{BufRead, BufReader};
56use std::io::{BufWriter, Write};
57use std::path::{Path, PathBuf};
58
59use osm_ingest::proto::{err, zigzag, Error, Result};
60use tile_build::geom::{bounds as geom_bounds, Geometry, Rect};
61use tile_build::mvt::Value;
62use tile_build::spill::{
63 encode_geometry, GeomKind, NormalizedChunks, NormalizedReader, NormalizedWriter,
64 NORM_CHUNK_FEATURES,
65};
66
67use crate::extract::Feature;
68use crate::schema::Class;
69use tilecodec::mamaps::body::{BuildingAttrs, Carriageway};
70
71/// The property key the packed [`Class`] travels under.
72///
73/// One byte, because it is written once per feature and 15.5 M allocations of a longer name is a
74/// cost with nothing to show for it.
75const CLASS_KEY: &str = "c";
76
77/// The property key a transit line's colour travels under, as a `Uint` of `0xRRGGBB`.
78///
79/// Only `transit` features set it. Absent for everything else, so the spill pays nothing for the
80/// 200 M features that have no colour.
81const COLOR_KEY: &str = "t";
82
83/// The property key a transit line's lane inputs travel under, as a `Uint` packing the colour's
84/// ordinal, the corridor's colour count and the taper fraction one byte each.
85///
86/// A second key rather than packed alongside the colour: the two are decided in different places
87/// (the colour is the agency's, the lane inputs are the exporter's). Three bytes in one `Uint`
88/// rather than three keys, because a spilled key is an owned `String` per feature.
89const LANE_KEY: &str = "s";
90
91/// The property key a label's display name travels under, when it has one.
92///
93/// `places` and `poi` are the only layers that set it. Absent (not empty) for everything else,
94/// so the spill pays nothing for the 190 M features that have no name.
95const NAME_KEY: &str = "n";
96
97/// The property key a label's tagged OSM element id travels under, as a `Uint`.
98///
99/// Only `places` and `poi` features set it, and only when the element had an id to carry. Absent
100/// (not zero) otherwise, so the spill pays nothing for the 190 M features that have none — the
101/// same bargain [`NAME_KEY`] makes.
102const ID_KEY: &str = "i";
103
104/// The property key a road's carriageway lane count travels under, as a `Uint`.
105///
106/// Only `roads` features with a `lanes` tag set it. Absent (not zero) otherwise, so the spill
107/// pays nothing for the roads with no lane data and for every non-road — the same bargain
108/// [`NAME_KEY`] and [`ID_KEY`] make.
109const LANE_COUNT_KEY: &str = "l";
110
111/// The property keys a road's per-lane turn masks travel under, forward and backward, each a
112/// `|`-separated decimal string of `LANE_*` masks (the same [`osm_ingest::roads::pack_lanes`] form
113/// the graph and pmtiles use). Only roads with `turn:lanes` set them; absent otherwise, so the
114/// spill pays nothing for the roads and every non-road that have none.
115const TURN_FWD_KEY: &str = "tf";
116const TURN_BWD_KEY: &str = "tb";
117
118/// The property key a road's carriageway travels under, as a `Uint` packing the forward and
119/// backward lane counts a byte each and the solid-divider bits above them (see
120/// [`pack_carriageway`]).
121///
122/// Only a road whose split was actually surveyed sets it. Absent (not zero) otherwise, so the
123/// spill pays nothing for the roads whose division is unknown — which is most of them, and the
124/// same bargain [`NAME_KEY`] and [`LANE_COUNT_KEY`] make.
125const CARRIAGEWAY_KEY: &str = "cw";
126
127/// A [`Carriageway`] as the single `Uint` the spill carries it as: forward in bits 0..8, backward
128/// in 8..16, the divider bits in 16..48. Lossless, and the inverse is [`unpack_carriageway`].
129fn pack_carriageway(c: Carriageway) -> u64 {
130 (c.forward as u64) | ((c.backward as u64) << 8) | ((c.solid_dividers as u64) << 16)
131}
132
133fn unpack_carriageway(bits: u64) -> Carriageway {
134 Carriageway {
135 forward: bits as u8,
136 backward: (bits >> 8) as u8,
137 solid_dividers: (bits >> 16) as u32,
138 }
139}
140
141/// The property keys a building's S3DB attributes travel under, three `Uint`s packing the eight
142/// [`BuildingAttrs`] fields (see [`pack_building`]). Only `buildings` features set them, and every
143/// building sets all three — even one with no S3DB tags, whose attributes are all zero — so a
144/// building stays distinguishable from a non-building on the way back and the side table the tiler
145/// builds stays dense-parallel to the layer's features.
146const BLD_A_KEY: &str = "ba";
147const BLD_B_KEY: &str = "bb";
148const BLD_C_KEY: &str = "bc";
149
150/// A [`BuildingAttrs`] packed into the three `Uint`s the spill carries it as.
151///
152/// `a` holds the three heights and the roof shape; `b` the two roof bytes and the wall colour;
153/// `c` the roof colour. Lossless — every field is copied bit for bit — and the inverse is
154/// [`unpack_building`].
155fn pack_building(a: &BuildingAttrs) -> (u64, u64, u64) {
156 let word_a = ((a.height as u64) << 40)
157 | ((a.min_height as u64) << 24)
158 | ((a.roof_height as u64) << 8)
159 | (a.roof_shape as u64);
160 let word_b = ((a.roof_direction as u64) << 40)
161 | ((a.roof_orientation as u64) << 32)
162 | (a.building_colour as u64);
163 (word_a, word_b, a.roof_colour as u64)
164}
165
166fn unpack_building(a: u64, b: u64, c: u64) -> BuildingAttrs {
167 BuildingAttrs {
168 height: (a >> 40) as u16,
169 min_height: (a >> 24) as u16,
170 roof_height: (a >> 8) as u16,
171 roof_shape: a as u8,
172 roof_direction: (b >> 40) as u8,
173 roof_orientation: (b >> 32) as u8,
174 building_colour: b as u32,
175 roof_colour: c as u32,
176 }
177}
178
179/// Parse a `|`-separated decimal mask string ([`osm_ingest::roads::pack_lanes`]'s output) back into
180/// per-lane `LANE_*` masks. An empty string is no lanes.
181fn unpack_lanes(packed: &str) -> Result<Vec<u16>> {
182 if packed.is_empty() {
183 return Ok(Vec::new());
184 }
185 packed
186 .split('|')
187 .map(|t| {
188 t.parse::<u16>().map_err(|_| Error(format!("a spilled turn mask `{t}` is not a u16")))
189 })
190 .collect()
191}
192
193/// A [`Class`] as one integer, so a feature's classification costs one property rather than seven.
194///
195/// | field | bits | width |
196/// |---|---|---|
197/// | `layer` | 0..4 | 10 layers (v2: `places`, `poi`, `transit`) |
198/// | `kind` | 4..20 | `u16` |
199/// | `kind_detail` | 20..36 | `u16` |
200/// | `flags` | 36..44 | `u8` |
201/// | `area` | 44..45 | one bit |
202/// | `min_zoom` | 45..50 | 0..31 |
203/// | `min_area_px` | 50..58 | 0..255, integral |
204///
205/// `min_area_px` is an `f64` in [`Class`] and a byte here. Every value the schema uses is a small
206/// whole number of square pixels, and [`pack`] refuses anything else rather than rounding a
207/// threshold silently.
208fn pack(class: &Class) -> Result<u64> {
209 if class.layer > 0b1111 {
210 return err(format!("layer {} does not fit the packed class", class.layer));
211 }
212 if class.min_zoom > 0b11111 {
213 return err(format!("min_zoom {} does not fit the packed class", class.min_zoom));
214 }
215 // Refused rather than rounded: a threshold quietly changed is a layer quietly wrong.
216 if class.min_area_px < 0.0 || class.min_area_px > 255.0 || class.min_area_px.fract() != 0.0 {
217 return err(format!(
218 "min_area_px {} is not a whole number of square pixels in 0..=255",
219 class.min_area_px,
220 ));
221 }
222 Ok((class.layer as u64)
223 | ((class.kind as u64) << 4)
224 | ((class.kind_detail as u64) << 20)
225 | ((class.flags as u64) << 36)
226 | ((class.area as u64) << 44)
227 | ((class.min_zoom as u64) << 45)
228 | ((class.min_area_px as u64) << 50))
229}
230
231fn unpack(bits: u64) -> Class {
232 Class {
233 layer: (bits & 0b1111) as u8,
234 kind: ((bits >> 4) & 0xffff) as u16,
235 kind_detail: ((bits >> 20) & 0xffff) as u16,
236 flags: ((bits >> 36) & 0xff) as u8,
237 area: (bits >> 44) & 1 == 1,
238 min_zoom: ((bits >> 45) & 0b11111) as u8,
239 min_area_px: ((bits >> 50) & 0xff) as f64,
240 }
241}
242
243/// A geometry encoded for the feature spill, plus the two facts the spill
244/// derives from it.
245///
246/// Built on the pool by the materialise drains (`EncodedGeom::live` is pure:
247/// [`encode_geometry`](tile_build::spill::encode_geometry),
248/// [`GeomKind::of`](tile_build::spill::GeomKind::of), [`bounds`](tile_build::geom::bounds)
249/// and the e7 box below touch nothing shared), appended in order by the serial
250/// drain. Byte-identical to encoding in the sink: all four are pure functions
251/// of the same geometry.
252pub struct EncodedGeom {
253 kind: GeomKind,
254 bytes: Vec<u8>,
255 bounds: Option<Rect>,
256 ebbx: Option<(i32, i32, i32, i32)>,
257}
258
259impl EncodedGeom {
260 /// Encode a live geometry: what the sink always did inline, exposed so
261 /// callers with no pool pass the same shape the pool-built path does.
262 /// One path, two speeds.
263 pub fn live(geometry: &Geometry) -> Result<EncodedGeom> {
264 let mut bytes = Vec::new();
265 encode_geometry(geometry, &mut bytes)
266 .map_err(|e| osm_ingest::proto::Error(e.to_string()))?;
267 Ok(EncodedGeom {
268 kind: GeomKind::of(geometry),
269 bytes,
270 bounds: geom_bounds(geometry),
271 ebbx: ebbx_of(geometry),
272 })
273 }
274}
275
276/// The sink bbox's e7 box for one geometry: min/max over ALL vertices with
277/// [`Sink::grow`]'s exact conversion.
278///
279/// `bounds` above skips non-finite vertices (matching
280/// [`tile_build::geom::bounds`]); this must not: the old per-vertex walk
281/// folded `(NaN * 1e7) as i32` — which saturates to 0 — so a NaN vertex
282/// contributed 0 to the box. Reproducing the walk exactly (rather than
283/// converting `bounds`' corners) keeps the box identical even where a
284/// shapefile-derived coordinate misbehaves. `None` only when the geometry
285/// holds no vertices at all, in which case the old walk visited nothing and
286/// the box was unchanged.
287fn ebbx_of(geometry: &Geometry) -> Option<(i32, i32, i32, i32)> {
288 let mut acc: Option<(i32, i32, i32, i32)> = None;
289 let mut visit = |&(lon, lat): &(f64, f64)| {
290 let (x, y) = ((lon * 1e7) as i32, (lat * 1e7) as i32);
291 acc = Some(match acc {
292 None => (x, y, x, y),
293 Some(b) => (b.0.min(x), b.1.min(y), b.2.max(x), b.3.max(y)),
294 });
295 };
296 match geometry {
297 Geometry::Points(points) => points.iter().for_each(&mut visit),
298 Geometry::Lines(lines) => lines.iter().flatten().for_each(&mut visit),
299 Geometry::Polygons(polygons) => polygons.iter().flatten().flatten().for_each(&mut visit),
300 }
301 acc
302}
303
304/// Accumulates features into a file, tracking the bounding box as it goes.
305///
306/// The bbox is computed here rather than in a pass of its own, because a pass of its own would be a
307/// sixteenth read of a four-gigabyte file to learn four numbers.
308pub struct Sink {
309 writer: NormalizedWriter,
310 /// The shallowest `min_zoom` in each spill chunk, and the running one for the chunk being filled.
311 ///
312 /// One byte per 64 features — 243 KB on California — and it is what lets the tiler **skip** a
313 /// chunk rather than deserialise it. Every feature carries a `min_zoom` and most are deep: z14
314 /// alone holds 16.9 M against ~5 M across z0..z12. Without this the reader parses the whole
315 /// 2.0 GB spill once per zoom, which measured 55.2 s of a 180 s build back when the spill was
316 /// 3.3 GB, all of it on one thread.
317 chunk_mins: Vec<u8>,
318 filling: u8,
319 props: Vec<(String, Value)>,
320 count: u64,
321 bbox: Option<(i32, i32, i32, i32)>,
322}
323
324include!("store_part1.rs");
325include!("store_part2.rs");
326include!("store_part3.rs");
327include!("store_part4.rs");
328include!("store_part5.rs");
329include!("store_part6.rs");