geolith-tiles-builder 0.4.2

Builds tiles from OpenStreetMap and Overture Maps: protomaps-schema vector PMTiles, Terrain-RGB, raster archives and 3D Tiles from Gaussian splats
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
//! The disk the vector build needs, and the check before it starts.
//!
//! The build spills every tile feature into sort chunks, then merges the
//! chunks into the archive. At the end of phase 1 the chunks are whole; while
//! the merge runs, the archive grows. A planet build that runs out of disk
//! after twenty hours loses all of them, so the build asks the file system
//! first and stops with the number of GiB it needs.
//!
//! The sizes are estimates from the size of the inputs. The ratios come from
//! a dense metropolitan extract (1.2 GB of Parquet gave 28 bytes of run per
//! tile feature, 0.46 bytes of run and 0.38 bytes of archive per input byte)
//! and from a planet build (11.1 billion tile features, 197 GiB of archive
//! from 606 GiB of Parquet and PBF, so 0.33). The check adds a margin
//! and is meant to catch the order of magnitude, not the last GiB.
//!
//! Two flags give disk back during the build, and the check counts both:
//! `--reclaim-chunks` frees each chunk as the merge reads it (the peak is the
//! larger of chunks and archive, not their sum), and
//! `--reclaim-source-after-read` deletes each Overture file once it is read.
//! Phase 1 reads Overture first and the OSM PBF second, so every Overture
//! file is gone before the node store is built and before the merge: the
//! bytes of those files come off the peak of the volume they sit on.

use std::path::{Path, PathBuf};

use crate::config::TilesConfig;
use crate::source;
use crate::tiles_error::{Result, TilesError};

const GIB: u64 = 1024 * 1024 * 1024;

/// Bytes of sort chunks per byte of input (Overture Parquet plus OSM PBF).
const CHUNK_PER_INPUT_BYTE: f64 = 0.48;
/// Bytes of archive per byte of input.
const OUTPUT_PER_INPUT_BYTE: f64 = 0.35;
/// Bytes of node store per byte of PBF.
const NODE_STORE_PER_PBF_BYTE: f64 = 1.2;
/// The margin on every estimate.
const MARGIN: f64 = 1.1;
/// Estimated bytes of disk the build takes, by kind.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Estimate {
    /// The sort chunks at the end of phase 1.
    pub chunks: u64,
    /// The finished archive.
    pub output: u64,
    /// The node store, when it has to be built.
    pub node_store: u64,
}

impl Estimate {
    /// The estimate for inputs of `input_bytes` of which `pbf_bytes` are PBF.
    pub(crate) fn for_inputs(input_bytes: u64, pbf_bytes: u64) -> Self {
        let scale = |per_byte: f64, bytes: u64| (per_byte * bytes as f64 * MARGIN) as u64;
        Self {
            chunks: scale(CHUNK_PER_INPUT_BYTE, input_bytes),
            output: scale(OUTPUT_PER_INPUT_BYTE, input_bytes),
            node_store: scale(NODE_STORE_PER_PBF_BYTE, pbf_bytes),
        }
    }
}

/// One volume the build writes to and what it puts there.
#[derive(Debug)]
struct Need {
    /// A path on the volume.
    probe: PathBuf,
    device: u64,
    chunks: u64,
    output: u64,
    node_store: u64,
    /// Bytes of source files on this volume that `--reclaim-source-after-read`
    /// deletes before the peak.
    credit: u64,
    /// Room the build needs before the first source file is deleted, from
    /// [`transient_bytes`]; zero on a volume that holds no source file.
    transient: u64,
}

impl Need {
    /// The bytes on the volume at the peak of the build.
    ///
    /// The chunks and the archive coexist while the merge runs, unless the
    /// merge reclaims each chunk as it reads it: then the chunks shrink as the
    /// archive grows, and the larger of the two is the peak.
    const fn peak(&self, reclaim_chunks: bool) -> u64 {
        let both = if reclaim_chunks {
            if self.chunks > self.output {
                self.chunks
            } else {
                self.output
            }
        } else {
            self.chunks + self.output
        };
        let net = (both + self.node_store).saturating_sub(self.credit);
        if self.credit > 0 && self.chunks > 0 && net < self.transient {
            self.transient
        } else {
            net
        }
    }

