Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / tile_build / src / spill.rs
spill.rs455 lines · 16.8 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 | |
| 60 | use crate::geom::{Geometry, IPt, IntGeometry, Pt, Rect}; |
| 61 | use crate::mvt::Value; |
| 62 | use crate::proto::{err, Error, Result}; |
| 63 | use std::fs::File; |
| 64 | use std::io::{BufReader, BufWriter, Read, Write}; |
| 65 | use 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. |
| 72 | pub const REC_HEADER_BYTES: usize = 48; |
| 73 | |
| 74 | /// Bytes of fixed header before a normalized record's two variable payloads. |
| 75 | pub const NORM_HEADER_BYTES: usize = 16; |
| 76 | |
| 77 | /// Features per entry in the normalized file's chunk index. |
| 78 | /// |
| 79 | /// The index is what lets the bucket pass read the normalized file across the pool |
| 80 | /// instead of through one cursor: a worker takes a chunk, reads its byte range |
| 81 | /// positionally, and decodes the records in it. Records are self-delimiting, so an |
| 82 | /// offset every `NORM_CHUNK_FEATURES` features is all that is needed — a per-feature |
| 83 | /// table would cost 64x the memory to save nothing. |
| 84 | /// |
| 85 | /// 64 is a compromise between two hard constraints. Larger chunks mean fewer tasks |
| 86 | /// per batch, and the batch is bounded by memory (`par::batch_len()` features), so a |
| 87 | /// stride of 1024 would leave a 64-core box with four tasks per batch. Smaller chunks |
| 88 | /// mean more index entries and smaller reads. At 64 the batch is one chunk per thread |
| 89 | /// at memory parity with the serial path, and the index is 8 bytes per 64 features: |
| 90 | /// a 200M-feature Europe extract indexes in ~25 MB. |
| 91 | pub const NORM_CHUNK_FEATURES: u64 = 64; |
| 92 | |
| 93 | /// A record longer than this is corruption, not a large feature. The largest plausible |
| 94 | /// single OSM geometry is a coastline relation at a few million vertices, which is two |
| 95 | /// orders of magnitude below this. |
| 96 | const MAX_RECORD_BYTES: u64 = 1 << 30; |
| 97 | |
| 98 | /// Which [`Geometry`] variant a record holds. |
| 99 | /// |
| 100 | /// Stored as a byte so the decoder does not have to infer it, and reused as the |
| 101 | /// normalized file's summary of the input's geometry kind. |
| 102 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 103 | pub enum GeomKind { |
| 104 | Points, |
| 105 | Lines, |
| 106 | Polygons, |
| 107 | } |
| 108 | |
| 109 | impl GeomKind { |
| 110 | fn tag(self) -> u8 { |
| 111 | match self { |
| 112 | GeomKind::Points => 0, |
| 113 | GeomKind::Lines => 1, |
| 114 | GeomKind::Polygons => 2, |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | fn from_tag(tag: u8) -> Result<GeomKind> { |
| 119 | match tag { |
| 120 | 0 => Ok(GeomKind::Points), |
| 121 | 1 => Ok(GeomKind::Lines), |
| 122 | 2 => Ok(GeomKind::Polygons), |
| 123 | other => err(format!("spill record has geometry kind {other}")), |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | pub fn of(g: &Geometry) -> GeomKind { |
| 128 | match g { |
| 129 | Geometry::Points(_) => GeomKind::Points, |
| 130 | Geometry::Lines(_) => GeomKind::Lines, |
| 131 | Geometry::Polygons(_) => GeomKind::Polygons, |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | pub fn of_int(g: &IntGeometry) -> GeomKind { |
| 136 | match g { |
| 137 | IntGeometry::Points(_) => GeomKind::Points, |
| 138 | IntGeometry::Lines(_) => GeomKind::Lines, |
| 139 | IntGeometry::Polygons(_) => GeomKind::Polygons, |
| 140 | } |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | // --- little-endian primitives ------------------------------------------------- |
| 145 | |
| 146 | /// A bounds-checked cursor over a record's bytes. |
| 147 | /// |
| 148 | /// Every read is fallible, because the bytes come off a disk file that a previous run |
| 149 | /// may have been killed halfway through writing. |
| 150 | struct Cur<'a> { |
| 151 | b: &'a [u8], |
| 152 | i: usize, |
| 153 | } |
| 154 | |
| 155 | impl<'a> Cur<'a> { |
| 156 | fn new(b: &'a [u8]) -> Cur<'a> { |
| 157 | Cur { b, i: 0 } |
| 158 | } |
| 159 | |
| 160 | fn take(&mut self, n: usize) -> Result<&'a [u8]> { |
| 161 | let end = self.i.checked_add(n).filter(|e| *e <= self.b.len()); |
| 162 | match end { |
| 163 | Some(end) => { |
| 164 | let s = &self.b[self.i..end]; |
| 165 | self.i = end; |
| 166 | Ok(s) |
| 167 | } |
| 168 | None => err(format!( |
| 169 | "spill payload wants {n} byte(s) at offset {} of {}", |
| 170 | self.i, |
| 171 | self.b.len() |
| 172 | )), |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | fn u8(&mut self) -> Result<u8> { |
| 177 | Ok(self.take(1)?[0]) |
| 178 | } |
| 179 | |
| 180 | fn u32(&mut self) -> Result<u32> { |
| 181 | Ok(u32::from_le_bytes(self.take(4)?.try_into().expect("4 bytes"))) |
| 182 | } |
| 183 | |
| 184 | fn u64(&mut self) -> Result<u64> { |
| 185 | Ok(u64::from_le_bytes(self.take(8)?.try_into().expect("8 bytes"))) |
| 186 | } |
| 187 | |
| 188 | fn i32(&mut self) -> Result<i32> { |
| 189 | Ok(i32::from_le_bytes(self.take(4)?.try_into().expect("4 bytes"))) |
| 190 | } |
| 191 | |
| 192 | fn i64(&mut self) -> Result<i64> { |
| 193 | Ok(i64::from_le_bytes(self.take(8)?.try_into().expect("8 bytes"))) |
| 194 | } |
| 195 | |
| 196 | /// How many bytes the decoder consumed, so the caller can check it against the |
| 197 | /// length the header claimed. |
| 198 | fn consumed(&self) -> usize { |
| 199 | self.i |
| 200 | } |
| 201 | |
| 202 | fn at_end(&self) -> bool { |
| 203 | self.i == self.b.len() |
| 204 | } |
| 205 | } |
| 206 | |
| 207 | fn put_u32(out: &mut Vec<u8>, v: u32) { |
| 208 | out.extend_from_slice(&v.to_le_bytes()); |
| 209 | } |
| 210 | |
| 211 | fn put_u64(out: &mut Vec<u8>, v: u64) { |
| 212 | out.extend_from_slice(&v.to_le_bytes()); |
| 213 | } |
| 214 | |
| 215 | fn count(n: usize) -> Result<u32> { |
| 216 | u32::try_from(n).map_err(|_| Error(format!("spill cannot encode a count of {n}"))) |
| 217 | } |
| 218 | |
| 219 | // --- integer geometry codec --------------------------------------------------- |
| 220 | |
| 221 | /// Encode an [`IntGeometry`]. The kind is carried in the record header, so this is only |
| 222 | /// the shape and the vertices. |
| 223 | pub fn encode_int_geometry(g: &IntGeometry, out: &mut Vec<u8>) -> Result<()> { |
| 224 | let put_ring = |ring: &[IPt], out: &mut Vec<u8>| -> Result<()> { |
| 225 | put_u32(out, count(ring.len())?); |
| 226 | for (x, y) in ring { |
| 227 | out.extend_from_slice(&x.to_le_bytes()); |
| 228 | out.extend_from_slice(&y.to_le_bytes()); |
| 229 | } |
| 230 | Ok(()) |
| 231 | }; |
| 232 | match g { |
| 233 | IntGeometry::Points(p) => put_ring(p, out)?, |
| 234 | IntGeometry::Lines(lines) => { |
| 235 | put_u32(out, count(lines.len())?); |
| 236 | for l in lines { |
| 237 | put_ring(l, out)?; |
| 238 | } |
| 239 | } |
| 240 | IntGeometry::Polygons(polys) => { |
| 241 | put_u32(out, count(polys.len())?); |
| 242 | for rings in polys { |
| 243 | put_u32(out, count(rings.len())?); |
| 244 | for r in rings { |
| 245 | put_ring(r, out)?; |
| 246 | } |
| 247 | } |
| 248 | } |
| 249 | } |
| 250 | Ok(()) |
| 251 | } |
| 252 | |
| 253 | fn decode_int_ring(c: &mut Cur) -> Result<Vec<IPt>> { |
| 254 | let n = c.u32()? as usize; |
| 255 | // Eight bytes a vertex, so a count larger than what is left is corruption rather |
| 256 | // than a request to allocate gigabytes. |
| 257 | let mut out = Vec::with_capacity(n.min(1 << 16)); |
| 258 | for _ in 0..n { |
| 259 | let x = c.i32()?; |
| 260 | let y = c.i32()?; |
| 261 | out.push((x, y)); |
| 262 | } |
| 263 | Ok(out) |
| 264 | } |
| 265 | |
| 266 | fn decode_int_geometry(kind: GeomKind, b: &[u8]) -> Result<IntGeometry> { |
| 267 | let mut c = Cur::new(b); |
| 268 | let g = match kind { |
| 269 | GeomKind::Points => IntGeometry::Points(decode_int_ring(&mut c)?), |
| 270 | GeomKind::Lines => { |
| 271 | let n = c.u32()? as usize; |
| 272 | let mut lines = Vec::with_capacity(n.min(1 << 16)); |
| 273 | for _ in 0..n { |
| 274 | lines.push(decode_int_ring(&mut c)?); |
| 275 | } |
| 276 | IntGeometry::Lines(lines) |
| 277 | } |
| 278 | GeomKind::Polygons => { |
| 279 | let n = c.u32()? as usize; |
| 280 | let mut polys = Vec::with_capacity(n.min(1 << 16)); |
| 281 | for _ in 0..n { |
| 282 | let rings_n = c.u32()? as usize; |
| 283 | let mut rings = Vec::with_capacity(rings_n.min(1 << 16)); |
| 284 | for _ in 0..rings_n { |
| 285 | rings.push(decode_int_ring(&mut c)?); |
| 286 | } |
| 287 | polys.push(rings); |
| 288 | } |
| 289 | IntGeometry::Polygons(polys) |
| 290 | } |
| 291 | }; |
| 292 | if !c.at_end() { |
| 293 | return err(format!( |
| 294 | "spill geometry decoded {} of {} byte(s)", |
| 295 | c.consumed(), |
| 296 | b.len() |
| 297 | )); |
| 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. |
| 323 | pub 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 | |
| 353 | fn 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 | |
| 364 | fn 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!( |
| 392 | "spill geometry decoded {} of {} byte(s)", |
| 393 | c.consumed(), |
| 394 | b.len() |
| 395 | )); |
| 396 | } |
| 397 | Ok(g) |
| 398 | } |
| 399 | |
| 400 | // --- property codec ---------------------------------------------------------- |
| 401 | |
| 402 | /// Encode a feature's properties. |
| 403 | /// |
| 404 | /// Not [`crate::mvt`]'s layer encoder, which dictionary-encodes keys and values across a |
| 405 | /// whole layer. That is the right format for a tile and the wrong one for a record: a |
| 406 | /// bucket is read one record at a time and has no layer to share a dictionary with. |
| 407 | pub fn encode_props(props: &[(String, Value)], out: &mut Vec<u8>) -> Result<()> { |
| 408 | put_u32(out, count(props.len())?); |
| 409 | for (k, v) in props { |
| 410 | put_u32(out, count(k.len())?); |
| 411 | out.extend_from_slice(k.as_bytes()); |
| 412 | // Matched exhaustively with no `_` arm on purpose: adding an MVT value type |
| 413 | // should break this build rather than silently spill the wrong bytes. |
| 414 | match v { |
| 415 | Value::String(s) => { |
| 416 | out.push(0); |
| 417 | put_u32(out, count(s.len())?); |
| 418 | out.extend_from_slice(s.as_bytes()); |
| 419 | } |
| 420 | Value::Float(f) => { |
| 421 | out.push(1); |
| 422 | out.extend_from_slice(&f.to_bits().to_le_bytes()); |
| 423 | } |
| 424 | Value::Double(d) => { |
| 425 | out.push(2); |
| 426 | out.extend_from_slice(&d.to_bits().to_le_bytes()); |
| 427 | } |
| 428 | Value::Int(i) => { |
| 429 | out.push(3); |
| 430 | out.extend_from_slice(&i.to_le_bytes()); |
| 431 | } |
| 432 | Value::Uint(u) => { |
| 433 | out.push(4); |
| 434 | put_u64(out, *u); |
| 435 | } |
| 436 | Value::SInt(i) => { |
| 437 | out.push(5); |
| 438 | out.extend_from_slice(&i.to_le_bytes()); |
| 439 | } |
| 440 | Value::Bool(b) => { |
| 441 | out.push(6); |
| 442 | out.push(u8::from(*b)); |
| 443 | } |
| 444 | } |
| 445 | } |
| 446 | Ok(()) |
| 447 | } |
| 448 | |
| 449 | include!("spill_part1.rs"); |
| 450 | include!("spill_part2.rs"); |
| 451 | #[cfg(test)] |
| 452 | mod tests { |
| 453 | include!("spill_part3.rs"); |
| 454 | include!("spill_part4.rs"); |
| 455 | } |