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

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

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