    /// What the bytes are for, for the message.
    fn what(&self) -> &'static str {
        match (self.chunks > 0, self.output > 0, self.node_store > 0) {
            (true, true, true) => "sort chunks, output archive and node store",
            (true, true, false) => "sort chunks and output archive",
            (true, false, true) => "sort chunks and node store",
            (false, true, true) => "output archive and node store",
            (true, false, false) => "sort chunks",
            (false, true, false) => "output archive",
            (false, false, true) => "node store",
            (false, false, false) => "nothing",
        }
    }
}

/// Stop with [`TilesError::InsufficientDisk`] when a volume the build writes
/// to has less free space than the estimate says it needs.
///
/// Skipped on platforms that cannot report free space.
///
/// # Errors
///
/// The error names the volume, the GiB needed and the GiB free. Reading the
/// inputs' sizes can fail with the usual I/O or discovery errors.
pub(crate) fn preflight(config: &TilesConfig, tmp_dir: &Path) -> Result<()> {
    let (estimate, reclaimable) = estimate_for(config)?;
    check(
        &needs(config, tmp_dir, estimate, reclaimable),
        config.reclaim_chunks,
        free_bytes,
    )
}

/// The estimate, and the bytes of Overture Parquet the run deletes as it
/// reads them (zero without `--reclaim-source-after-read`).
fn estimate_for(config: &TilesConfig) -> Result<(Estimate, u64)> {
    let mut parquet = 0u64;
    for src in source::discover(config.data.as_path())? {
        if src
            .target_layers
            .iter()
            .any(|&l| config.overture_enabled(l))
        {
            parquet += std::fs::metadata(&src.path)?.len();
        }
    }
    let pbf = match &config.osm_pbf {
        Some(path) => std::fs::metadata(path)?.len(),
        None => 0,
    };
    let reclaimable = if config.reclaim_source_after_read {
        parquet
    } else {
        0
    };
    Ok((Estimate::for_inputs(parquet + pbf, pbf), reclaimable))
}

/// What the build puts on each volume it writes to.
fn needs(config: &TilesConfig, tmp_dir: &Path, estimate: Estimate, reclaimable: u64) -> Vec<Need> {
    let output_dir = config
        .output
        .parent()
        .filter(|p| !p.as_os_str().is_empty())
        .unwrap_or_else(|| Path::new("."));
    let transient = transient_bytes(config, estimate);
    let mut parts: Vec<(&Path, u64, u64, u64, u64, u64)> = vec![
        (tmp_dir, estimate.chunks, 0, 0, 0, 0),
        (output_dir, 0, estimate.output, 0, 0, 0),
        (config.data.as_path(), 0, 0, 0, reclaimable, transient),
    ];
    if let Some(store) = &config.node_store
        && !store.exists()
        && let Some(dir) = store.parent().filter(|p| !p.as_os_str().is_empty())
    {
        parts.push((dir, 0, 0, estimate.node_store, 0, 0));
    }
    let mut needs: Vec<Need> = Vec::new();
    for (path, chunks, output, node_store, credit, part_transient) in parts {
        let probe = existing_ancestor(path);
        let device = device_of(&probe);
        if let Some(same) = needs.iter_mut().find(|n| n.device == device) {
            same.chunks += chunks;
            same.output += output;
            same.node_store += node_store;
            same.credit += credit;
            same.transient = same.transient.max(part_transient);
        } else {
            needs.push(Need {
                probe,
                device,
                chunks,
                output,
                node_store,
                credit,
                transient: part_transient,
            });
        }
    }
    needs
}

/// Room the build holds outside the chunks when `--reclaim-source-after-read`
/// has deleted nothing yet: every worker fills its sort buffer before it flushes
/// a run, so up to `threads × buffer` is in memory and in the run being written.
///
/// It is never more than the data the buffers can hold, which is the chunk
/// estimate: a build whose inputs fit in one buffer never holds a planet's
/// worth of transient room. A fixed floor asked a London-sized build for 64 GiB
/// and failed it on any volume smaller than that (the CI runner has 29 GiB free
/// in `/tmp`).
fn transient_bytes(config: &TilesConfig, estimate: Estimate) -> u64 {
    let threads = config.threads.unwrap_or_else(|| {
        std::thread::available_parallelism()
            .map(|n| n.get())
            .unwrap_or(4)
    });
    let buffers =
        (threads as u128 * config.effective_chunk_bytes() as u128).min(u128::from(u64::MAX)) as u64;
    buffers.min(estimate.chunks)
}

