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

Modern-Apps.git / scripts / maps / tile_build / src / spill.rs

spill.rs454 lines · 16.9 KiBRaw
1//! On-disk spill for the streaming tiler: a record format, and `tile_id`-range buckets.
2//!
3//! [`crate::pyramid::build_archive`] holds every feature and, per zoom, every CLIPPED
4//! copy of every geometry: one per `(feature, tile)` pair, plus the `tile -> candidates`
5//! map that indexes them. So it is proportional to the input bytes and then again to the
6//! zoom's OUTPUT geometry, which is why a `roads` layer — every OSM road, z11-16,
7//! planet-wide — cannot be built by it: the `maxspeed` layer, which is only the ways
8//! carrying a `maxspeed` tag and one zoom shallower, already produces an 8.3 GB archive.
9//!
10//! Holding the clipped copies is what [`crate::subdivide`] costs that path. The old loop
11//! clipped lazily inside the per-tile encode batch and could throw each copy away, but it
12//! paid a full vertex walk per tile to do it — `O(T · V)` for a feature reaching `T`
13//! tiles. Keeping the descent's output instead trades memory for that, and it is the
14//! right trade *here* because this path is the in-memory oracle the byte-identity tests
15//! pin the streaming one against; anything at real scale goes through
16//! [`crate::pyramid::build_archive_to`], which spills these very records to disk.
17//!
18//! This module is the disk that replaces that memory. It follows
19//! `osm_ingest::chains`: manual little-endian encode and decode, a zero-filled reserved
20//! tail so a field can be added without moving anything, counts cross-checked against
21//! file length, and `Drop` cleanup so a run that dies mid-planet cannot strand tens of
22//! gigabytes.
23//!
24//! Two files, for two different jobs:
25//!
26//! * **The normalized file** ([`NormalizedWriter`]) is the geojsonseq parsed exactly
27//! once into a compact binary. Every zoom then re-reads that instead of re-parsing
28//! JSON, which is the cheaper end of a trade that has to be made six times. The same
29//! pass records a fixed-stride offset index ([`NormalizedSummary::chunks`]), so those
30//! re-reads can be spread across the pool via [`NormalizedChunks`] rather than pulled
31//! through one cursor.
32//! * **The buckets** ([`BucketSet`]) hold one record per `(feature, tile)` pair for ONE
33//! zoom, partitioned by `tile_id` range.
34//!
35//! # Why buckets and not an external merge sort
36//!
37//! [`crate::pmtiles::StreamBuilder`] needs tiles in ascending `tile_id`. A bucket index
38//! of `(tile_id - lo) / span` is monotonic in `tile_id` by construction, so consuming
39//! buckets in ascending index, each one internally sorted, yields globally ascending
40//! `tile_id` — which is exactly that precondition, for one write and one read of the
41//! spill. `osm_ingest::graph_build`'s rescan-per-round model would instead re-read the
42//! whole spill once per round, and because Hilbert ranges are spatially local they are
43//! badly skewed: an ocean range is empty and a metro range is enormous, so the round
44//! count would have to be sized for the worst range and the rescan becomes thousands of
45//! full passes. There is no `BinaryHeap` here for the same reason there is none anywhere
46//! else in `scripts/maps`.
47//!
48//! Skew is handled by re-partitioning an oversized bucket over its own id sub-range
49//! rather than by hoping. Sub-buckets ascend within a parent and parents ascend, so the
50//! append-only order holds at every depth.
51//!
52//! # Props are inlined
53//!
54//! A feature touching forty tiles writes its properties forty times. That costs spill
55//! bytes and keeps every read sequential, which is the trade worth making first. The
56//! alternative — properties once in the normalized file plus a fixed-stride index keyed
57//! by `seq`, exactly the `chains.rs` `hdr`+`pts` shape — is what [`SpillRecord::seq`] is
58//! for, and should only be built if a measured run approaches the disk ceiling.
59
60use crate::geom::{Geometry, IPt, IntGeometry, Pt, Rect};
61use crate::mvt::Value;
62use crate::proto::{err, Error, Result};
63use std::fs::File;
64use std::io::{BufReader, BufWriter, Read, Write};
65use std::path::{Path, PathBuf};
66
67/// Bytes of fixed header before a spill record's two variable payloads.
68///
69/// The trailing padding is reserved and written as zero, so a field can be added
70/// without moving the ones already there. A decoder that finds it nonzero is reading
71/// something a newer writer produced, and says so rather than guessing.
72pub const REC_HEADER_BYTES: usize = 48;
73
74/// Bytes of fixed header before a normalized record's two variable payloads.
75pub const NORM_HEADER_BYTES: usize = 16;
76
77/// Property predicate for [`NormalizedChunks::read_into_where`]: keep a feature
78/// whose `(key, value)` properties satisfy it.
79type KeepProps = dyn Fn(&[(String, Value)]) -> bool;
80
81/// Features per entry in the normalized file's chunk index.
82///
83/// The index is what lets the bucket pass read the normalized file across the pool
84/// instead of through one cursor: a worker takes a chunk, reads its byte range
85/// positionally, and decodes the records in it. Records are self-delimiting, so an
86/// offset every `NORM_CHUNK_FEATURES` features is all that is needed — a per-feature
87/// table would cost 64x the memory to save nothing.
88///
89/// 64 is a compromise between two hard constraints. Larger chunks mean fewer tasks
90/// per batch, and the batch is bounded by memory (`par::batch_len()` features), so a
91/// stride of 1024 would leave a 64-core box with four tasks per batch. Smaller chunks
92/// mean more index entries and smaller reads. At 64 the batch is one chunk per thread
93/// at memory parity with the serial path, and the index is 8 bytes per 64 features:
94/// a 200M-feature Europe extract indexes in ~25 MB.
95pub const NORM_CHUNK_FEATURES: u64 = 64;
96
97/// A record longer than this is corruption, not a large feature. The largest plausible
98/// single OSM geometry is a coastline relation at a few million vertices, which is two
99/// orders of magnitude below this.
100const MAX_RECORD_BYTES: u64 = 1 << 30;
101
102/// Which [`Geometry`] variant a record holds.
103///
104/// Stored as a byte so the decoder does not have to infer it, and reused as the
105/// normalized file's summary of the input's geometry kind.
106#[derive(Debug, Clone, Copy, PartialEq, Eq)]
107pub enum GeomKind {
108 Points,
109 Lines,
110 Polygons,
111}
112
113impl GeomKind {
114 fn tag(self) -> u8 {
115 match self {
116 GeomKind::Points => 0,
117 GeomKind::Lines => 1,
118 GeomKind::Polygons => 2,
119 }
120 }
121
122 fn from_tag(tag: u8) -> Result<GeomKind> {
123 match tag {
124 0 => Ok(GeomKind::Points),
125 1 => Ok(GeomKind::Lines),
126 2 => Ok(GeomKind::Polygons),
127 other => err(format!("spill record has geometry kind {other}")),
128 }
129 }
130
131 pub fn of(g: &Geometry) -> GeomKind {
132 match g {
133 Geometry::Points(_) => GeomKind::Points,
134 Geometry::Lines(_) => GeomKind::Lines,
135 Geometry::Polygons(_) => GeomKind::Polygons,
136 }
137 }
138
139 pub fn of_int(g: &IntGeometry) -> GeomKind {
140 match g {
141 IntGeometry::Points(_) => GeomKind::Points,
142 IntGeometry::Lines(_) => GeomKind::Lines,
143 IntGeometry::Polygons(_) => GeomKind::Polygons,
144 }
145 }
146}
147
148// --- little-endian primitives -------------------------------------------------
149
150/// A bounds-checked cursor over a record's bytes.
151///
152/// Every read is fallible, because the bytes come off a disk file that a previous run
153/// may have been killed halfway through writing.
154struct Cur<'a> {
155 b: &'a [u8],
156 i: usize,
157}
158
159impl<'a> Cur<'a> {
160 fn new(b: &'a [u8]) -> Cur<'a> {
161 Cur { b, i: 0 }
162 }
163
164 fn take(&mut self, n: usize) -> Result<&'a [u8]> {
165 let end = self.i.checked_add(n).filter(|e| *e <= self.b.len());
166 match end {
167 Some(end) => {
168 let s = &self.b[self.i..end];
169 self.i = end;
170 Ok(s)
171 }
172 None => err(format!(
173 "spill payload wants {n} byte(s) at offset {} of {}",
174 self.i,
175 self.b.len()
176 )),
177 }
178 }
179
180 fn u8(&mut self) -> Result<u8> {
181 Ok(self.take(1)?[0])
182 }
183
184 fn u32(&mut self) -> Result<u32> {
185 Ok(u32::from_le_bytes(self.take(4)?.try_into().expect("4 bytes")))
186 }
187
188 fn u64(&mut self) -> Result<u64> {
189 Ok(u64::from_le_bytes(self.take(8)?.try_into().expect("8 bytes")))
190 }
191
192 fn i32(&mut self) -> Result<i32> {
193 Ok(i32::from_le_bytes(self.take(4)?.try_into().expect("4 bytes")))
194 }
195
196 fn i64(&mut self) -> Result<i64> {
197 Ok(i64::from_le_bytes(self.take(8)?.try_into().expect("8 bytes")))
198 }
199
200 /// How many bytes the decoder consumed, so the caller can check it against the
201 /// length the header claimed.
202 fn consumed(&self) -> usize {
203 self.i
204 }
205
206 fn at_end(&self) -> bool {
207 self.i == self.b.len()
208 }
209}
210
211fn put_u32(out: &mut Vec<u8>, v: u32) {
212 out.extend_from_slice(&v.to_le_bytes());
213}
214
215fn put_u64(out: &mut Vec<u8>, v: u64) {
216 out.extend_from_slice(&v.to_le_bytes());
217}
218
219fn count(n: usize) -> Result<u32> {
220 u32::try_from(n).map_err(|_| Error(format!("spill cannot encode a count of {n}")))
221}
222
223// --- integer geometry codec ---------------------------------------------------
224
225/// Encode an [`IntGeometry`]. The kind is carried in the record header, so this is only
226/// the shape and the vertices.
227pub fn encode_int_geometry(g: &IntGeometry, out: &mut Vec<u8>) -> Result<()> {
228 let put_ring = |ring: &[IPt], out: &mut Vec<u8>| -> Result<()> {
229 put_u32(out, count(ring.len())?);
230 for (x, y) in ring {
231 out.extend_from_slice(&x.to_le_bytes());
232 out.extend_from_slice(&y.to_le_bytes());
233 }
234 Ok(())
235 };
236 match g {
237 IntGeometry::Points(p) => put_ring(p, out)?,
238 IntGeometry::Lines(lines) => {
239 put_u32(out, count(lines.len())?);
240 for l in lines {
241 put_ring(l, out)?;
242 }
243 }
244 IntGeometry::Polygons(polys) => {
245 put_u32(out, count(polys.len())?);
246 for rings in polys {
247 put_u32(out, count(rings.len())?);
248 for r in rings {
249 put_ring(r, out)?;
250 }
251 }
252 }
253 }
254 Ok(())
255}
256
257fn decode_int_ring(c: &mut Cur) -> Result<Vec<IPt>> {
258 let n = c.u32()? as usize;
259 // Eight bytes a vertex, so a count larger than what is left is corruption rather
260 // than a request to allocate gigabytes.
261 let mut out = Vec::with_capacity(n.min(1 << 16));
262 for _ in 0..n {
263 let x = c.i32()?;
264 let y = c.i32()?;
265 out.push((x, y));
266 }
267 Ok(out)
268}
269
270fn decode_int_geometry(kind: GeomKind, b: &[u8]) -> Result<IntGeometry> {
271 let mut c = Cur::new(b);
272 let g = match kind {
273 GeomKind::Points => IntGeometry::Points(decode_int_ring(&mut c)?),
274 GeomKind::Lines => {
275 let n = c.u32()? as usize;
276 let mut lines = Vec::with_capacity(n.min(1 << 16));
277 for _ in 0..n {
278 lines.push(decode_int_ring(&mut c)?);
279 }
280 IntGeometry::Lines(lines)
281 }
282 GeomKind::Polygons => {
283 let n = c.u32()? as usize;
284 let mut polys = Vec::with_capacity(n.min(1 << 16));
285 for _ in 0..n {
286 let rings_n = c.u32()? as usize;
287 let mut rings = Vec::with_capacity(rings_n.min(1 << 16));
288 for _ in 0..rings_n {
289 rings.push(decode_int_ring(&mut c)?);
290 }
291 polys.push(rings);
292 }
293 IntGeometry::Polygons(polys)
294 }
295 };
296 if !c.at_end() {
297 return err(format!("spill geometry decoded {} of {} byte(s)", c.consumed(), b.len()));
298 }
299 Ok(g)
300}
301
302// --- lon/lat geometry codec ---------------------------------------------------
303
304/// Encode a lon/lat [`Geometry`] for the normalized file, quantised to e7.
305///
306/// **The wire format is [`encode_int_geometry`]'s**, vertex for vertex: the same nested
307/// counts and the same `(i32, i32)` pairs, so [`decode_int_ring`]'s corruption bound
308/// applies here unchanged. It is spelled out again rather than delegated because routing
309/// a read through [`IntGeometry`] would allocate the whole nested geometry a second time
310/// only to convert it, and the normalized file is decoded once per feature per zoom --
311/// fifteen times over a z0-14 build.
312///
313/// # Why quantising is lossless for the data this carries
314///
315/// `osm_ingest`'s node table stores coordinates as `(i32 lat_e7, i32 lon_e7)`, and
316/// `mamaps_build`'s `extract::locate` multiplies by `1e-7` purely to hand `f64` degrees
317/// on. [`crate::pyramid::e7`] recovers the exact integer from that product, so an
318/// OSM-only archive is byte-identical at half the spill bytes.
319///
320/// A shapefile-derived coastline is arbitrary `f64` and IS quantised, to ~1.1 cm. That is
321/// ~1/70th of a z14 tile unit, so it cannot move a pixel, but it does change such an
322/// archive's bytes and so needs its own baseline hash.
323pub fn encode_geometry(g: &Geometry, out: &mut Vec<u8>) -> Result<()> {
324 let put_ring = |ring: &[Pt], out: &mut Vec<u8>| -> Result<()> {
325 put_u32(out, count(ring.len())?);
326 for (x, y) in ring {
327 out.extend_from_slice(&crate::pyramid::e7(*x).to_le_bytes());
328 out.extend_from_slice(&crate::pyramid::e7(*y).to_le_bytes());
329 }
330 Ok(())
331 };
332 match g {
333 Geometry::Points(p) => put_ring(p, out)?,
334 Geometry::Lines(lines) => {
335 put_u32(out, count(lines.len())?);
336 for l in lines {
337 put_ring(l, out)?;
338 }
339 }
340 Geometry::Polygons(polys) => {
341 put_u32(out, count(polys.len())?);
342 for rings in polys {
343 put_u32(out, count(rings.len())?);
344 for r in rings {
345 put_ring(r, out)?;
346 }
347 }
348 }
349 }
350 Ok(())
351}
352
353fn decode_ring(c: &mut Cur) -> Result<Vec<Pt>> {
354 let n = c.u32()? as usize;
355 let mut out = Vec::with_capacity(n.min(1 << 16));
356 for _ in 0..n {
357 let x = c.i32()?;
358 let y = c.i32()?;
359 out.push((x as f64 * 1e-7, y as f64 * 1e-7));
360 }
361 Ok(out)
362}
363
364fn decode_geometry(kind: GeomKind, b: &[u8]) -> Result<Geometry> {
365 let mut c = Cur::new(b);
366 let g = match kind {
367 GeomKind::Points => Geometry::Points(decode_ring(&mut c)?),
368 GeomKind::Lines => {
369 let n = c.u32()? as usize;
370 let mut lines = Vec::with_capacity(n.min(1 << 16));
371 for _ in 0..n {
372 lines.push(decode_ring(&mut c)?);
373 }
374 Geometry::Lines(lines)
375 }
376 GeomKind::Polygons => {
377 let n = c.u32()? as usize;
378 let mut polys = Vec::with_capacity(n.min(1 << 16));
379 for _ in 0..n {
380 let rings_n = c.u32()? as usize;
381 let mut rings = Vec::with_capacity(rings_n.min(1 << 16));
382 for _ in 0..rings_n {
383 rings.push(decode_ring(&mut c)?);
384 }
385 polys.push(rings);
386 }
387 Geometry::Polygons(polys)
388 }
389 };
390 if !c.at_end() {
391 return err(format!("spill geometry decoded {} of {} byte(s)", c.consumed(), b.len()));
392 }
393 Ok(g)
394}
395
396// --- property codec ----------------------------------------------------------
397
398/// Encode a feature's properties.
399///
400/// Not [`crate::mvt`]'s layer encoder, which dictionary-encodes keys and values across a
401/// whole layer. That is the right format for a tile and the wrong one for a record: a
402/// bucket is read one record at a time and has no layer to share a dictionary with.
403pub fn encode_props(props: &[(String, Value)], out: &mut Vec<u8>) -> Result<()> {
404 put_u32(out, count(props.len())?);
405 for (k, v) in props {
406 put_u32(out, count(k.len())?);
407 out.extend_from_slice(k.as_bytes());
408 // Matched exhaustively with no `_` arm on purpose: adding an MVT value type
409 // should break this build rather than silently spill the wrong bytes.
410 match v {
411 Value::String(s) => {
412 out.push(0);
413 put_u32(out, count(s.len())?);
414 out.extend_from_slice(s.as_bytes());
415 }
416 Value::Float(f) => {
417 out.push(1);
418 out.extend_from_slice(&f.to_bits().to_le_bytes());
419 }
420 Value::Double(d) => {
421 out.push(2);
422 out.extend_from_slice(&d.to_bits().to_le_bytes());
423 }
424 Value::Int(i) => {
425 out.push(3);
426 out.extend_from_slice(&i.to_le_bytes());
427 }
428 Value::Uint(u) => {
429 out.push(4);
430 put_u64(out, *u);
431 }
432 Value::SInt(i) => {
433 out.push(5);
434 out.extend_from_slice(&i.to_le_bytes());
435 }
436 Value::Bool(b) => {
437 out.push(6);
438 out.push(u8::from(*b));
439 }
440 }
441 }
442 Ok(())
443}
444
445include!("spill_part1.rs");
446include!("spill_part2.rs");
447include!("spill_part5.rs");
448include!("spill_part6.rs");
449include!("spill_part7.rs");
450#[cfg(test)]
451mod tests {
452 include!("spill_part3.rs");
453 include!("spill_part4.rs");
454}