fn check(needs: &[Need], reclaim_chunks: bool, free: impl Fn(&Path) -> Option<u64>) -> Result<()> {
    for need in needs {
        let Some(available) = free(&need.probe) else {
            continue;
        };
        let bytes = need.peak(reclaim_chunks);
        if available < bytes {
            return Err(TilesError::InsufficientDisk {
                path: need.probe.clone(),
                need_gib: bytes.div_ceil(GIB),
                free_gib: available / GIB,
                what: need.what(),
                reclaim_chunks,
            });
        }
    }
    Ok(())
}

/// The nearest ancestor of `path` that exists: the volume a new directory
/// would land on.
fn existing_ancestor(path: &Path) -> PathBuf {
    let absolute = std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf());
    absolute
        .ancestors()
        .find(|p| p.exists())
        .map_or_else(|| PathBuf::from("/"), Path::to_path_buf)
}

#[cfg(unix)]
fn device_of(path: &Path) -> u64 {
    use std::os::unix::fs::MetadataExt;
    std::fs::metadata(path).map_or(0, |m| m.dev())
}

#[cfg(not(unix))]
fn device_of(_path: &Path) -> u64 {
    0
}

#[cfg(unix)]
#[allow(
    unsafe_code,
    clippy::useless_conversion,
    clippy::unnecessary_cast,
    reason = "statvfs fills a MaybeUninit; its field widths differ by platform"
)]
fn free_bytes(path: &Path) -> Option<u64> {
    use std::os::unix::ffi::OsStrExt;
    let c_path = std::ffi::CString::new(path.as_os_str().as_bytes()).ok()?;
    let mut stat = std::mem::MaybeUninit::<libc::statvfs>::uninit();
    // SAFETY: `c_path` is a NUL-terminated path and `stat` is a valid
    // out-pointer for one `statvfs`.
    let result = unsafe { libc::statvfs(c_path.as_ptr(), stat.as_mut_ptr()) };
    if result != 0 {
        return None;
    }
    // SAFETY: statvfs returned 0, so it filled `stat`.
    let stat = unsafe { stat.assume_init() };
    Some(u64::from(stat.f_bavail) * (stat.f_frsize as u64))
}

#[cfg(not(unix))]
fn free_bytes(_path: &Path) -> Option<u64> {
    None
}

#[cfg(test)]
mod tests {
    use super::*;

    fn config(output: &Path, reclaim: bool) -> TilesConfig {
        let mut config = TilesConfig::new("/data", "/ne", "/w", "/l", output);
        config.reclaim_chunks = reclaim;
        config
    }

    /// The floor of a planet-sized build: 32 workers with a 2 GiB buffer each.
    const PLANET_TRANSIENT: u64 = 64 * GIB;

    fn need(chunks: u64, output: u64) -> Need {
        Need {
            probe: PathBuf::from("/vol"),
            device: 1,
            chunks,
            output,
            node_store: 0,
            credit: 0,
            transient: PLANET_TRANSIENT,
        }
    }

    #[test]
    fn the_estimate_scales_with_the_inputs_and_carries_the_margin() {
        // 0.48, 0.35 and 1.2 bytes per input byte, each with the 10 % margin:
        // 1000 GiB of input and 100 GiB of PBF give 528, 385 and 132 GiB.
        let e = Estimate::for_inputs(1000 * GIB, 100 * GIB);
        let near = |got: u64, gib: u64| got.abs_diff(gib * GIB) < GIB / 1000;
        assert!(near(e.chunks, 528), "{}", e.chunks);
        assert!(near(e.output, 385), "{}", e.output);
        assert!(near(e.node_store, 132), "{}", e.node_store);
    }

    #[test]
    fn chunks_and_archive_add_up_unless_the_merge_reclaims() {
        let n = need(200 * GIB, 190 * GIB);
        assert_eq!(n.peak(false), 390 * GIB);
        assert_eq!(n.peak(true), 200 * GIB);
    }

    #[test]
    fn one_volume_holds_what_the_build_puts_there() {
        let dir = tempfile::tempdir().expect("tmpdir");
        let est = Estimate {
            chunks: 200 * GIB,
            output: 190 * GIB,
            node_store: 100 * GIB,
        };
        let mut config = config(&dir.path().join("out.pmtiles"), false);
        config.node_store = Some(dir.path().join("nodes.store"));
        let n = needs(&config, &dir.path().join("sort"), est, 0);
        assert_eq!(n.len(), 1, "same volume folds to one need");
        assert_eq!(n[0].peak(false), 490 * GIB);
        assert_eq!(n[0].peak(true), 300 * GIB);
        assert_eq!(n[0].what(), "sort chunks, output archive and node store");
    }

    #[test]
    fn a_short_volume_stops_the_build_and_names_the_gib() {
        let err =
            check(&[need(300 * GIB + 1, 0)], false, |_| Some(100 * GIB)).expect_err("short volume");
        match err {
            TilesError::InsufficientDisk {
                need_gib,
                free_gib,
                what,
                ..
            } => {
                assert_eq!(need_gib, 301);
                assert_eq!(free_gib, 100);
                assert_eq!(what, "sort chunks");
            }
            other => panic!("wrong error: {other}"),
        }
    }

    #[test]
    fn enough_free_space_passes_and_an_unknown_volume_is_skipped() {
        assert!(check(&[need(10 * GIB, 0)], false, |_| Some(100 * GIB)).is_ok());
        assert!(check(&[need(u64::MAX / 2, 0)], false, |_| None).is_ok());
    }

    #[test]
    fn the_temp_dir_reports_free_space() {
        #[cfg(unix)]
        assert!(free_bytes(&std::env::temp_dir()).is_some_and(|b| b > 0));
    }

    /// The planet build of 29 Nov: 516 GiB of Overture Parquet and 90 GiB of
    /// PBF, all on one volume. Worked by hand with the 10 % margin: chunks
    /// 0.48 x 606 x 1.1 = 319.97 GiB, archive 0.35 x 606 x 1.1 = 233.31 GiB,
    /// node store 1.2 x 90 x 1.1 = 118.8 GiB.
    fn planet_need(
        dir: &Path,
        reclaim_chunks: bool,
        reclaim_sources: bool,
    ) -> std::result::Result<(), (u64, u64)> {
        let mut config = config(&dir.join("out.pmtiles"), reclaim_chunks);
        config.data = dir.join("overture");
        config.node_store = Some(dir.join("nodes.store"));
        let estimate = Estimate::for_inputs(606 * GIB, 90 * GIB);
        let credit = if reclaim_sources { 516 * GIB } else { 0 };
        let n = needs(&config, &dir.join("sort"), estimate, credit);
        assert_eq!(n.len(), 1, "one volume");
        match check(&n, reclaim_chunks, |_| Some(150 * GIB)) {
            Ok(()) => Ok(()),
            Err(TilesError::InsufficientDisk {
                need_gib, free_gib, ..
            }) => Err((need_gib, free_gib)),
            Err(other) => panic!("wrong error: {other}"),
        }
    }

    #[test]
    fn the_planet_needs_what_each_reclaim_flag_leaves() {
        let dir = tempfile::tempdir().expect("tmpdir");
        let p = dir.path();
        // 319.97 + 233.31 + 118.8 = 672.08 GiB
        assert_eq!(planet_need(p, false, false), Err((673, 150)));
        // max(319.97, 233.31) + 118.8 = 438.77 GiB
        assert_eq!(planet_need(p, true, false), Err((439, 150)));
        // 672.08 - 516 = 156.08 GiB: still more than 150 free
        assert_eq!(planet_need(p, false, true), Err((157, 150)));
        // 438.77 - 516 < 0: the sources freed cover the whole peak
        assert_eq!(planet_need(p, true, true), Ok(()));
    }

    #[test]
    fn a_source_credit_never_takes_the_peak_below_the_floor() {
        let mut n = need(10 * GIB, 0);
        n.credit = 500 * GIB;
        assert_eq!(n.peak(false), PLANET_TRANSIENT);
        // A volume that holds only the sources has nothing to write.
        let mut sources_only = need(0, 0);
        sources_only.credit = 500 * GIB;
        assert_eq!(sources_only.peak(false), 0);
    }

    #[test]
    fn only_a_reclaiming_build_counts_its_sources_as_freed() {
        let dir = tempfile::tempdir().expect("tmpdir");
        let part = dir.path().join("theme=buildings/type=building");
        std::fs::create_dir_all(&part).expect("dirs");
        std::fs::write(part.join("a.parquet"), vec![0u8; 1000]).expect("write");
        std::fs::write(part.join("b.parquet"), vec![0u8; 234]).expect("write");
        let mut config = config(&dir.path().join("out.pmtiles"), false);
        config.data = dir.path().to_path_buf();
        assert_eq!(estimate_for(&config).expect("estimate").1, 0);
        config.reclaim_source_after_read = true;
        assert_eq!(estimate_for(&config).expect("estimate").1, 1234);
    }

    /// With `--reclaim-source-after-read` the credit can cover the whole peak
    /// (the planet: 516 GiB of Overture against a 439 GiB peak). The check must
    /// still ask for room to start: every thread fills a sort buffer and
    /// writes runs before the first source file is deleted.
    #[test]
    fn a_credit_that_covers_the_peak_still_leaves_room_to_start() {
        let mut n = need(320 * GIB, 233 * GIB);
        n.node_store = 119 * GIB;
        n.credit = 516 * GIB;
        assert_eq!(n.peak(true), PLANET_TRANSIENT, "the floor, not zero");
        let err = check(&[need_with(&n)], true, |_| Some(40 * GIB)).expect_err("40 GiB free");
        match err {
            TilesError::InsufficientDisk {
                need_gib, free_gib, ..
            } => assert_eq!((need_gib, free_gib), (64, 40)),
            other => panic!("wrong error: {other}"),
        }
        assert!(check(&[need_with(&n)], true, |_| Some(70 * GIB)).is_ok());
    }

    #[test]
    fn without_a_credit_the_peak_is_not_raised_to_the_floor() {
        let n = need(10 * GIB, 0);
        assert_eq!(n.peak(false), 10 * GIB);
    }

    fn need_with(n: &Need) -> Need {
        Need {
            probe: n.probe.clone(),
            device: n.device,
            chunks: n.chunks,
            output: n.output,
            node_store: n.node_store,
            credit: n.credit,
            transient: n.transient,
        }
    }

    /// The floor is the buffers the build will fill, and never more than the
    /// data it has: a build of a few megabytes of Overture does not ask a volume
    /// for 64 GiB because it also reclaims its sources.
    #[test]
    fn the_transient_floor_is_the_buffers_the_build_fills() {
        let dir = tempfile::tempdir().expect("tmpdir");
        let mut config = config(&dir.path().join("out.pmtiles"), false);
        config.threads = Some(4);
        config.chunk_size_mb = 64;
        let small = Estimate {
            chunks: 3 * 1024 * 1024,
            output: 2 * 1024 * 1024,
            node_store: 0,
        };
        assert_eq!(
            transient_bytes(&config, small),
            3 * 1024 * 1024,
            "never more than the chunks the build writes"
        );
        let planet = Estimate {
            chunks: 300 * GIB,
            output: 200 * GIB,
            node_store: 100 * GIB,
        };
        assert_eq!(
            transient_bytes(&config, planet),
            4 * 64 * 1024 * 1024,
            "4 workers x 64 MB"
        );
    }

    /// The London build of the pipeline tests: 3 MiB of chunks, 2 MiB of
    /// archive, every source reclaimable. The credit covers the peak, so the
    /// need is the floor, and the floor is what the buffers hold, not 64 GiB.
    #[test]
    fn a_small_build_is_not_asked_for_a_planets_transient_room() {
        let dir = tempfile::tempdir().expect("tmpdir");
        let est = Estimate {
            chunks: 3 * 1024 * 1024,
            output: 2 * 1024 * 1024,
            node_store: 0,
        };
        let mut config = config(&dir.path().join("out.pmtiles"), false);
        config.reclaim_source_after_read = true;
        config.threads = Some(4);
        config.chunk_size_mb = 64;
        let n = needs(&config, &dir.path().join("sort"), est, 3 * 1024 * 1024);
        assert_eq!(n.len(), 1, "same volume folds to one need");
        assert_eq!(n[0].peak(false), 3 * 1024 * 1024);
        assert!(
            check(&n, false, |_| Some(11 * GIB),).is_ok(),
            "11 GiB free is enough for a 3 MiB build"
        );
    }
}