Modern Apps git

← Modern-Apps.git

maps: stream and thread the tile build, byte-identically

Commit
0ef2bd1d1038762232c378fbb2c10ad8c1fe9d17
Author
vayun-mathur <[email protected]>
When
2026-08-26 02:11 UTC (3 months ago)
Parents
9d759d1

Diff

scripts/maps/tile_build/Cargo.lock
diff --git a/scripts/maps/tile_build/Cargo.lock b/scripts/maps/tile_build/Cargo.lockindex 6cd31447df..bf7612ab23 100644--- a/scripts/maps/tile_build/Cargo.lock+++ b/scripts/maps/tile_build/Cargo.lock@@ -8,6 +8,37 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" +[[package]]+name = "crossbeam-deque"+version = "0.8.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5181e0de7b61eb03a81e347d6dd8797bae9da5146707b51077e2d71a54ec0ceb"+dependencies = [+ "crossbeam-epoch",+ "crossbeam-utils",+]++[[package]]+name = "crossbeam-epoch"+version = "0.9.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f"+dependencies = [+ "crossbeam-utils",+]++[[package]]+name = "crossbeam-utils"+version = "0.8.22"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17"++[[package]]+name = "either"+version = "1.17.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9e5e8f6c15a24b9a3ee5efec809ccd006d3b30e8b3bb63c39af737c7f87daa1d"+ [[package]] name = "miniz_oxide" version = "0.8.9"@@ -17,9 +48,30 @@ dependencies = [  "adler2", ] +[[package]]+name = "rayon"+version = "1.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"+dependencies = [+ "either",+ "rayon-core",+]++[[package]]+name = "rayon-core"+version = "1.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"+dependencies = [+ "crossbeam-deque",+ "crossbeam-utils",+]+ [[package]] name = "tile_build" version = "0.1.0" dependencies = [  "miniz_oxide",+ "rayon", ]
scripts/maps/tile_build/Cargo.toml
diff --git a/scripts/maps/tile_build/Cargo.toml b/scripts/maps/tile_build/Cargo.tomlindex c3e133533f..1a386495cc 100644--- a/scripts/maps/tile_build/Cargo.toml+++ b/scripts/maps/tile_build/Cargo.toml@@ -8,13 +8,21 @@ # Deliberately DETACHED from the Android Rust workspace (the empty [workspace] # table below), exactly like `scripts/maps/gtfs_ingest` and # `scripts/maps/osm_ingest`: it is a host binary, so `cargo build` here never-# pulls the aarch64-android toolchain or the app crates' lints. Its single-# dependency, `miniz_oxide`, is pure Rust and already in the local registry cache-# (osm_ingest and the app's maps crate both pull it), so builds resolve offline.+# pulls the aarch64-android toolchain or the app crates' lints. #-# NOTE: unlike osm_ingest, this crate needs miniz_oxide's DEFLATE side too ---# PMTiles gzips both its directories and its tiles, so we compress as well as-# decompress.+# Both dependencies are pure Rust and no C toolchain is involved:+#+#   miniz_oxide  inflate AND deflate. Unlike osm_ingest, this crate needs the+#                DEFLATE side too -- PMTiles gzips both its directories and its+#                tiles, so we compress as well as decompress.+#   rayon        the tilers' work-stealing pool. Level-9 DEFLATE inside+#                `pyramid::fit_tile` is where a layer build spends ~90% of its+#                wall clock, and it is per-tile pure, so it threads.+#+# `cargo build --offline` resolves both from the local registry cache, along with+# rayon's own tree (rayon-core, crossbeam-deque, crossbeam-utils, crossbeam-epoch,+# either). That is a statement about THIS box's cache, not a guarantee: a clean+# machine needs one online `cargo fetch` before it can build offline. [package] name = "tile_build" version = "0.1.0"@@ -45,6 +53,7 @@ name = "pmtiles_extract" path = "src/bin/pmtiles_extract.rs" [dependencies] miniz_oxide = "0.8"+rayon = "1" [profile.release] opt-level = 3 # Detach from the repo-root workspace so this host tool builds standalone/offline.
scripts/maps/tile_build/bench/gen_roads.py
diff --git a/scripts/maps/tile_build/bench/gen_roads.py b/scripts/maps/tile_build/bench/gen_roads.pynew file mode 100644index 0000000000..39a107c34c--- /dev/null+++ b/scripts/maps/tile_build/bench/gen_roads.py@@ -0,0 +1,59 @@+"""Generate a roads-like or POI-like GeoJSONSeq for benchmarking the tilers.++Not a fixture: nothing asserts against this. It exists so the per-phase+performance gate has an input with the shape that matters -- many short polylines+(or many points) spread over a wide area, which is what makes the tile count large+and the spill non-trivial. A handful of long lines would measure the wrong thing.++  python gen_roads.py 200000 bench_roads.geojsonseq lines+  python gen_roads.py 200000 bench_pois.geojsonseq  points+"""++import json+import random+import sys++count = int(sys.argv[1]) if len(sys.argv) > 1 else 200_000+out = sys.argv[2] if len(sys.argv) > 2 else "bench_roads.geojsonseq"+kind = sys.argv[3] if len(sys.argv) > 3 else "lines"+if kind not in ("lines", "points"):+    raise SystemExit(f"kind must be 'lines' or 'points', not {kind!r}")++rng = random.Random(20260826)++# Roughly California's box, so the zoom range the real roads layer uses is honest.+LON0, LON1 = -124.4, -114.1+LAT0, LAT1 = 32.5, 42.0++CLASSES = ["motorway", "trunk", "primary", "secondary", "tertiary", "residential"]++with open(out, "w", encoding="utf-8", newline="\n") as f:+    for i in range(count):+        lon = rng.uniform(LON0, LON1)+        lat = rng.uniform(LAT0, LAT1)+        if kind == "points":+            geometry = {"type": "Point", "coordinates": [round(lon, 7), round(lat, 7)]}+        else:+            # 2-8 vertices, each a short hop, so a feature covers a few tiles at z16+            # rather than thousands.+            n = rng.randint(2, 8)+            coords = []+            for _ in range(n):+                coords.append([round(lon, 7), round(lat, 7)])+                lon += rng.uniform(-0.004, 0.004)+                lat += rng.uniform(-0.004, 0.004)+            geometry = {"type": "LineString", "coordinates": coords}+        feature = {+            "type": "Feature",+            "geometry": geometry,+            "properties": {+                "class": CLASSES[i % len(CLASSES)],+                "name": f"Road {i}",+                "lanes": 1 + (i % 4),+                "maxspeed": 25 + 5 * (i % 13),+            },+        }+        f.write(json.dumps(feature, separators=(",", ":")))+        f.write("\n")++print(f"wrote {count} {kind} feature(s) to {out}")
scripts/maps/tile_build/bench/measure.ps1
diff --git a/scripts/maps/tile_build/bench/measure.ps1 b/scripts/maps/tile_build/bench/measure.ps1new file mode 100644index 0000000000..a7022c5225--- /dev/null+++ b/scripts/maps/tile_build/bench/measure.ps1@@ -0,0 +1,86 @@+# Wall clock and PEAK working set for one tiler run, at a given thread count.+#+# Peak RSS is the number that matters as much as wall clock: a phase that gets+# faster while multiplying peak memory by the thread count has not succeeded. The+# .NET Process object is used rather than Measure-Command because only it exposes+# PeakWorkingSet64.+param(+    [Parameter(Mandatory = $true)][string] $Bin,+    [Parameter(Mandatory = $true)][string] $Geojson,+    [int[]] $Threads = @(1, 32),+    [int] $MinZoom = 11,+    [int] $MaxZoom = 16,+    [switch] $Stream+)++$ErrorActionPreference = "Stop"+$here = Split-Path -Parent $MyInvocation.MyCommand.Path+$exe = Join-Path $here "../target/release/$Bin.exe"+if (-not (Test-Path $exe)) { throw "build it first: cargo build --release ($exe)" }++# Scratch goes to the system temp dir, not into the repo: the outputs are hundreds of+# MB and the spill is larger still, and neither belongs anywhere git has to think+# about. Only this script and gen_roads.py live under bench/.+$work = Join-Path ([System.IO.Path]::GetTempPath()) "tile_build_bench_$PID"+New-Item -ItemType Directory -Force -Path $work | Out-Null++try {+$results = @()+foreach ($n in $Threads) {+    $out = Join-Path $work "out_$n.pmtiles"+    $spill = Join-Path $work "spill_$n"+    Remove-Item -Recurse -Force $out, $spill -ErrorAction SilentlyContinue++    $argv = @("--geojson", $Geojson, "--out", $out, "--layer", "roads",+              "--minzoom", "$MinZoom", "--maxzoom", "$MaxZoom", "--threads", "$n")+    if ($Stream) { $argv += @("--stream", "--spill-dir", $spill) }++    $psi = New-Object System.Diagnostics.ProcessStartInfo+    $psi.FileName = (Resolve-Path $exe).Path+    foreach ($a in $argv) { $psi.ArgumentList.Add($a) }+    $psi.RedirectStandardOutput = $true+    $psi.RedirectStandardError = $true+    $psi.UseShellExecute = $false++    $sw = [System.Diagnostics.Stopwatch]::StartNew()+    $p = [System.Diagnostics.Process]::Start($psi)+    # Drained on background tasks so a full pipe buffer cannot deadlock the child.+    $so = $p.StandardOutput.ReadToEndAsync()+    $se = $p.StandardError.ReadToEndAsync()+    # Polled while the child is alive: PeakWorkingSet64 reads 0 once a process has+    # exited, so sampling after WaitForExit measures nothing at all.+    $peak = 0L+    while (-not $p.HasExited) {+        try { $p.Refresh(); if ($p.PeakWorkingSet64 -gt $peak) { $peak = $p.PeakWorkingSet64 } } catch { }+        Start-Sleep -Milliseconds 20+    }+    $p.WaitForExit()+    $sw.Stop()+    $null = $so.Result; $err = $se.Result++    if ($p.ExitCode -ne 0) { Write-Host $err; throw "$Bin exited $($p.ExitCode) at --threads $n" }++    $results += [pscustomobject]@{+        Threads    = $n+        Seconds    = [math]::Round($sw.Elapsed.TotalSeconds, 1)+        PeakRssMiB = [math]::Round($peak / 1MB, 1)+        OutMiB     = [math]::Round((Get-Item $out).Length / 1MB, 1)+        Sha256     = (Get-FileHash $out -Algorithm SHA256).Hash.Substring(0, 16)+    }+    Remove-Item -Recurse -Force $spill -ErrorAction SilentlyContinue+}++$results | Format-Table -AutoSize++$hashes = $results.Sha256 | Sort-Object -Unique+if ($hashes.Count -ne 1) {+    throw "THREAD COUNT CHANGED THE OUTPUT: $($results.Sha256 -join ', ')"+}+Write-Host "all $($results.Count) run(s) byte-identical (sha256 $($hashes[0])...)"+$base = $results | Where-Object { $_.Threads -eq $results[0].Threads }+Write-Host ("speedup vs {0} thread(s): {1}" -f $results[0].Threads,+    (($results | ForEach-Object { "{0}t {1:N2}x" -f $_.Threads, ($base.Seconds / $_.Seconds) }) -join "  "))+}+finally {+    Remove-Item -Recurse -Force $work -ErrorAction SilentlyContinue+}
scripts/maps/tile_build/src/bin/pmtiles_dump.rs
diff --git a/scripts/maps/tile_build/src/bin/pmtiles_dump.rs b/scripts/maps/tile_build/src/bin/pmtiles_dump.rsindex a2d7c1e2b1..97bd147b5c 100644--- a/scripts/maps/tile_build/src/bin/pmtiles_dump.rs+++ b/scripts/maps/tile_build/src/bin/pmtiles_dump.rs@@ -17,10 +17,15 @@ //!            what `diff_pmtiles.py` reads. //!   tiles    one line per (z/x/y, layer). Verbose, for chasing a single tile. //!   header   the archive header fields, one per line.+//!+//! The archive is opened rather than read: `--mode header` costs a 127-byte read, and+//! the other modes hold one tile body plus a 12-byte row per tile. Dumping a planet+//! layer used to mean an 8 GB allocation before the first line of output.  use std::collections::{BTreeMap, BTreeSet}; use std::process::ExitCode; use tile_build::mvt::{GeomType, Tile};+use tile_build::pmtiles::ArchiveFile; use tile_build::{gz, pmtiles};  fn main() -> ExitCode {@@ -77,23 +82,14 @@ fn main() -> ExitCode {         return ExitCode::from(2);     } -    let bytes = match std::fs::read(&input) {-        Ok(b) => b,-        Err(e) => {-            eprintln!("pmtiles_dump: cannot read {input}: {e}");-            return ExitCode::FAILURE;-        }-    };-    let archive = match pmtiles::Archive::parse(&bytes) {-        Ok(a) => a,-        Err(e) => {-            eprintln!("pmtiles_dump: {input} is not a readable PMTiles archive: {e}");-            return ExitCode::FAILURE;-        }-    };-     if mode == "header" {-        let h = &archive.header;+        let h = match ArchiveFile::read_header(&input) {+            Ok(h) => h,+            Err(e) => {+                eprintln!("pmtiles_dump: {input} is not a readable PMTiles archive: {e}");+                return ExitCode::FAILURE;+            }+        };         println!("min_zoom\t{}", h.min_zoom);         println!("max_zoom\t{}", h.max_zoom);         println!("addressed_tiles\t{}", h.addressed_tiles);@@ -109,23 +105,41 @@ fn main() -> ExitCode {         return ExitCode::SUCCESS;     } -    let tiles = match archive.iter_tiles() {-        Ok(t) => t,+    let mut archive = match ArchiveFile::open(&input) {+        Ok(a) => a,         Err(e) => {-            eprintln!("pmtiles_dump: cannot walk the tile directory: {e}");+            eprintln!("pmtiles_dump: {input} is not a readable PMTiles archive: {e}");             return ExitCode::FAILURE;         }     };+    let compression = archive.header.tile_compression;++    // Runs expanded, so a run of identical ocean tiles is still counted once per tile.+    let mut rows: Vec<(u64, u64, u32)> = Vec::new();+    if let Err(e) = archive.visit_entries(&mut |e| {+        for k in 0..e.run_length as u64 {+            rows.push((e.tile_id + k, e.offset, e.length));+        }+        Ok(())+    }) {+        eprintln!("pmtiles_dump: cannot walk the tile directory: {e}");+        return ExitCode::FAILURE;+    }      // (zoom, layer) -> accumulator, ordered by BTreeMap so the output is sorted     // without a separate sort step.     let mut agg: BTreeMap<(u8, String), Agg> = BTreeMap::new();     let mut undecodable = 0usize;+    let mut body = Vec::new(); -    for (id, body) in tiles {-        let (z, x, y) = pmtiles::tile_zxy(id);-        let raw = if archive.header.tile_compression == pmtiles::COMPRESSION_GZIP {-            match gz::decompress(body) {+    for (id, off, len) in &rows {+        let (z, x, y) = pmtiles::tile_zxy(*id);+        if let Err(e) = archive.body_into(*off, *len, &mut body) {+            eprintln!("pmtiles_dump: z{z}/{x}/{y}: {e}");+            return ExitCode::FAILURE;+        }+        let raw = if compression == pmtiles::COMPRESSION_GZIP {+            match gz::decompress(&body) {                 Ok(v) => v,                 Err(e) => {                     eprintln!("pmtiles_dump: z{z}/{x}/{y}: {e}");@@ -134,7 +148,7 @@ fn main() -> ExitCode {                 }             }         } else {-            body.to_vec()+            body.clone()         };         let tile = match Tile::decode(&raw) {             Ok(t) => t,
scripts/maps/tile_build/src/bin/pmtiles_extract.rs
diff --git a/scripts/maps/tile_build/src/bin/pmtiles_extract.rs b/scripts/maps/tile_build/src/bin/pmtiles_extract.rsindex a90c8668e1..a0955971ad 100644--- a/scripts/maps/tile_build/src/bin/pmtiles_extract.rs+++ b/scripts/maps/tile_build/src/bin/pmtiles_extract.rs@@ -28,15 +28,16 @@ //! //! ## Memory //!-//! The input is read wholly into memory, like `tile_join`. That is fine for-//! subsetting an overlay and **not** fine for the 1.5 GB published basemap: do that-//! on a machine with the RAM for it. Making it streaming means a random-access-//! reader over the directory tree, which is a different program.+//! The input is opened, not read: only its root directory, its metadata, one tile body+//! and a 12-byte row per tile are held, so subsetting the 1.5 GB published basemap no+//! longer needs the RAM to hold it. The OUTPUT still goes through [`Builder`], which+//! does hold every kept tile — so extracting most of a planet archive is still out of+//! reach, and that is now the only ceiling.  use std::collections::BTreeSet; use std::process::ExitCode; use tile_build::mvt::Tile;-use tile_build::pmtiles::{self, Archive, Builder};+use tile_build::pmtiles::{self, Archive, ArchiveFile, Builder};  fn main() -> ExitCode {     let argv: Vec<String> = std::env::args().skip(1).collect();@@ -129,27 +130,27 @@ fn main() -> ExitCode {         }     } -    let bytes = match std::fs::read(&input) {-        Ok(b) => b,-        Err(e) => {-            eprintln!("pmtiles_extract: cannot read {input}: {e}");-            return ExitCode::FAILURE;-        }-    };-    let archive = match Archive::parse(&bytes) {+    let mut archive = match ArchiveFile::open(&input) {         Ok(a) => a,         Err(e) => {             eprintln!("pmtiles_extract: {input} is not a readable PMTiles archive: {e}");             return ExitCode::FAILURE;         }     };-    let tiles = match archive.iter_tiles() {-        Ok(t) => t,-        Err(e) => {-            eprintln!("pmtiles_extract: cannot walk the tile directory: {e}");-            return ExitCode::FAILURE;+    let source_bytes = std::fs::metadata(&input).map(|m| m.len()).unwrap_or(0);+    let compression = archive.header.tile_compression;+    // Runs expanded: a run means several ids share one body and each id is its own tile+    // in the subset.+    let mut rows: Vec<(u64, u64, u32)> = Vec::new();+    if let Err(e) = archive.visit_entries(&mut |e| {+        for k in 0..e.run_length as u64 {+            rows.push((e.tile_id + k, e.offset, e.length));         }-    };+        Ok(())+    }) {+        eprintln!("pmtiles_extract: cannot walk the tile directory: {e}");+        return ExitCode::FAILURE;+    }      let lo = min_zoom.unwrap_or(archive.header.min_zoom);     let hi = max_zoom.unwrap_or(archive.header.max_zoom);@@ -183,9 +184,10 @@ fn main() -> ExitCode {     let mut dropped_bbox = 0usize;     let mut dropped_layer = 0usize;     let mut seen_layers: BTreeSet<String> = BTreeSet::new();+    let mut body = Vec::new(); -    for (id, body) in tiles {-        let (z, x, y) = pmtiles::tile_zxy(id);+    for (id, off, len) in &rows {+        let (z, x, y) = pmtiles::tile_zxy(*id);         if z < lo || z > hi {             dropped_zoom += 1;             continue;@@ -196,16 +198,22 @@ fn main() -> ExitCode {                 continue;             }         }+        // Read only after the cheap filters, so a bbox subset does not touch the bodies+        // it is about to discard.+        if let Err(e) = archive.body_into(*off, *len, &mut body) {+            eprintln!("pmtiles_extract: z{z}/{x}/{y}: {e}");+            return ExitCode::FAILURE;+        }         if layers.is_empty() {             // Nothing to filter: copy the compressed body straight across, so the             // subset is byte-identical to the source for every tile it keeps.-            builder.add_tile_raw(id, body.to_vec());+            builder.add_tile_raw(*id, body.clone());             kept += 1;             continue;         } -        let raw = if archive.header.tile_compression == pmtiles::COMPRESSION_GZIP {-            match tile_build::gz::decompress(body) {+        let raw = if compression == pmtiles::COMPRESSION_GZIP {+            match tile_build::gz::decompress(&body) {                 Ok(v) => v,                 Err(e) => {                     eprintln!("pmtiles_extract: z{z}/{x}/{y}: {e}");@@ -213,7 +221,7 @@ fn main() -> ExitCode {                 }             }         } else {-            body.to_vec()+            body.clone()         };         let mut tile = match Tile::decode(&raw) {             Ok(t) => t,@@ -279,7 +287,7 @@ fn main() -> ExitCode {     eprintln!(         "pmtiles_extract: wrote {out} ({:.1} MiB from {:.1} MiB): {kept} tile(s), z{lo}-{hi}",         built.len() as f64 / (1024.0 * 1024.0),-        bytes.len() as f64 / (1024.0 * 1024.0),+        source_bytes as f64 / (1024.0 * 1024.0),     );     if !layers.is_empty() {         eprintln!(
scripts/maps/tile_build/src/bin/tile_join.rs
diff --git a/scripts/maps/tile_build/src/bin/tile_join.rs b/scripts/maps/tile_build/src/bin/tile_join.rsindex d4131c682f..bc213ded04 100644--- a/scripts/maps/tile_build/src/bin/tile_join.rs+++ b/scripts/maps/tile_build/src/bin/tile_join.rs@@ -2,19 +2,21 @@ //! layers. The `tile-join` replacement. //! //! Usage:-//!   tile_join --out OUT.pmtiles IN1.pmtiles IN2.pmtiles [...]+//!   tile_join --out OUT.pmtiles IN1.pmtiles IN2.pmtiles [...] [--threads N] //! //! Later inputs win a layer-name collision, so a freshly built layer replaces a //! stale copy of itself. //!-//! Inputs are read wholly into memory, which bounds what can be joined at the size-//! of the largest input. That is ample for the overlays (a few GB combined at planet-//! scale) and hopeless for a planet base (~127 GB) - which is why the base is not-//! joined at all. Build overlay-only archives with `build_v5_pmtiles.sh --no-base`-//! and let the app mount them alongside the published base.+//! Inputs are opened rather than read: only each one's root directory and metadata are+//! held, so what can be joined is bounded by the tile COUNT and not by the input bytes.+//! An overlay-only join of the whole planet fits; a planet BASE (~127 GB of tile data+//! across 300 M tiles) still does not, which is why the base is not joined at all.+//! Build overlay-only archives with `build_v5_pmtiles.sh --no-base` and let the app+//! mount them alongside the published base.  use std::process::ExitCode;-use tile_build::pmtiles::Archive;+use tile_build::par;+use tile_build::pmtiles::ArchiveFile; use tile_build::tiling::merge_archives_to;  fn main() -> ExitCode {@@ -29,6 +31,20 @@ fn main() -> ExitCode {                 out = args.get(i + 1).cloned();                 i += 2;             }+            "--threads" => {+                let Some(raw) = args.get(i + 1) else {+                    eprintln!("tile_join: --threads needs a value");+                    return ExitCode::from(2);+                };+                match par::parse_threads(raw) {+                    Ok(n) => par::set_threads(n),+                    Err(e) => {+                        eprintln!("tile_join: {e}");+                        return ExitCode::from(2);+                    }+                }+                i += 2;+            }             "-h" | "--help" => {                 usage();                 return ExitCode::SUCCESS;@@ -51,26 +67,12 @@ fn main() -> ExitCode {         return ExitCode::from(2);     } -    let mut blobs = Vec::with_capacity(inputs.len());+    let mut archives = Vec::with_capacity(inputs.len());     for path in &inputs {-        match std::fs::read(path) {-            Ok(b) => {-                eprintln!("tile_join: read {path} ({:.1} MiB)", b.len() as f64 / 1_048_576.0);-                blobs.push(b);-            }-            Err(e) => {-                eprintln!("tile_join: cannot read {path}: {e}");-                return ExitCode::FAILURE;-            }-        }-    }--    let mut archives = Vec::with_capacity(blobs.len());-    for (path, blob) in inputs.iter().zip(blobs.iter()) {-        match Archive::parse(blob) {+        match ArchiveFile::open(path) {             Ok(a) => {                 eprintln!(-                    "tile_join:   {path}: z{}-{}, {} addressed tile(s)",+                    "tile_join: opened {path}: z{}-{}, {} addressed tile(s)",                     a.header.min_zoom, a.header.max_zoom, a.header.addressed_tiles                 );                 archives.push(a);@@ -82,36 +84,30 @@ fn main() -> ExitCode {         }     } -    let refs: Vec<&Archive> = archives.iter().collect();     // Scratch beside the output, because the last step copies the data section across     // and a cross-filesystem copy would be needlessly slow.     let scratch = format!("{out}.tiledata");-    if let Err(e) = merge_archives_to(&refs, &out, &scratch, true) {+    if let Err(e) = merge_archives_to(&mut archives, &out, &scratch, true) {         eprintln!("tile_join: {e}");         let _ = std::fs::remove_file(&scratch);         return ExitCode::FAILURE;     }-    // Re-opened rather than kept in memory: the whole point is never to hold the-    // finished archive, and reading the header back is the check that matters.-    let written = match std::fs::read(&out) {-        Ok(b) => b,-        Err(e) => {-            eprintln!("tile_join: cannot re-read {out}: {e}");-            return ExitCode::FAILURE;-        }-    };-    match Archive::parse(&written) {-        Ok(a) => eprintln!(+    // Header only. Re-reading the whole finished archive to print its zoom range was+    // its own ceiling: 8 GB of reads and an 8 GB allocation, after the merge had just+    // gone to the trouble of never holding it.+    let size = std::fs::metadata(&out).map(|m| m.len()).unwrap_or(0);+    match ArchiveFile::read_header(&out) {+        Ok(h) => eprintln!(             "tile_join: wrote {out} ({:.1} MiB): z{}-{}, {} addressed tile(s), {} distinct body(ies)",-            written.len() as f64 / 1_048_576.0,-            a.header.min_zoom,-            a.header.max_zoom,-            a.header.addressed_tiles,-            a.header.tile_contents,+            size as f64 / 1_048_576.0,+            h.min_zoom,+            h.max_zoom,+            h.addressed_tiles,+            h.tile_contents,         ),         Err(e) => {             // Writing something we cannot read back is a bug, not a warning.-            eprintln!("tile_join: wrote {out} but it does not parse: {e}");+            eprintln!("tile_join: wrote {out} but its header does not parse: {e}");             return ExitCode::FAILURE;         }     }@@ -119,5 +115,5 @@ fn main() -> ExitCode { }  fn usage() {-    eprintln!("usage: tile_join --out OUT.pmtiles IN1.pmtiles IN2.pmtiles [...]");+    eprintln!("usage: tile_join --out OUT.pmtiles IN1.pmtiles IN2.pmtiles [...] [--threads N]"); }
scripts/maps/tile_build/src/bin/tile_points.rs
diff --git a/scripts/maps/tile_build/src/bin/tile_points.rs b/scripts/maps/tile_build/src/bin/tile_points.rsindex 59e5f4ffb7..4370d70429 100644--- a/scripts/maps/tile_build/src/bin/tile_points.rs+++ b/scripts/maps/tile_build/src/bin/tile_points.rs@@ -3,7 +3,7 @@ //! //! Usage: //!   tile_points --geojson IN.geojsonseq --out OUT.pmtiles --layer NAME-//!               [--minzoom N] [--maxzoom N]+//!               [--minzoom N] [--maxzoom N] [--threads N] //! //! Input is one GeoJSON `Feature` per line with `Point` geometry, exactly what //! `gtfs_ingest`'s `transit_stops` binary and `osm_ingest`'s `poi_extract` and@@ -19,6 +19,7 @@ use std::process::ExitCode; use tile_build::geojson; use tile_build::geom::Geometry;+use tile_build::par; use tile_build::tiling::{build_point_archive_with, Point};  fn main() -> ExitCode {@@ -53,6 +54,20 @@ fn main() -> ExitCode {                 maxzoom = take(i).and_then(|v| v.parse().ok()).unwrap_or(maxzoom);                 i += 2;             }+            "--threads" => {+                let Some(raw) = take(i) else {+                    eprintln!("tile_points: --threads needs a value");+                    return ExitCode::from(2);+                };+                match par::parse_threads(&raw) {+                    Ok(n) => par::set_threads(n),+                    Err(e) => {+                        eprintln!("tile_points: {e}");+                        return ExitCode::from(2);+                    }+                }+                i += 2;+            }             "-h" | "--help" => {                 usage();                 return ExitCode::SUCCESS;@@ -129,7 +144,7 @@ fn main() -> ExitCode {  fn usage() {     eprintln!("usage: tile_points --geojson IN.geojsonseq --out OUT.pmtiles --layer NAME");-    eprintln!("                   [--minzoom N] [--maxzoom N]");+    eprintln!("                   [--minzoom N] [--maxzoom N] [--threads N]"); }  /// One line's points, or `None` when the line is not point geometry.
scripts/maps/tile_build/src/gz.rs
diff --git a/scripts/maps/tile_build/src/gz.rs b/scripts/maps/tile_build/src/gz.rsindex 68e3b25aa7..4486dc2ab7 100644--- a/scripts/maps/tile_build/src/gz.rs+++ b/scripts/maps/tile_build/src/gz.rs@@ -20,8 +20,99 @@ const FCOMMENT: u8 = 1 << 4; const LEVEL: u8 = 9;  /// Wrap `data` in a gzip stream.+///+/// Convenience over [`Compressor`] for one-shot callers (directories, tests). The+/// tilers use a per-worker [`Compressor`] instead — see its docs for why. pub fn compress(data: &[u8]) -> Vec<u8> {-    let body = miniz_oxide::deflate::compress_to_vec(data, LEVEL);+    frame(data, &miniz_oxide::deflate::compress_to_vec(data, LEVEL))+}++/// A reusable DEFLATE state, so a tile's compression does not pay for building one.+///+/// `miniz_oxide::deflate::compress_to_vec` constructs a fresh `CompressorOxide` per+/// call, and that state is large — a 32 KiB dictionary plus hash and Huffman tables,+/// hundreds of kilobytes, much of it zeroed on construction. On one core that block+/// is reused by the allocator and stays cache-hot, so it costs almost nothing. Across+/// 32 cores each worker rebuilds its own every tile, and the encode pass becomes+/// memory-bandwidth bound: measured on 200k synthetic roads at z14, it went 3.72s at+/// one thread to 1.55s at four and then back UP to 3.23s at 32. Reusing one state per+/// worker is what removes that ceiling.+///+/// Output is byte-for-byte what `compress` produces — `reset` keeps the parameters,+/// and `the_reusable_compressor_matches_the_one_shot_one` holds the two to it.+pub struct Compressor {+    state: miniz_oxide::deflate::core::CompressorOxide,+    /// Grown to the largest tile seen and then reused, so the output buffer is not+    /// reallocated per tile either.+    scratch: Vec<u8>,+    used: bool,+}++impl Default for Compressor {+    fn default() -> Compressor {+        Compressor::new()+    }+}++impl Compressor {+    pub fn new() -> Compressor {+        // The flags `compress_to_vec(_, LEVEL)` computes: window_bits 0 (raw DEFLATE,+        // no zlib wrapper) and the default strategy. Matching them is what makes the+        // two functions produce the same bytes.+        let flags = miniz_oxide::deflate::core::create_comp_flags_from_zip_params(+            LEVEL as i32,+            0,+            0,+        );+        Compressor {+            state: miniz_oxide::deflate::core::CompressorOxide::new(flags),+            scratch: Vec::new(),+            used: false,+        }+    }++    /// Wrap `data` in a gzip stream, reusing this compressor's state.+    pub fn compress(&mut self, data: &[u8]) -> Vec<u8> {+        use miniz_oxide::deflate::core::{compress, TDEFLFlush, TDEFLStatus};++        if self.used {+            self.state.reset();+        }+        self.used = true;++        // Deflate output does not depend on how the output buffer is chunked, only on+        // the input and the parameters, so growing rather than guessing right is safe.+        let want = data.len().saturating_add(data.len() / 2).saturating_add(64);+        if self.scratch.len() < want {+            self.scratch.resize(want, 0);+        }++        let mut input = data;+        let mut at = 0usize;+        loop {+            let (status, read, wrote) =+                compress(&mut self.state, input, &mut self.scratch[at..], TDEFLFlush::Finish);+            at += wrote;+            match status {+                TDEFLStatus::Done => break,+                TDEFLStatus::Okay if read <= input.len() => {+                    input = &input[read..];+                    if self.scratch.len() - at < 64 {+                        let grown = (self.scratch.len() * 2).max(at + 64);+                        self.scratch.resize(grown, 0);+                    }+                }+                // Upstream panics here too: the remaining statuses are "bad parameters"+                // and "output buffer of length zero", neither of which can happen above.+                other => panic!("deflate failed unexpectedly: {other:?}"),+            }+        }+        frame(data, &self.scratch[..at])+    }+}++/// The 10-byte gzip header, the deflate body, then CRC32 and ISIZE.+fn frame(data: &[u8], body: &[u8]) -> Vec<u8> {     let mut out = Vec::with_capacity(body.len() + 18);     out.extend_from_slice(&[         0x1f, 0x8b, // magic@@ -31,7 +122,7 @@ pub fn compress(data: &[u8]) -> Vec<u8> {         0x00, // XFL         0xff, // OS = unknown, again for reproducibility     ]);-    out.extend_from_slice(&body);+    out.extend_from_slice(body);     out.extend_from_slice(&crc32(data).to_le_bytes());     out.extend_from_slice(&(data.len() as u32).to_le_bytes());     out@@ -134,6 +225,46 @@ mod tests {     const REAL_GZ: &[u8] = include_bytes!("../tests/fixtures/v5ca_z11_tile.mvt.gz");     const REAL_RAW: &[u8] = include_bytes!("../tests/fixtures/v5ca_z11_tile.mvt"); +    /// The reusable compressor must be indistinguishable from the one-shot one, or+    /// every archive built by a tiler differs from one built by a test helper.+    ///+    /// Reuse is the interesting half: a `reset` that left dictionary or Huffman state+    /// behind would still produce a VALID gzip stream, just a different one, and only+    /// comparing the bytes of the second and later calls catches it. So the corpus is+    /// run through a single compressor in sequence, and each result is checked against+    /// a fresh one-shot call.+    #[test]+    fn the_reusable_compressor_matches_the_one_shot_one() {+        let mut corpus: Vec<Vec<u8>> = vec![+            Vec::new(),+            b"a".to_vec(),+            b"hello hello hello hello hello".to_vec(),+            REAL_RAW.to_vec(),+            // Highly compressible, then barely compressible: two very different paths+            // through the Huffman tables, back to back.+            vec![0u8; 100_000],+            (0..70_000u32).map(|i| (i.wrapping_mul(2654435761) >> 13) as u8).collect(),+        ];+        // A run of small inputs after a large one, which is what a tiler actually does.+        for i in 0..40u32 {+            corpus.push(format!("tile body number {i} with some repetition repetition").into_bytes());+        }++        let mut reusable = Compressor::new();+        for (i, data) in corpus.iter().enumerate() {+            let want = compress(data);+            let got = reusable.compress(data);+            assert!(+                got == want,+                "corpus[{i}] ({} byte(s)): reused {} byte(s), one-shot {}",+                data.len(),+                got.len(),+                want.len()+            );+            assert_eq!(&decompress(&got).unwrap(), data, "corpus[{i}] round trip");+        }+    }+     #[test]     fn crc32_matches_the_known_check_value() {         // The standard CRC-32 check value for "123456789".
scripts/maps/tile_build/src/lib.rs
diff --git a/scripts/maps/tile_build/src/lib.rs b/scripts/maps/tile_build/src/lib.rsindex e266e2c728..5986ff284f 100644--- a/scripts/maps/tile_build/src/lib.rs+++ b/scripts/maps/tile_build/src/lib.rs@@ -25,6 +25,11 @@ //!     a tile's buffered rect. //!   * [`simplify`] — Douglas-Peucker in integer tile coordinates. //!   * [`pyramid`] — the tile pyramid driver and the drop policy.+//!   * [`par`] — the thread budget (`--threads`, `MAPS_THREADS`) and the pool the+//!     tilers run on. Parallelism never changes an output byte.+//!   * [`spill`] — the on-disk record format and `tile_id`-range buckets the streaming+//!     tiler partitions through, so peak memory tracks the tile COUNT rather than the+//!     input bytes. //!   * [`tiling`] — bucket points into tiles, and merge tilesets. //! //! [`geom`], [`clip`] and [`simplify`] compose in one fixed order; [`geom`]'s module@@ -53,9 +58,11 @@ pub mod geojson; pub mod geom; pub mod gz; pub mod mvt;+pub mod par; pub mod pmtiles; pub mod progress; pub mod proto; pub mod pyramid; pub mod simplify;+pub mod spill; pub mod tiling;
scripts/maps/tile_build/src/par.rs
diff --git a/scripts/maps/tile_build/src/par.rs b/scripts/maps/tile_build/src/par.rsnew file mode 100644index 0000000000..5906721c2f--- /dev/null+++ b/scripts/maps/tile_build/src/par.rs@@ -0,0 +1,185 @@+//! The thread budget, and the pool every parallel stage in this crate runs on.+//!+//! Sized the same way `osm_ingest::par` sizes its pool, and deliberately so: the+//! build scripts fan out several of these tools at once, and+//! `available_parallelism()` reports the whole box to every one of them. Six+//! concurrent layer builds each claiming 32 threads on a 32-core machine finish+//! slower than running in sequence, so the cap has to be settable from outside+//! the process. Hence `--threads` and `MAPS_THREADS`, spelled identically in both+//! crates so one `MAPS_THREADS` export governs a whole build.+//!+//! Parallelism here never changes an output byte. Every stage either collects+//! results into a slot indexed by input position, or writes them in a+//! sequentially-folded second pass; see [`crate::pyramid::build_archive_to`].++use std::sync::atomic::{AtomicUsize, Ordering};+use std::sync::{Arc, Mutex};++/// 0 means "not set"; any other value is an explicit cap from `--threads`.+static OVERRIDE: AtomicUsize = AtomicUsize::new(0);++/// Cap the pool for the rest of the process. Called from `main` after argument+/// parsing.+pub fn set_threads(n: usize) {+    OVERRIDE.store(n.max(1), Ordering::Relaxed);+}++/// Drop the override again, so a test can leave the process as it found it.+#[cfg(test)]+pub fn clear_threads() {+    OVERRIDE.store(0, Ordering::Relaxed);+}++/// Threads to use. `--threads` beats `MAPS_THREADS` beats the box.+pub fn threads() -> usize {+    resolve(+        OVERRIDE.load(Ordering::Relaxed),+        std::env::var("MAPS_THREADS").ok().as_deref(),+    )+}++/// The precedence rule, split out so it can be tested without mutating the+/// process-wide override or the environment.+fn resolve(override_n: usize, env: Option<&str>) -> usize {+    if override_n > 0 {+        return override_n;+    }+    if let Some(n) = env_threads(env) {+        return n;+    }+    std::thread::available_parallelism()+        .map(|n| n.get())+        .unwrap_or(4)+}++/// A malformed or non-positive `MAPS_THREADS` is ignored rather than fatal: it is+/// usually exported once for a whole script run, and killing an eight-hour planet+/// build over a typo in an environment variable serves nobody.+fn env_threads(raw: Option<&str>) -> Option<usize> {+    static WARNED: std::sync::Once = std::sync::Once::new();+    let trimmed = raw?.trim();+    match trimmed.parse::<usize>() {+        Ok(n) if n > 0 => Some(n),+        _ => {+            WARNED.call_once(|| {+                eprintln!("WARNING: ignoring MAPS_THREADS='{trimmed}' (wants a positive count)");+            });+            None+        }+    }+}++/// Parse a `--threads N` value.+pub fn parse_threads(value: &str) -> std::result::Result<usize, String> {+    value+        .parse::<usize>()+        .ok()+        .filter(|n| *n > 0)+        .ok_or_else(|| format!("--threads wants a positive count, not {value}"))+}++/// Our own pool rather than rayon's global one, so the cap applies even when+/// something else in the process has already initialised the global.+///+/// Cached, and rebuilt only when the requested count changes. In production that+/// happens once, because `--threads` is read before any tiling starts; the reason+/// it is not a `OnceLock` is that the byte-identity tests build the same archive at+/// 1, 2, 3 and 32 threads in one process, and a pool fixed on first use would make+/// that test assert nothing.+///+/// If rayon refuses to build a pool — which in practice means the OS would not give+/// us threads — fall back to a single-threaded one rather than failing the build:+/// every caller is a `map` whose serial execution is correct, just slower.+fn pool() -> Arc<rayon::ThreadPool> {+    static POOL: Mutex<Option<(usize, Arc<rayon::ThreadPool>)>> = Mutex::new(None);+    let want = threads();+    let mut cached = POOL.lock().expect("thread pool mutex");+    if let Some((have, p)) = cached.as_ref() {+        if *have == want {+            return Arc::clone(p);+        }+    }+    let built = Arc::new(build_pool(want).unwrap_or_else(|e| {+        eprintln!("WARNING: cannot start a {want}-thread pool ({e}); continuing on one thread");+        build_pool(1).expect("a one-thread pool")+    }));+    *cached = Some((want, Arc::clone(&built)));+    built+}++fn build_pool(n: usize) -> std::result::Result<rayon::ThreadPool, rayon::ThreadPoolBuildError> {+    rayon::ThreadPoolBuilder::new()+        .num_threads(n)+        .thread_name(|i| format!("tile_build-{i}"))+        .build()+}++/// Run `f` on the pool, so it sees our thread cap rather than rayon's global one.+pub fn install<R: Send>(f: impl FnOnce() -> R + Send) -> R {+    pool().install(f)+}++/// How many items to hand the pool at once.+///+/// The tilers map over items whose results are held until the batch is written, so+/// the batch size is what bounds that memory. It has to be large enough to keep+/// every core fed — a batch of `threads` items means one task each and a barrier+/// after every one — while still holding only a bounded number of results. Encoded+/// tile bodies and spill records are kilobytes each, so a few thousand is a few MB:+/// measured peak RSS moves by ~12% between 1 and 32 threads, not by 32x.+pub fn batch_len() -> usize {+    threads().saturating_mul(64).max(512)+}++/// The smallest number of items worth waking a worker for.+///+/// One tile's encode is tens of microseconds. Handed to rayon one at a time, the+/// work-stealing and spinning cost more than the work: measured on 200k synthetic+/// roads at z14, the encode pass went 4.15s at one thread to 1.81s at four and then+/// back UP to 3.51s at 32, purely on scheduling overhead. Batching several items+/// into each task amortises that away, which is what makes the high thread counts+/// pay at all.+pub const MIN_TASK_LEN: usize = 16;++#[cfg(test)]+mod tests {+    use super::*;++    #[test]+    fn parse_threads_rejects_zero_and_junk() {+        assert_eq!(parse_threads("8"), Ok(8));+        assert!(parse_threads("0").is_err());+        assert!(parse_threads("-1").is_err());+        assert!(parse_threads("many").is_err());+        assert!(parse_threads("").is_err());+    }++    #[test]+    fn the_flag_beats_the_env_beats_the_box() {+        let box_threads = resolve(0, None);+        assert_eq!(resolve(6, Some("2")), 6, "--threads wins");+        assert_eq!(resolve(0, Some("2")), 2, "MAPS_THREADS wins over the box");+        assert_eq!(resolve(6, None), 6);+        for junk in ["0", "many", "", "-4"] {+            assert_eq!(resolve(0, Some(junk)), box_threads, "MAPS_THREADS={junk}");+        }+        assert_eq!(resolve(0, Some(" 3 ")), 3, "surrounding space is tolerated");+    }++    /// A batch has to hold enough tasks to keep the pool busy: at least a few+    /// `MIN_TASK_LEN` tasks per thread, or the barrier at the end of each batch+    /// costs more than the batch saves.+    #[test]+    fn a_batch_holds_several_tasks_per_thread() {+        for n in [1usize, 2, 3, 32, 64] {+            set_threads(n);+            let tasks = batch_len() / MIN_TASK_LEN;+            assert!(+                tasks >= n * 2,+                "{n} threads: {tasks} task(s) of {MIN_TASK_LEN} in a batch of {}",+                batch_len()+            );+        }+        clear_threads();+    }+}
scripts/maps/tile_build/src/pmtiles.rs
diff --git a/scripts/maps/tile_build/src/pmtiles.rs b/scripts/maps/tile_build/src/pmtiles.rsindex e57126cc1c..e7e7289cee 100644--- a/scripts/maps/tile_build/src/pmtiles.rs+++ b/scripts/maps/tile_build/src/pmtiles.rs@@ -414,35 +414,42 @@ impl Archive {     /// "not a gzip stream" halfway through a merge.     pub fn tile_offsets(&self) -> Result<Vec<(u64, u64, u32)>> {         let mut out = Vec::new();-        let mut push = |e: &Entry| -> Result<()> {-            if e.offset + e.length as u64 > self.tile_data.len() as u64 {-                return err("PMTiles entry runs past the tile data section");-            }+        self.visit_entries(&mut |e| {             for k in 0..e.run_length as u64 {                 out.push((e.tile_id + k, e.offset, e.length));             }             Ok(())-        };+        })?;+        Ok(out)+    }++    /// Call `visit` once per tile entry, ascending by `tile_id`, runs unexpanded.+    ///+    /// The in-memory counterpart of [`ArchiveFile::visit_entries`], with the same+    /// contract, so a caller written against one works against the other.+    pub fn visit_entries(&self, visit: &mut dyn FnMut(&Entry) -> Result<()>) -> Result<()> {         for e in &self.root {             if e.run_length > 0 {-                push(e)?;-            } else {-                let (o, l) = (e.offset as usize, e.length as usize);-                if o + l > self.leaves.len() {-                    return err("PMTiles leaf entry runs past leaf section");-                }-                let leaf = parse_directory(&decompress(-                    self.header.internal_compression,-                    &self.leaves[o..o + l],-                )?)?;-                for le in &leaf {-                    if le.run_length > 0 {-                        push(le)?;-                    }+                check_body(&self.header, e)?;+                visit(e)?;+                continue;+            }+            let (o, l) = (e.offset as usize, e.length as usize);+            if o + l > self.leaves.len() {+                return err("PMTiles leaf entry runs past leaf section");+            }+            let leaf = parse_directory(&decompress(+                self.header.internal_compression,+                &self.leaves[o..o + l],+            )?)?;+            for le in &leaf {+                if le.run_length > 0 {+                    check_body(&self.header, le)?;+                    visit(le)?;                 }             }         }-        Ok(out)+        Ok(())     }      /// The still-compressed body at `offset..offset + length` in the data section.@@ -498,6 +505,218 @@ fn push_run<'a>(out: &mut Vec<(u64, &'a [u8])>, e: &Entry, data: &'a [u8]) -> Re     Ok(()) } +// --- Reading from a file, without holding it -----------------------------------++/// An archive read through a file handle, holding only its root directory.+///+/// [`Archive`] needs the whole file resident, which puts a second ceiling on every+/// planet job: `tile_join` read each input with `std::fs::read` and then `parse`+/// copied the leaf and data sections again, so a 17 GB merge needed roughly 34 GB+/// before the writer had allocated anything. This keeps the root directory and the+/// metadata — kilobytes — and reads one leaf directory or one tile body at a time into+/// a buffer it reuses.+///+/// Its readers take `&mut self`, because seeking mutates the handle. `mmap` would+/// avoid that and be faster, but it needs either a dependency or `unsafe libc` that+/// would not compile on Windows, and this crate is deliberately single-dependency and+/// offline-resolvable.+pub struct ArchiveFile {+    /// Declared first so the handle closes before [`Scratch`]-style cleanup or any+    /// caller's `remove_file` runs. Nothing depends on it today, but the ordering is+    /// free and Windows is unforgiving about open handles.+    file: File,+    path: PathBuf,+    pub header: Header,+    pub metadata: Vec<u8>,+    root: Vec<Entry>,+    /// Reused across leaf reads: the published basemap has 324 of them.+    leaf_buf: Vec<u8>,+}++impl ArchiveFile {+    /// Just the 127-byte header, for a caller that only wants to report on an archive.+    ///+    /// What `tile_join` prints its summary from. Re-reading a finished planet archive+    /// to recover its zoom range cost 8 GB of reads and an 8 GB allocation.+    pub fn read_header(path: impl AsRef<Path>) -> Result<Header> {+        let path = path.as_ref();+        let mut file = File::open(path)+            .map_err(|e| Error(format!("cannot read {}: {e}", path.display())))?;+        let mut head = [0u8; HEADER_LEN];+        file.read_exact(&mut head)+            .map_err(|e| Error(format!("reading {}'s header: {e}", path.display())))?;+        Header::parse(&head)+    }++    pub fn open(path: impl Into<PathBuf>) -> Result<ArchiveFile> {+        let path = path.into();+        let mut file = File::open(&path)+            .map_err(|e| Error(format!("cannot read {}: {e}", path.display())))?;+        let file_len = file+            .metadata()+            .map_err(|e| Error(format!("cannot stat {}: {e}", path.display())))?+            .len();++        let mut head = [0u8; HEADER_LEN];+        file.read_exact(&mut head)+            .map_err(|e| Error(format!("reading {}'s header: {e}", path.display())))?;+        let header = Header::parse(&head)?;++        let root_raw = read_section(+            &mut file,+            file_len,+            header.root_offset,+            header.root_length,+            "root directory",+        )?;+        let root = parse_directory(&decompress(header.internal_compression, &root_raw)?)?;+        let metadata_raw = read_section(+            &mut file,+            file_len,+            header.metadata_offset,+            header.metadata_length,+            "metadata",+        )?;+        let metadata = decompress(header.internal_compression, &metadata_raw)?;+        // Checked once here so every later read can be bounds-checked against the+        // section length alone, exactly as `Archive` checks against its slice.+        for (off, len, what) in [+            (header.leaf_offset, header.leaf_length, "leaf directories"),+            (header.tile_data_offset, header.tile_data_length, "tile data"),+        ] {+            if off.checked_add(len).filter(|e| *e <= file_len).is_none() {+                return err(format!("PMTiles {what} runs past end of file"));+            }+        }++        Ok(ArchiveFile {+            file,+            path,+            header,+            metadata,+            root,+            leaf_buf: Vec::new(),+        })+    }++    pub fn path(&self) -> &Path {+        &self.path+    }++    /// Call `visit` once per tile entry in the archive, ascending by `tile_id`.+    ///+    /// Runs are **not** expanded: an entry covering `run_length` ids arrives once, and+    /// a caller that needs a row per id expands it itself. Leaf directories are read+    /// and inflated one at a time, so resident bytes are the root plus one leaf.+    pub fn visit_entries(+        &mut self,+        visit: &mut dyn FnMut(&Entry) -> Result<()>,+    ) -> Result<()> {+        // Indexed rather than iterated: reading a leaf needs `&mut self`, and `Entry`+        // is `Copy`, so a shared borrow of `root` would only be in the way.+        for i in 0..self.root.len() {+            let e = self.root[i];+            if e.run_length > 0 {+                check_body(&self.header, &e)?;+                visit(&e)?;+                continue;+            }+            let leaf = self.read_leaf(&e)?;+            for le in &leaf {+                if le.run_length > 0 {+                    check_body(&self.header, le)?;+                    visit(le)?;+                }+            }+        }+        Ok(())+    }++    fn read_leaf(&mut self, e: &Entry) -> Result<Vec<Entry>> {+        let len = e.length as u64;+        if e.offset+            .checked_add(len)+            .filter(|v| *v <= self.header.leaf_length)+            .is_none()+        {+            return err("PMTiles leaf entry runs past leaf section");+        }+        let at = self.header.leaf_offset + e.offset;+        self.leaf_buf.clear();+        self.leaf_buf.resize(len as usize, 0);+        self.file+            .seek(SeekFrom::Start(at))+            .map_err(|e| Error(format!("seeking {} to {at}: {e}", self.path.display())))?;+        self.file+            .read_exact(&mut self.leaf_buf)+            .map_err(|e| Error(format!("reading a leaf directory of {}: {e}", self.path.display())))?;+        parse_directory(&decompress(self.header.internal_compression, &self.leaf_buf)?)+    }++    /// Read the still-compressed body at `offset..offset + length` into `out`.+    ///+    /// `out` is a caller-owned buffer so a merge loop allocates once rather than once+    /// per tile. `offset` is `u64`: a planet layer's data section is far past+    /// `u32::MAX`.+    pub fn body_into(&mut self, offset: u64, length: u32, out: &mut Vec<u8>) -> Result<()> {+        if offset+            .checked_add(length as u64)+            .filter(|e| *e <= self.header.tile_data_length)+            .is_none()+        {+            return err(format!(+                "PMTiles body at {offset}+{length} runs past the {}-byte tile data section",+                self.header.tile_data_length+            ));+        }+        let at = self.header.tile_data_offset + offset;+        out.clear();+        out.resize(length as usize, 0);+        self.file+            .seek(SeekFrom::Start(at))+            .map_err(|e| Error(format!("seeking {} to {at}: {e}", self.path.display())))?;+        self.file+            .read_exact(out)+            .map_err(|e| Error(format!("reading a tile body of {}: {e}", self.path.display())))?;+        Ok(())+    }+}++/// An entry's body must lie inside the data section. Shared by both readers so the+/// message a corrupt archive produces does not depend on which one opened it.+fn check_body(header: &Header, e: &Entry) -> Result<()> {+    if e.offset+        .checked_add(e.length as u64)+        .filter(|v| *v <= header.tile_data_length)+        .is_none()+    {+        return err("PMTiles entry runs past the tile data section");+    }+    Ok(())+}++fn read_section(+    file: &mut File,+    file_len: u64,+    offset: u64,+    length: u64,+    what: &str,+) -> Result<Vec<u8>> {+    if offset+        .checked_add(length)+        .filter(|e| *e <= file_len)+        .is_none()+    {+        return err(format!("PMTiles {what} runs past end of file"));+    }+    file.seek(SeekFrom::Start(offset))+        .map_err(|e| Error(format!("seeking to the {what}: {e}")))?;+    let mut buf = vec![0u8; length as usize];+    file.read_exact(&mut buf)+        .map_err(|e| Error(format!("reading the {what}: {e}")))?;+    Ok(buf)+}+ /// Find the entry covering `want`: the last entry whose `tile_id <= want`, then a /// bounds check against its run. fn find_entry(entries: &[Entry], want: u64) -> Option<&Entry> {@@ -684,6 +903,23 @@ impl Builder {     } } +/// The scratch file's lifetime, so a run that dies mid-planet cannot strand tens of+/// gigabytes. Follows `osm_ingest::chains::Spill`.+///+/// A field of its own rather than `impl Drop for StreamBuilder`, because a struct's+/// fields drop in declaration order and the removal must happen **after** the write+/// handle closes: Windows refuses to delete a file something still holds open. So+/// `data` is declared first and this second.+struct Scratch(PathBuf);++impl Drop for Scratch {+    fn drop(&mut self) {+        // Best effort: a leftover scratch is bad, but failing a finished build over an+        // undeletable temporary would be worse.+        let _ = std::fs::remove_file(&self.0);+    }+}+ /// A [`Builder`] that never holds the archive in memory. /// /// [`Builder`] is fine for a single layer but cannot assemble a planet-scale join: it@@ -709,7 +945,7 @@ impl Builder { /// rather than trusting the caller. pub struct StreamBuilder {     data: BufWriter<File>,-    scratch_path: PathBuf,+    scratch: Scratch,     data_len: u64,     /// How much of `data` has actually reached the file. Lets a dedup lookup skip the     /// flush unless the body it wants is still sitting in the write buffer.@@ -749,7 +985,7 @@ impl StreamBuilder {             .map_err(|e| Error(format!("cannot create {}: {e}", scratch_path.display())))?;         Ok(StreamBuilder {             data: BufWriter::with_capacity(1 << 20, file),-            scratch_path,+            scratch: Scratch(scratch_path),             data_len: 0,             flushed: 0,             entries: Vec::new(),@@ -878,10 +1114,9 @@ impl StreamBuilder {         put(&leaf_body)?;          // Stream the data section across rather than loading it: it is the whole point-        // of the scratch file.-        let mut src = self.data.into_inner().map_err(|e| {-            Error(format!("recovering the scratch handle: {}", e.error()))-        })?;+        // of the scratch file. Read through `get_mut` rather than `into_inner`, so no+        // field is moved out and `Scratch` stays in charge of the cleanup.+        let src = self.data.get_mut();         src.seek(SeekFrom::Start(0))             .map_err(|e| Error(format!("rewinding scratch: {e}")))?;         let mut buf = vec![0u8; 1 << 20];@@ -893,20 +1128,21 @@ impl StreamBuilder {             if n == 0 {                 break;             }-            put(&buf[..n])?;+            w.write_all(&buf[..n])+                .map_err(|e| Error(format!("writing {}: {e}", out.display())))?;             copied += n as u64;         }         if copied != self.data_len {             return err(format!(-                "scratch held {copied} tile byte(s), expected {}",+                "scratch {} held {copied} tile byte(s), expected {}",+                self.scratch.0.display(),                 self.data_len             ));         }         w.flush()             .map_err(|e| Error(format!("flushing {}: {e}", out.display())))?;-        drop(w);-        drop(src);-        let _ = std::fs::remove_file(&self.scratch_path);+        // `self` — and with it `Scratch` — drops here, which is what removes the+        // scratch file.         Ok(())     } }
scripts/maps/tile_build/src/pyramid.rs
diff --git a/scripts/maps/tile_build/src/pyramid.rs b/scripts/maps/tile_build/src/pyramid.rsindex c3e288081a..c729c3c62e 100644--- a/scripts/maps/tile_build/src/pyramid.rs+++ b/scripts/maps/tile_build/src/pyramid.rs@@ -44,10 +44,14 @@ use crate::clip::clip_geometry; use crate::geom::{self, Geometry, IntGeometry}; use crate::mvt::{self, Feature as MvtFeature, GeomType, Layer, Tile, Value, DEFAULT_EXTENT};+use crate::par; use crate::pmtiles::{self, Builder}; use crate::progress::Progress;-use crate::proto::{err, Result};+use crate::proto::{err, Error, Result}; use crate::simplify;+use crate::spill::{self, GeomKind};+use rayon::prelude::*;+use std::path::Path;  /// tippecanoe's default maximum gzipped tile size, and what the published /// archives were built against.@@ -117,6 +121,136 @@ pub struct ZoomStats {     pub largest_tile_bytes: usize, } +/// One feature's contribution to one tile, ready for the drop policy.+///+/// Everything is borrowed. Both producers already own the geometry and the properties+/// somewhere -- the in-memory one in a per-tile vector, the streaming one in a loaded+/// bucket -- and a third copy per candidate would be the largest allocation in the+/// tiler. `extent` is [`extent_of`] precomputed at construction rather than recomputed+/// inside the importance sort, which would rescan every vertex `O(n log n)` times.+struct TileCandidate<'a> {+    /// The feature's position in the input, which is what makes the importance order+    /// total and therefore the drop policy deterministic.+    seq: u64,+    geom: &'a IntGeometry,+    props: &'a [(String, Value)],+    extent: i64,+}++/// One encoded candidate tile, waiting for the sequential fold that writes it.+///+/// The parallel passes produce these and the fold consumes them in `tile_id` order;+/// keeping the fields named is what makes that fold readable, since it has to update+/// five different counters plus the archive.+struct EncodedTile {+    id: u64,+    body: Vec<u8>,+    kept: usize,+    over_budget: bool,+    /// Candidates the tile held before the drop policy ran.+    placed: usize,+}++/// The stable importance order: largest bounding box first, input position breaking+/// ties.+///+/// Taken as loose fields so the streaming producer can sort its records by+/// `(tile_id, importance)` without first building candidates it cannot borrow from a+/// vector it is still sorting. One function either way, so the two producers cannot+/// disagree about which features a tight budget drops -- a disagreement no test+/// comparing anything less than whole bytes would catch.+fn by_importance_keys(+    a_extent: i64,+    a_seq: u64,+    b_extent: i64,+    b_seq: u64,+) -> std::cmp::Ordering {+    b_extent.cmp(&a_extent).then_with(|| a_seq.cmp(&b_seq))+}++fn by_importance(a: &TileCandidate, b: &TileCandidate) -> std::cmp::Ordering {+    by_importance_keys(a.extent, a.seq, b.extent, b.seq)+}++/// The candidate tiles of one zoom as `(tile_id, tx, ty)`, ascending by `tile_id`.+///+/// `(tx, ty)` order is **not** `tile_id` order -- at z1 the lexicographic walk gives+/// ids 1, 2, 4, 3 -- so sorting on the pair is not enough. [`Builder`] sorts by id+/// itself and so does not care, but [`pmtiles::StreamBuilder`] hard-errors on a+/// non-ascending id, and both producers visiting tiles in the same order is what lets+/// their outputs be compared byte for byte.+fn tiles_in_id_order(z: u8, tiles: impl IntoIterator<Item = (u64, u64)>) -> Vec<(u64, u64, u64)> {+    let mut out: Vec<(u64, u64, u64)> = tiles+        .into_iter()+        .map(|(tx, ty)| (pmtiles::tile_id(z, tx, ty), tx, ty))+        .collect();+    out.sort_unstable();+    out+}++/// One feature's contribution to one zoom's spill: every record it produces, in one+/// allocation.+///+/// One `Vec` per feature rather than one per record, because a coastline at z16+/// reaches thousands of tiles and a `Vec` each would make the allocator the hot+/// path. `spans` indexes `blob`, so pushing is `set.push(id, &blob[at..at + len])`.+struct BucketedFeature {+    blob: Vec<u8>,+    spans: Vec<(u64, usize, usize)>,+}++/// Project one feature, clip it into every tile it reaches, and encode a spill+/// record per tile.+///+/// Pure: every argument is shared except the two scratch buffers, which are the+/// caller's per-worker `touched` and `rec`. That is what lets the bucket pass run+/// this across the pool — and the reason the buffers are passed in rather than+/// declared here is the one the serial loop had, unchanged: allocating them per+/// feature would cost three million allocations a zoom.+#[allow(clippy::too_many_arguments)]+fn bucket_feature(+    f: &Feature,+    seq: u64,+    z: u8,+    opts: &Options,+    buffer: f64,+    tolerance: f64,+    touched: &mut Vec<(u64, u64)>,+    rec: &mut Vec<u8>,+) -> Result<BucketedFeature> {+    // Project once per feature per zoom, not once per tile: a coastline can cross+    // thousands of tiles and the projection is the expensive part.+    let projected = geom::project_geometry(&f.geometry, z, opts.extent);+    geom::tiles_touched(&projected, z, opts.extent, buffer, touched);+    let mut out = BucketedFeature {+        blob: Vec::new(),+        spans: Vec::with_capacity(touched.len()),+    };+    for &(tx, ty) in touched.iter() {+        let rect = geom::tile_rect(tx, ty, opts.extent, buffer);+        let clipped = clip_geometry(&projected, &rect);+        let local = geom::to_tile(&clipped, tx, ty, opts.extent);+        let simplified = simplify::simplify(&local, tolerance);+        if simplified.is_empty() {+            continue;+        }+        rec.clear();+        spill::encode_record(+            pmtiles::tile_id(z, tx, ty),+            seq,+            extent_of(&simplified),+            &simplified,+            &f.props,+            rec,+        )?;+        let at = out.blob.len();+        out.blob.extend_from_slice(rec);+        out.spans+            .push((pmtiles::tile_id(z, tx, ty), at, out.blob.len() - at));+    }+    Ok(out)+}+ /// Build the archive, and a per-zoom report. pub fn build_archive(features: &[Feature], opts: &Options) -> Result<(Vec<u8>, Vec<ZoomStats>)> {     if opts.min_zoom > opts.max_zoom {@@ -148,11 +282,14 @@ pub fn build_archive(features: &[Feature], opts: &Options) -> Result<(Vec<u8>, V         let tolerance = simplify::tolerance_for(z, opts.max_zoom, opts.simplification);          // Project once per zoom, not once per tile: a coastline can cross thousands-        // of tiles and the projection is the expensive part.-        let projected: Vec<Option<Geometry>> = features-            .iter()-            .map(|f| Some(geom::project_geometry(&f.geometry, z, opts.extent)))-            .collect();+        // of tiles and the projection is the expensive part. Per-feature pure, so it+        // maps across the pool; `collect` into a Vec keeps it in input order.+        let projected: Vec<Option<Geometry>> = par::install(|| {+            features+                .par_iter()+                .map(|f| Some(geom::project_geometry(&f.geometry, z, opts.extent)))+                .collect()+        });          // tile -> the features that reach it, in input order.         let mut by_tile: std::collections::HashMap<(u64, u64), Vec<usize>> =@@ -171,53 +308,83 @@ pub fn build_archive(features: &[Feature], opts: &Options) -> Result<(Vec<u8>, V             }         } -        let mut tiles: Vec<(u64, u64)> = by_tile.keys().copied().collect();-        tiles.sort_unstable();+        let tiles = tiles_in_id_order(z, by_tile.keys().copied());         let mut bar = Progress::new(             format!("{} z{z}", opts.layer),             tiles.len(),             CANDIDATES,             opts.progress,         );-        for (tx, ty) in tiles {-            bar.tick(CANDIDATES);-            let indices = &by_tile[&(tx, ty)];-            let rect = geom::tile_rect(tx, ty, opts.extent, buffer);--            // Clip, move into the tile, simplify. Anything that vanishes here never-            // reached the tile in the first place, so it is not a "drop".-            let mut candidates: Vec<(usize, IntGeometry)> = Vec::with_capacity(indices.len());-            for &i in indices {-                let p = projected[i].as_ref().expect("filtered above");-                let clipped = clip_geometry(p, &rect);-                let local = geom::to_tile(&clipped, tx, ty, opts.extent);-                let simplified = simplify::simplify(&local, tolerance);-                if simplified.is_empty() {-                    continue;+        // Across tiles, not within one: a tile holds a handful of features, so mapping+        // its clip loop over the pool costs more in scheduling than the clipping is+        // worth. Tiles are independent and there are many, which is the seam. The fold+        // below is sequential and in `tile_id` order, so `stats` and the archive are+        // exactly what the serial version produced.+        for chunk in tiles.chunks(par::batch_len()) {+            let done: Vec<Option<EncodedTile>> = par::install(|| {+                chunk+                    .par_iter()+                    .with_min_len(par::MIN_TASK_LEN)+                    .map_init(crate::gz::Compressor::new, |gz, &(id, tx, ty)| {+                        let indices = &by_tile[&(tx, ty)];+                        let rect = geom::tile_rect(tx, ty, opts.extent, buffer);++                        // Clip, move into the tile, simplify. Anything that vanishes+                        // here never reached the tile in the first place, so it is not+                        // a "drop".+                        let mut placed: Vec<(usize, i64, IntGeometry)> =+                            Vec::with_capacity(indices.len());+                        for &i in indices {+                            let p = projected[i].as_ref().expect("filtered above");+                            let clipped = clip_geometry(p, &rect);+                            let local = geom::to_tile(&clipped, tx, ty, opts.extent);+                            let simplified = simplify::simplify(&local, tolerance);+                            if simplified.is_empty() {+                                continue;+                            }+                            placed.push((i, extent_of(&simplified), simplified));+                        }+                        if placed.is_empty() {+                            return Ok(None);+                        }++                        let mut candidates: Vec<TileCandidate> = placed+                            .iter()+                            .map(|(i, extent, g)| TileCandidate {+                                seq: *i as u64,+                                geom: g,+                                props: &features[*i].props,+                                extent: *extent,+                            })+                            .collect();+                        candidates.sort_by(by_importance);++                        let (body, kept, over) =+                            fit_tile(&candidates, &opts.layer, geom_type, opts, gz)?;+                        Ok(Some(EncodedTile {+                            id,+                            body,+                            kept,+                            over_budget: over,+                            placed: candidates.len(),+                        }))+                    })+                    .collect::<Result<Vec<_>>>()+            })?;++            for one in done {+                bar.tick(CANDIDATES);+                let Some(t) = one else { continue };+                stats.placed += t.placed;+                stats.kept += t.kept;+                stats.dropped += t.placed - t.kept;+                if t.over_budget {+                    stats.over_budget += 1;                 }-                candidates.push((i, simplified));-            }-            if candidates.is_empty() {-                continue;-            }-            stats.placed += candidates.len();--            // The stable importance order: largest first, index breaking ties.-            candidates.sort_by(|a, b| {-                extent_of(&b.1)-                    .cmp(&extent_of(&a.1))-                    .then_with(|| a.0.cmp(&b.0))-            });--            let (body, kept, over) = fit_tile(&candidates, features, &opts.layer, geom_type, opts)?;-            stats.kept += kept;-            stats.dropped += candidates.len() - kept;-            if over {-                stats.over_budget += 1;+                stats.largest_tile_bytes = stats.largest_tile_bytes.max(t.body.len());+                stats.tiles += 1;+                builder.add_tile_raw(t.id, t.body);             }-            stats.largest_tile_bytes = stats.largest_tile_bytes.max(body.len());-            stats.tiles += 1;-            builder.add_tile_raw(pmtiles::tile_id(z, tx, ty), body);         }         bar.finish(CANDIDATES);         report.push(stats);@@ -234,17 +401,17 @@ pub fn build_archive(features: &[Feature], opts: &Options) -> Result<(Vec<u8>, V /// over budget -- which happens when even a single feature does not fit, and is the /// one case worth telling the operator about. fn fit_tile(-    candidates: &[(usize, IntGeometry)],-    features: &[Feature],+    candidates: &[TileCandidate],     layer_name: &str,     geom_type: GeomType,     opts: &Options,+    gz: &mut crate::gz::Compressor, ) -> Result<(Vec<u8>, usize, bool)> {-    let encode = |n: usize| -> Vec<u8> {+    let mut encode = |n: usize| -> Vec<u8> {         let mut layer = Layer::new(layer_name);         layer.extent = opts.extent;-        for (i, g) in &candidates[..n] {-            let geometry = match g {+        for c in &candidates[..n] {+            let geometry = match c.geom {                 IntGeometry::Points(p) => mvt::encode_points(p),                 IntGeometry::Lines(l) => mvt::encode_lines(l),                 IntGeometry::Polygons(p) => mvt::encode_polygons(p),@@ -256,10 +423,10 @@ fn fit_tile(                 id: None,                 geom_type,                 geometry,-                props: features[*i].props.clone(),+                props: c.props.to_vec(),             });         }-        crate::gz::compress(&Tile { layers: vec![layer] }.encode())+        gz.compress(&Tile { layers: vec![layer] }.encode())     };      let all = encode(candidates.len());@@ -317,30 +484,37 @@ fn extent_of(g: &IntGeometry) -> i64 { /// and applying it throughout makes that mistake visible as wrong rendering rather /// than hiding it as a silently split layer. fn dominant_geom_type(features: &[Feature]) -> GeomType {-    match features.first().map(|f| &f.geometry) {-        Some(Geometry::Points(_)) => GeomType::Point,-        Some(Geometry::Lines(_)) => GeomType::LineString,-        Some(Geometry::Polygons(_)) => GeomType::Polygon,+    geom_type_of(features.first().map(|f| GeomKind::of(&f.geometry)))+}++/// The same rule, from a kind a source reported rather than a feature in hand.+fn geom_type_of(kind: Option<GeomKind>) -> GeomType {+    match kind {+        Some(GeomKind::Points) => GeomType::Point,+        Some(GeomKind::Lines) => GeomType::LineString,+        Some(GeomKind::Polygons) => GeomType::Polygon,         None => GeomType::Unknown,     } }  fn lonlat_bounds(features: &[Feature]) -> Option<geom::Rect> {-    let mut acc: Option<geom::Rect> = None;-    for f in features {-        if let Some(b) = geom::bounds(&f.geometry) {-            acc = Some(match acc {-                None => b,-                Some(a) => geom::Rect {-                    min_x: a.min_x.min(b.min_x),-                    min_y: a.min_y.min(b.min_y),-                    max_x: a.max_x.max(b.max_x),-                    max_y: a.max_y.max(b.max_y),-                },-            });-        }-    }-    acc+    features.iter().fold(None, |acc, f| fold_bounds(acc, &f.geometry))+}++/// Grow `acc` to cover `g`. The whole of [`lonlat_bounds`], so the streaming path can+/// fold the same function over a source it only ever sees one feature at a time and+/// arrive at the same header bytes.+pub fn fold_bounds(acc: Option<geom::Rect>, g: &Geometry) -> Option<geom::Rect> {+    let Some(b) = geom::bounds(g) else { return acc };+    Some(match acc {+        None => b,+        Some(a) => geom::Rect {+            min_x: a.min_x.min(b.min_x),+            min_y: a.min_y.min(b.min_y),+            max_x: a.max_x.max(b.max_x),+            max_y: a.max_y.max(b.max_y),+        },+    }) }  fn e7(deg: f64) -> i32 {@@ -357,6 +531,552 @@ fn metadata(layer_name: &str, min_zoom: u8, max_zoom: u8) -> String {     ) } +// --- the streaming producer -----------------------------------------------++/// How much disk and recursion the streaming producer may use.+pub struct StreamLimits {+    /// Buckets per partition level. Must be a power of four so a bucket is exactly one+    /// quadtree cell's descendants, and must stay under the process's file-descriptor+    /// limit — see [`crate::spill::BucketSet`].+    pub buckets: usize,+    /// A bucket over this many bytes is re-partitioned rather than loaded. This is the+    /// number that sets peak memory, because a loaded bucket is resident.+    pub bucket_budget_bytes: u64,+    pub max_repartition_depth: u32,+}++/// 256 buckets: four levels of the quadtree per partition, and well under any+/// descriptor limit.+pub const DEFAULT_BUCKETS: usize = 256;++/// 512 MiB of encoded records per bucket. Decoded they cost more, so this is a budget+/// on the spill bytes rather than a promise about RSS; Phase 6's measurement is what+/// turns it into one.+pub const DEFAULT_BUCKET_BUDGET_BYTES: u64 = 512 << 20;++/// Recursion cap, so a pathological range cannot spin.+///+/// Not the thing that terminates the recursion: a child's span is its parent's range+/// divided by the bucket count, so it strictly shrinks and the single-`tile_id` floor is+/// always reached. This is the backstop, and it has to have room for the smallest useful+/// bucket count — 4 buckets need one level per zoom, so 24 covers z16 with headroom+/// while 8 would refuse a build the partition could have finished.+pub const DEFAULT_MAX_REPARTITION_DEPTH: u32 = 24;++impl Default for StreamLimits {+    fn default() -> StreamLimits {+        StreamLimits {+            buckets: DEFAULT_BUCKETS,+            bucket_budget_bytes: DEFAULT_BUCKET_BUDGET_BYTES,+            max_repartition_depth: DEFAULT_MAX_REPARTITION_DEPTH,+        }+    }+}++/// A rewindable feature stream, which is all [`build_archive_to`] needs of its input.+///+/// Rewindable because the producer makes one pass per zoom: six passes over a compact+/// binary is far cheaper than six re-parses of planet GeoJSON, and it is what lets the+/// features not be resident.+///+/// `bounds` and `geom_kind` come from a fold the caller already did while writing the+/// source, so there is no bounds pre-pass:+/// [`crate::pmtiles::StreamBuilder`] serialises its header last.+pub trait FeatureSource {+    fn rewind(&mut self) -> Result<()>;+    fn next(&mut self) -> Result<Option<Feature>>;+    /// How many features a pass will yield, for the progress bar.+    fn len(&self) -> u64;+    fn is_empty(&self) -> bool {+        self.len() == 0+    }+    fn bounds(&self) -> Option<geom::Rect>;+    /// The FIRST feature's kind, the rule [`dominant_geom_type`] already applies.+    fn geom_kind(&self) -> Option<GeomKind>;+}++/// A [`FeatureSource`] over features already in memory.+///+/// What the byte-identity tests drive the streaming producer from, so they need no+/// temporary input file and compare exactly the same features the in-memory path saw.+pub struct SliceSource<'a> {+    features: &'a [Feature],+    at: usize,+    bounds: Option<geom::Rect>,+    kind: Option<GeomKind>,+}++impl<'a> SliceSource<'a> {+    pub fn new(features: &'a [Feature]) -> SliceSource<'a> {+        SliceSource {+            features,+            at: 0,+            bounds: lonlat_bounds(features),+            kind: features.first().map(|f| GeomKind::of(&f.geometry)),+        }+    }+}++impl FeatureSource for SliceSource<'_> {+    fn rewind(&mut self) -> Result<()> {+        self.at = 0;+        Ok(())+    }++    fn next(&mut self) -> Result<Option<Feature>> {+        let f = self.features.get(self.at).cloned();+        if f.is_some() {+            self.at += 1;+        }+        Ok(f)+    }++    fn len(&self) -> u64 {+        self.features.len() as u64+    }++    fn bounds(&self) -> Option<geom::Rect> {+        self.bounds+    }++    fn geom_kind(&self) -> Option<GeomKind> {+        self.kind+    }+}++/// A [`FeatureSource`] over [`crate::spill`]'s normalized file. The production path.+pub struct NormalizedSource {+    reader: spill::NormalizedReader,+    summary: spill::NormalizedSummary,+}++impl NormalizedSource {+    /// `summary` is what [`crate::spill::NormalizedWriter::finish`] returned for this+    /// file. Passed in rather than re-derived, because deriving it would be the pre-pass+    /// the design exists to avoid.+    pub fn open(+        path: impl Into<std::path::PathBuf>,+        summary: spill::NormalizedSummary,+    ) -> Result<NormalizedSource> {+        Ok(NormalizedSource {+            reader: spill::NormalizedReader::open(path)?,+            summary,+        })+    }+}++impl FeatureSource for NormalizedSource {+    fn rewind(&mut self) -> Result<()> {+        self.reader.rewind()+    }++    fn next(&mut self) -> Result<Option<Feature>> {+        Ok(self.reader.next()?.map(|f| Feature {+            geometry: f.geometry,+            props: f.props,+        }))+    }++    fn len(&self) -> u64 {+        self.summary.count+    }++    fn bounds(&self) -> Option<geom::Rect> {+        self.summary.bounds+    }++    fn geom_kind(&self) -> Option<GeomKind> {+        self.summary.geom_kind+    }+}++/// Features bucketed in one zoom's first pass.+const BUCKETED: &str = "feature(s) bucketed";++/// Spill records encoded in one zoom's second pass.+const ENCODED: &str = "record(s) encoded";++/// Build the archive straight to `out`, with peak memory set by the tile count.+///+/// The same drop policy, the same encoder and the same [`ZoomStats`] as+/// [`build_archive`] — which stays as the oracle the byte-identity tests pin this+/// against — but nothing proportional to the input bytes is ever resident. Per zoom:+///+/// 1. **The bucket pass** rewinds `src`, projects each feature once, finds the tiles it+///    touches, and for each of them clips, moves into the tile and simplifies, writing a+///    [`crate::spill`] record. Empties are skipped exactly as [`build_archive`] skips+///    them, so `placed` counts the same things.+/// 2. **The encode pass** walks the buckets in ascending index, re-partitioning any that+///    exceed the budget, and for each loaded bucket sorts by `(tile_id, importance)`,+///    groups runs of equal `tile_id`, and calls the same [`fit_tile`].+///+/// The bucket set is dropped at the end of each zoom, so peak spill disk is the largest+/// SINGLE zoom rather than the sum of them — `tile_id` is zoom-major, so every id at+/// `z` precedes every id at `z+1` and a zoom can be finished before the next begins.+///+/// I/O, with `F` the source, `S_z` a zoom's spill, `T` the archive and `Z` zooms:+/// `read(F) · Z + write(S_z) + read(S_z)` per zoom, plus `3·T` for the writer's scratch+/// round trip. Disk peak is `F + max(S_z) + T`, plus one full copy of an over-budget+/// bucket per level of re-partition below it — an ancestor set's files stay alive while+/// its children are drained, so a heavily skewed metro range costs+/// `depth × that bucket's bytes` on top.+pub fn build_archive_to(+    out: impl AsRef<Path>,+    scratch_dir: impl AsRef<Path>,+    opts: &Options,+    src: &mut impl FeatureSource,+    limits: &StreamLimits,+) -> Result<Vec<ZoomStats>> {+    if opts.min_zoom > opts.max_zoom {+        return err("minzoom is above maxzoom");+    }+    if opts.extent == 0 {+        return err("extent 0");+    }+    // This path needs `zoom_base(max_zoom + 1)` for the bucket range, which+    // `build_archive` never computes and which overflows above z30. Refused rather than+    // left to panic: the in-memory path merely produces nonsense that deep, and a+    // message is a better failure than a shift overflow.+    if opts.max_zoom > 30 {+        return err(format!(+            "maxzoom {} is above 30, the deepest zoom a PMTiles tile id is exact at",+            opts.max_zoom+        ));+    }+    let out = out.as_ref();+    let scratch_dir = scratch_dir.as_ref();+    std::fs::create_dir_all(scratch_dir)+        .map_err(|e| Error(format!("cannot create {}: {e}", scratch_dir.display())))?;++    let geom_type = geom_type_of(src.geom_kind());+    let buffer = geom::buffer_for(opts.extent);++    // Beside the OUTPUT, not in the spill directory: `finish` copies this section into+    // the archive, and a cross-filesystem copy of 40 GB would be needlessly slow.+    let tile_scratch = {+        let mut p = out.as_os_str().to_owned();+        p.push(".tiledata");+        std::path::PathBuf::from(p)+    };+    let mut builder = pmtiles::StreamBuilder::new(tile_scratch)?;+    builder.min_zoom = opts.min_zoom;+    builder.max_zoom = opts.max_zoom;+    builder.center_zoom = opts.min_zoom;+    builder.metadata = metadata(&opts.layer, opts.min_zoom, opts.max_zoom).into_bytes();+    match src.bounds() {+        Some(b) => {+            builder.min_lon_e7 = e7(b.min_x);+            builder.min_lat_e7 = e7(b.min_y);+            builder.max_lon_e7 = e7(b.max_x);+            builder.max_lat_e7 = e7(b.max_y);+            builder.center_lon_e7 = e7((b.min_x + b.max_x) / 2.0);+            builder.center_lat_e7 = e7((b.min_y + b.max_y) / 2.0);+        }+        // `Builder::new` defaults latitude to +/-850_511_290 and `StreamBuilder::new` to+        // +/-850_511_287. Three units, and on an input with no bounds nothing else+        // overwrites them -- so leaving them alone would make the two producers disagree+        // on an empty archive's header.+        None => {+            builder.min_lon_e7 = -1_800_000_000;+            builder.min_lat_e7 = -850_511_290;+            builder.max_lon_e7 = 1_800_000_000;+            builder.max_lat_e7 = 850_511_290;+        }+    }++    let mut report = Vec::new();+    for z in opts.min_zoom..=opts.max_zoom {+        let mut stats = ZoomStats { zoom: z, ..Default::default() };+        let tolerance = simplify::tolerance_for(z, opts.max_zoom, opts.simplification);++        // Named per zoom so a set cannot be mistaken for the previous zoom's, and+        // scoped to the zoom so its files go before the next one allocates disk.+        let mut set = spill::BucketSet::new(+            scratch_dir,+            &format!("z{z}"),+            pmtiles::zoom_base(z),+            pmtiles::zoom_base(z + 1),+            limits.buckets,+        )?;++        src.rewind()?;+        let mut bar = Progress::new(+            format!("{} z{z} bucket", opts.layer),+            src.len() as usize,+            BUCKETED,+            opts.progress,+        );+        let mut touched: Vec<(u64, u64)> = Vec::new();+        let mut rec = Vec::new();+        let mut seq = 0u64;+        // Read serially, project and clip across the pool, push serially.+        //+        // The source is a `&mut` cursor and the bucket writers are buffered files, so+        // neither end threads; everything between them -- projection, clipping,+        // simplification, record encoding -- is per-feature pure and is where the time+        // goes. Live memory is one batch's records, which is what bounds the batch.+        //+        // Push order does not matter to the output: `encode_buckets` sorts each bucket+        // by the total key `(tile_id, extent, seq)`, and `seq` is the feature's index in+        // the source, not its arrival order. Pushing in batch order anyway costs nothing+        // and keeps the spill files themselves reproducible.+        let batch_len = par::batch_len();+        let mut batch: Vec<Feature> = Vec::with_capacity(batch_len);+        loop {+            batch.clear();+            while batch.len() < batch_len {+                match src.next()? {+                    Some(f) => batch.push(f),+                    None => break,+                }+            }+            if batch.is_empty() {+                break;+            }+            let first = seq;+            let encoded: Vec<Result<BucketedFeature>> = if batch.len() == 1 {+                // One feature is not worth a pool round trip, and this is the path the+                // single-threaded case and the tail of every stream take.+                vec![bucket_feature(+                    &batch[0],+                    first,+                    z,+                    opts,+                    buffer,+                    tolerance,+                    &mut touched,+                    &mut rec,+                )]+            } else {+                par::install(|| {+                    batch+                        .par_iter()+                        .enumerate()+                        .with_min_len(par::MIN_TASK_LEN)+                        .map_init(+                            || (Vec::new(), Vec::new()),+                            |(touched, rec), (i, f)| {+                                bucket_feature(+                                    f,+                                    first + i as u64,+                                    z,+                                    opts,+                                    buffer,+                                    tolerance,+                                    touched,+                                    rec,+                                )+                            },+                        )+                        .collect()+                })+            };+            for one in encoded {+                let one = one?;+                for &(id, at, len) in &one.spans {+                    set.push(id, &one.blob[at..at + len])?;+                }+                bar.tick(BUCKETED);+            }+            seq += batch.len() as u64;+        }+        bar.finish(BUCKETED);+        set.seal()?;++        let mut bar = Progress::new(+            format!("{} z{z} encode", opts.layer),+            set.total_records() as usize,+            ENCODED,+            opts.progress,+        );+        encode_buckets(+            &set,+            scratch_dir,+            z,+            0,+            opts,+            geom_type,+            limits,+            &mut builder,+            &mut stats,+            &mut bar,+        )?;+        bar.finish(ENCODED);+        report.push(stats);+    }++    builder.finish(out)?;+    Ok(report)+}++/// Drain one bucket set in ascending index, recursing into anything over budget.+///+/// Sub-buckets ascend within a parent and parents ascend, so the ids handed to+/// [`crate::pmtiles::StreamBuilder`] ascend at every depth.+#[allow(clippy::too_many_arguments)]+fn encode_buckets(+    set: &spill::BucketSet,+    scratch_dir: &Path,+    z: u8,+    depth: u32,+    opts: &Options,+    geom_type: GeomType,+    limits: &StreamLimits,+    builder: &mut pmtiles::StreamBuilder,+    stats: &mut ZoomStats,+    bar: &mut Progress,+) -> Result<()> {+    for i in 0..set.len() {+        let records = set.records_in(i);+        if records == 0 {+            continue;+        }+        let bytes = set.bytes_in(i);+        let (lo, hi) = set.range_of(i);++        if bytes > limits.bucket_budget_bytes {+            // `--buckets 1` would give a child covering exactly this range, so the split+            // is a no-op that copies the bucket once per level until the depth cap. A+            // split has to actually narrow the range to be worth doing.+            let splittable = hi - lo > 1+                && limits.buckets > 1+                && depth < limits.max_repartition_depth;+            if !splittable {+                // A single tile's candidates cannot be split any further, and capping+                // them would change which features survive -- an output change, and out+                // of scope. Erroring beats being killed by the OOM reaper halfway+                // through a planet run with nothing to show for it.+                if hi - lo == 1 {+                    let (_, x, y) = pmtiles::tile_zxy(lo);+                    return err(format!(+                        "z{z}/{x}/{y} alone holds {records} spill record(s) in {bytes} byte(s), \+                         over the {}-byte bucket budget; raise --bucket-budget-bytes",+                        limits.bucket_budget_bytes+                    ));+                }+                return err(format!(+                    "z{z} tile ids {lo}..{hi} hold {records} spill record(s) in {bytes} byte(s), \+                     over the {}-byte bucket budget, and the range cannot be split further \+                     (--buckets {}, --max-repartition-depth {}, depth {depth})",+                    limits.bucket_budget_bytes, limits.buckets, limits.max_repartition_depth+                ));+            }+            // `lo` is unique across every sibling at every depth, so the child's files+            // cannot collide with anyone else's.+            let mut child = spill::BucketSet::new(+                scratch_dir,+                &format!("z{z}_d{}_{lo}", depth + 1),+                lo,+                hi,+                limits.buckets,+            )?;+            let mut reader = set+                .reader(i)?+                .ok_or_else(|| Error(format!("bucket {i} of z{z} vanished mid-pass")))?;+            let mut buf = Vec::new();+            while let Some(r) = reader.next()? {+                buf.clear();+                r.encode(&mut buf)?;+                child.push(r.tile_id, &buf)?;+            }+            child.seal()?;+            encode_buckets(+                &child,+                scratch_dir,+                z,+                depth + 1,+                opts,+                geom_type,+                limits,+                builder,+                stats,+                bar,+            )?;+            continue;+        }++        let mut recs = set.load(i)?;+        // The total sort key: tile id first, then the drop policy's own order, so a+        // group is already in importance order when `fit_tile` sees it.+        recs.sort_by(|a, b| {+            a.tile_id+                .cmp(&b.tile_id)+                .then_with(|| by_importance_keys(a.extent, a.seq, b.extent, b.seq))+        });++        // Runs of equal `tile_id`. Each run is one candidate tile, and `fit_tile` is+        // pure -- all-shared refs, a fresh `Layer`/`Tile` per call, no statics -- so the+        // runs are independent and that is the seam.+        //+        // Parallel WITHIN a bucket rather than across buckets: one bucket is resident at+        // a time either way, so peak memory is unchanged and `--bucket-budget-bytes`+        // keeps meaning what it says. Going across buckets instead would hold one+        // decoded bucket per thread and turn a 690 MiB peak into ~22 GB at 32 threads.+        let mut groups: Vec<(usize, usize)> = Vec::new();+        let mut k = 0usize;+        while k < recs.len() {+            let id = recs[k].tile_id;+            let mut j = k;+            while j < recs.len() && recs[j].tile_id == id {+                j += 1;+            }+            groups.push((k, j));+            k = j;+        }++        let encode_group = |gz: &mut crate::gz::Compressor,+                            &(k, j): &(usize, usize)|+         -> Result<EncodedTile> {+            let candidates: Vec<TileCandidate> = recs[k..j]+                .iter()+                .map(|r| TileCandidate {+                    seq: r.seq,+                    geom: &r.geom,+                    props: &r.props,+                    extent: r.extent,+                })+                .collect();+            let (body, kept, over) = fit_tile(&candidates, &opts.layer, geom_type, opts, gz)?;+            Ok(EncodedTile {+                id: recs[k].tile_id,+                body,+                kept,+                over_budget: over,+                placed: candidates.len(),+            })+        };++        // A batch at a time, so live memory is a bounded number of encoded bodies+        // rather than every body in the bucket. The fold below is sequential and in+        // ascending group order, which is what keeps `add_tile_raw` fed ascending ids+        // and the `stats` sums and `largest_tile_bytes` max identical to a serial run.+        for chunk in groups.chunks(par::batch_len()) {+            let done: Vec<EncodedTile> = par::install(|| {+                chunk+                    .par_iter()+                    .with_min_len(par::MIN_TASK_LEN)+                    .map_init(crate::gz::Compressor::new, encode_group)+                    .collect::<Result<Vec<_>>>()+            })?;+            for t in done {+                for _ in 0..t.placed {+                    bar.tick(ENCODED);+                }+                stats.placed += t.placed;+                stats.kept += t.kept;+                stats.dropped += t.placed - t.kept;+                if t.over_budget {+                    stats.over_budget += 1;+                }+                stats.largest_tile_bytes = stats.largest_tile_bytes.max(t.body.len());+                stats.tiles += 1;+                builder.add_tile_raw(t.id, &t.body)?;+            }+        }+    }+    Ok(())+}+ /// Print the per-zoom report the drop policy owes the operator. pub fn print_report(report: &[ZoomStats], out: &mut impl std::io::Write) -> std::io::Result<()> {     writeln!(out, "  zoom  tiles   placed     kept  dropped  largest")?;@@ -411,12 +1131,20 @@ impl Accept { /// [`Accept`], so they share one implementation and differ only in the name they /// print. pub fn cli_main(name: &str, accept: Accept, argv: &[String]) -> std::process::ExitCode {+    use std::io::BufRead;     use std::process::ExitCode;      let usage = || {         eprintln!("usage: {name} --geojson IN.geojsonseq --out OUT.pmtiles --layer NAME");         eprintln!("                  [--minzoom N] [--maxzoom N] [--simplification F]");-        eprintln!("                  [--max-tile-bytes N] [--extent N]");+        eprintln!("                  [--max-tile-bytes N] [--extent N] [--threads N]");+        eprintln!("                  [--stream [--spill-dir DIR] [--buckets N]");+        eprintln!("                            [--bucket-budget-bytes N] [--max-repartition-depth N]]");+        eprintln!();+        eprintln!("  --stream  keep peak memory proportional to the TILE COUNT rather than the");+        eprintln!("            input bytes, by spilling to --spill-dir. Required for a");+        eprintln!("            planet-scale layer; unnecessary for a metro extract. Output is");+        eprintln!("            byte-identical either way.");     };      let mut geojson = None;@@ -427,6 +1155,9 @@ pub fn cli_main(name: &str, accept: Accept, argv: &[String]) -> std::process::Ex     let mut simplification = 1.0f64;     let mut max_tile_bytes = DEFAULT_MAX_TILE_BYTES;     let mut extent = DEFAULT_EXTENT;+    let mut stream = false;+    let mut spill_dir: Option<String> = None;+    let mut limits = StreamLimits::default();      let mut i = 0;     while i < argv.len() {@@ -444,11 +1175,20 @@ pub fn cli_main(name: &str, accept: Accept, argv: &[String]) -> std::process::Ex                 layer = value();                 i += 2;             }+            "--stream" => {+                stream = true;+                i += 1;+            }+            "--spill-dir" => {+                spill_dir = value();+                i += 2;+            }             // A bad numeric value is fatal rather than falling back to the default:             // silently tiling z11-14 when the caller asked for z0-8 produces an             // archive that looks fine and is wrong.             flag @ ("--minzoom" | "--maxzoom" | "--simplification" | "--max-tile-bytes"-            | "--extent") => {+            | "--extent" | "--buckets" | "--bucket-budget-bytes"+            | "--max-repartition-depth") => {                 let Some(raw) = value() else {                     eprintln!("{name}: {flag} needs a value");                     return ExitCode::from(2);@@ -458,7 +1198,12 @@ pub fn cli_main(name: &str, accept: Accept, argv: &[String]) -> std::process::Ex                     "--maxzoom" => raw.parse().map(|v| max_zoom = v).is_ok(),                     "--simplification" => raw.parse().map(|v| simplification = v).is_ok(),                     "--max-tile-bytes" => raw.parse().map(|v| max_tile_bytes = v).is_ok(),-                    _ => raw.parse().map(|v| extent = v).is_ok(),+                    "--extent" => raw.parse().map(|v| extent = v).is_ok(),+                    "--buckets" => raw.parse().map(|v| limits.buckets = v).is_ok(),+                    "--bucket-budget-bytes" => {+                        raw.parse().map(|v| limits.bucket_budget_bytes = v).is_ok()+                    }+                    _ => raw.parse().map(|v| limits.max_repartition_depth = v).is_ok(),                 };                 if !ok {                     eprintln!("{name}: {flag} wants a number, got '{raw}'");@@ -466,6 +1211,20 @@ pub fn cli_main(name: &str, accept: Accept, argv: &[String]) -> std::process::Ex                 }                 i += 2;             }+            "--threads" => {+                let Some(raw) = value() else {+                    eprintln!("{name}: --threads needs a value");+                    return ExitCode::from(2);+                };+                match par::parse_threads(&raw) {+                    Ok(n) => par::set_threads(n),+                    Err(e) => {+                        eprintln!("{name}: {e}");+                        return ExitCode::from(2);+                    }+                }+                i += 2;+            }             "-h" | "--help" => {                 usage();                 return ExitCode::SUCCESS;@@ -487,45 +1246,16 @@ pub fn cli_main(name: &str, accept: Accept, argv: &[String]) -> std::process::Ex         eprintln!("{name}: --minzoom {min_zoom} is above --maxzoom {max_zoom}");         return ExitCode::from(2);     }--    let text = match std::fs::read_to_string(&geojson) {-        Ok(t) => t,-        Err(e) => {-            eprintln!("{name}: cannot read {geojson}: {e}");-            return ExitCode::FAILURE;-        }-    };--    let mut features = Vec::new();-    let mut skipped = 0usize;-    for (n, line) in text.lines().enumerate() {-        let line = line.trim();-        if line.is_empty() {-            continue;-        }-        match crate::geojson::parse_feature(line) {-            Some(f) if accept.matches(&f.geometry) => features.push(Feature {-                geometry: f.geometry,-                props: f.props,-            }),-            _ => {-                skipped += 1;-                if skipped <= 5 {-                    eprintln!(-                        "{name}: skipping line {} (not a {})",-                        n + 1,-                        accept.describe()-                    );-                }-            }-        }-    }-    if skipped > 5 {-        eprintln!("{name}: ... and {} more skipped line(s)", skipped - 5);-    }-    if features.is_empty() {-        eprintln!("{name}: no {} features in {geojson}", accept.describe());-        return ExitCode::FAILURE;+    // Checked before the parse pass rather than after it: a bad bucket count would+    // otherwise fail an hour into a planet run, having already written the whole+    // normalized file.+    if stream && (!limits.buckets.is_power_of_two() || limits.buckets.trailing_zeros() % 2 != 0) {+        eprintln!(+            "{name}: --buckets must be a power of four so a bucket is one quadtree cell, \+             got {}",+            limits.buckets+        );+        return ExitCode::from(2);     }      let opts = Options {@@ -538,24 +1268,179 @@ pub fn cli_main(name: &str, accept: Accept, argv: &[String]) -> std::process::Ex         // A planet layer spends minutes to hours per zoom, so the operator gets a bar.         progress: true,     };-    let (bytes, report) = match build_archive(&features, &opts) {-        Ok(v) => v,++    // Read a line at a time rather than slurping the file: a planet geojsonseq is tens+    // of gigabytes and `read_to_string` keeps all of it resident alongside whatever the+    // parse produces, so the two peaks land together for no reason.+    let file = match std::fs::File::open(&geojson) {+        Ok(f) => f,         Err(e) => {-            eprintln!("{name}: {e}");+            eprintln!("{name}: cannot read {geojson}: {e}");             return ExitCode::FAILURE;         }     };-    if let Err(e) = std::fs::write(&out, &bytes) {-        eprintln!("{name}: cannot write {out}: {e}");-        return ExitCode::FAILURE;+    let mut lines = std::io::BufReader::with_capacity(1 << 20, file).lines();++    if stream {+        let spill_dir = spill_dir.unwrap_or_else(|| format!("{out}.spill"));+        // Both temporaries clean themselves up, so a run that dies mid-planet cannot+        // strand tens of gigabytes in a directory nobody is watching.+        let normalized = crate::spill::NormalizedFile::new(+            std::path::Path::new(&spill_dir).join("features.bin"),+        );+        let mut writer = match crate::spill::NormalizedWriter::create(normalized.path()) {+            Ok(w) => w,+            Err(e) => {+                eprintln!("{name}: {e}");+                return ExitCode::FAILURE;+            }+        };+        let mut skipped = 0usize;+        let mut n = 0usize;+        for line in lines.by_ref() {+            let line = match line {+                Ok(l) => l,+                Err(e) => {+                    eprintln!("{name}: cannot read {geojson}: {e}");+                    return ExitCode::FAILURE;+                }+            };+            n += 1;+            let line = line.trim();+            if line.is_empty() {+                continue;+            }+            match crate::geojson::parse_feature(line) {+                Some(f) if accept.matches(&f.geometry) => {+                    if let Err(e) = writer.push(&f.geometry, &f.props) {+                        eprintln!("{name}: {e}");+                        return ExitCode::FAILURE;+                    }+                }+                _ => {+                    skipped += 1;+                    writer.skip();+                    if skipped <= 5 {+                        eprintln!("{name}: skipping line {n} (not a {})", accept.describe());+                    }+                }+            }+        }+        if skipped > 5 {+            eprintln!("{name}: ... and {} more skipped line(s)", skipped - 5);+        }+        let summary = match writer.finish() {+            Ok(s) => s,+            Err(e) => {+                eprintln!("{name}: {e}");+                return ExitCode::FAILURE;+            }+        };+        if summary.count == 0 {+            eprintln!("{name}: no {} features in {geojson}", accept.describe());+            return ExitCode::FAILURE;+        }+        eprintln!(+            "{name}: normalized {} feature(s) into {}",+            summary.count,+            normalized.path().display()+        );++        let count = summary.count;+        let mut src = match NormalizedSource::open(normalized.path(), summary) {+            Ok(s) => s,+            Err(e) => {+                eprintln!("{name}: {e}");+                return ExitCode::FAILURE;+            }+        };+        let report = match build_archive_to(&out, &spill_dir, &opts, &mut src, &limits) {+            Ok(r) => r,+            Err(e) => {+                eprintln!("{name}: {e}");+                return ExitCode::FAILURE;+            }+        };+        // Only if empty: every bucket set and the normalized file remove themselves, so+        // anything left here is a leftover worth seeing rather than deleting.+        drop(src);+        drop(normalized);+        let _ = std::fs::remove_dir(&spill_dir);++        let size = std::fs::metadata(&out).map(|m| m.len()).unwrap_or(0);+        eprintln!(+            "{name}: wrote {out} ({:.1} MiB): {count} feature(s), layer '{layer}', \+             z{min_zoom}-{max_zoom}",+            size as f64 / (1024.0 * 1024.0),+        );+        report_and_exit(name, &report, max_tile_bytes)+    } else {+        let mut features = Vec::new();+        let mut skipped = 0usize;+        let mut n = 0usize;+        for line in lines.by_ref() {+            let line = match line {+                Ok(l) => l,+                Err(e) => {+                    eprintln!("{name}: cannot read {geojson}: {e}");+                    return ExitCode::FAILURE;+                }+            };+            n += 1;+            let line = line.trim();+            if line.is_empty() {+                continue;+            }+            match crate::geojson::parse_feature(line) {+                Some(f) if accept.matches(&f.geometry) => features.push(Feature {+                    geometry: f.geometry,+                    props: f.props,+                }),+                _ => {+                    skipped += 1;+                    if skipped <= 5 {+                        eprintln!("{name}: skipping line {n} (not a {})", accept.describe());+                    }+                }+            }+        }+        if skipped > 5 {+            eprintln!("{name}: ... and {} more skipped line(s)", skipped - 5);+        }+        if features.is_empty() {+            eprintln!("{name}: no {} features in {geojson}", accept.describe());+            return ExitCode::FAILURE;+        }++        let (bytes, report) = match build_archive(&features, &opts) {+            Ok(v) => v,+            Err(e) => {+                eprintln!("{name}: {e}");+                return ExitCode::FAILURE;+            }+        };+        if let Err(e) = std::fs::write(&out, &bytes) {+            eprintln!("{name}: cannot write {out}: {e}");+            return ExitCode::FAILURE;+        }+        eprintln!(+            "{name}: wrote {out} ({:.1} MiB): {} feature(s), layer '{layer}', \+             z{min_zoom}-{max_zoom}",+            bytes.len() as f64 / (1024.0 * 1024.0),+            features.len(),+        );+        report_and_exit(name, &report, max_tile_bytes)     }+} -    eprintln!(-        "{name}: wrote {out} ({:.1} MiB): {} feature(s), layer '{layer}', z{min_zoom}-{max_zoom}",-        bytes.len() as f64 / (1024.0 * 1024.0),-        features.len(),-    );-    let _ = print_report(&report, &mut std::io::stderr());+/// The per-zoom report and the drop summary, shared by both paths so a `--stream` build+/// tells the operator exactly what a non-streamed one does.+fn report_and_exit(+    name: &str,+    report: &[ZoomStats],+    max_tile_bytes: usize,+) -> std::process::ExitCode {+    let _ = print_report(report, &mut std::io::stderr());     let dropped: usize = report.iter().map(|s| s.dropped).sum();     if dropped > 0 {         eprintln!(@@ -563,7 +1448,7 @@ pub fn cli_main(name: &str, accept: Accept, argv: &[String]) -> std::process::Ex              per-tile budget"         );     }-    ExitCode::SUCCESS+    std::process::ExitCode::SUCCESS }  #[cfg(test)]@@ -918,4 +1803,446 @@ mod tests {         assert!(text.contains("z10"), "{text}");         assert!(text.contains("z11"), "{text}");     }++    // --- the streaming producer --------------------------------------------+    //+    // `build_archive` is covered by every test above, so pinning the streaming producer+    // against it byte for byte inherits all of it -- the drop policy, the importance+    // order, the simplification, the header, the deduplication, the run coalescing and+    // the directory split -- without restating any of it. This is the same contract+    // `tiling.rs`'s `the_streaming_join_is_byte_identical_to_the_in_memory_one` holds+    // the merge to.++    struct Scratch(std::path::PathBuf);++    impl Scratch {+        fn new(name: &str) -> Scratch {+            let d = std::env::temp_dir().join(format!(+                "tb_pyr_{}_{name}_{:?}",+                std::process::id(),+                std::thread::current().id()+            ));+            let _ = std::fs::remove_dir_all(&d);+            std::fs::create_dir_all(&d).unwrap();+            Scratch(d)+        }+    }++    impl Drop for Scratch {+        fn drop(&mut self) {+            let _ = std::fs::remove_dir_all(&self.0);+        }+    }++    /// Drive both producers from one `Vec<Feature>` and return the streamed bytes.+    ///+    /// Asserts the archive bytes AND the `ZoomStats` are equal, and that nothing was+    /// left behind in the scratch directory -- a stranded per-zoom bucket set would make+    /// peak disk the SUM of the zooms rather than the largest one.+    fn assert_identical(+        name: &str,+        features: &[Feature],+        opts: &Options,+        limits: &StreamLimits,+    ) -> Vec<u8> {+        let scratch = Scratch::new(name);+        let (want_bytes, want_report) = build_archive(features, opts).unwrap();++        let out = scratch.0.join("streamed.pmtiles");+        let mut src = SliceSource::new(features);+        let got_report = build_archive_to(&out, &scratch.0, opts, &mut src, limits).unwrap();+        let got_bytes = std::fs::read(&out).unwrap();++        assert_eq!(got_report, want_report, "{name}: the per-zoom reports differ");+        assert_eq!(+            got_bytes.len(),+            want_bytes.len(),+            "{name}: streamed {} bytes, in-memory {}",+            got_bytes.len(),+            want_bytes.len()+        );+        assert!(+            got_bytes == want_bytes,+            "{name}: the two archives differ byte for byte"+        );++        let leftovers: Vec<String> = std::fs::read_dir(&scratch.0)+            .unwrap()+            .filter_map(|e| e.ok())+            .map(|e| e.file_name().to_string_lossy().into_owned())+            .filter(|n| n != "streamed.pmtiles")+            .collect();+        assert!(+            leftovers.is_empty(),+            "{name}: the spill was left behind: {leftovers:?}"+        );+        assert!(+            !out.with_extension("pmtiles.tiledata").exists(),+            "{name}: the writer's scratch was left behind"+        );+        got_bytes+    }++    /// A fixture covering every branch the two producers could disagree on: a line+    /// spanning many tiles, a polygon with a hole, and two features with identical+    /// geometry so the `seq` tie-break in the importance order has to decide between+    /// them.+    fn mixed_fixture() -> Vec<Feature> {+        let mut features = vec![+            // Long enough at z11-12 to land in many tiles, which is what makes the+            // bucket partition non-trivial.+            line(&[(-124.0, 42.0), (-114.0, 33.0)], vec![("id", Value::Uint(0))]),+            square(-122.5, 37.7, 0.4, "A"),+        ];+        // A polygon with a hole.+        features.push(Feature {+            geometry: Geometry::Polygons(vec![vec![+                vec![+                    (-122.5, 37.7),+                    (-122.3, 37.7),+                    (-122.3, 37.9),+                    (-122.5, 37.9),+                    (-122.5, 37.7),+                ],+                vec![+                    (-122.45, 37.75),+                    (-122.35, 37.75),+                    (-122.35, 37.85),+                    (-122.45, 37.85),+                    (-122.45, 37.75),+                ],+            ]]),+            props: vec![("name".to_string(), Value::String("holey".into()))],+        });+        // Two identical geometries: tied on `extent_of`, so only `seq` orders them.+        for k in 0..2 {+            features.push(line(+                &[(-122.42, 37.77), (-122.40, 37.79)],+                vec![("tied", Value::Uint(k))],+            ));+        }+        features+    }++    #[test]+    fn the_streaming_producer_is_byte_identical_to_the_in_memory_one() {+        let features = mixed_fixture();+        let opts = Options::new("l", 10, 12);+        assert_identical("mixed", &features, &opts, &StreamLimits::default());+    }++    /// The drop policy is where the two could diverge without the output looking wrong,+    /// so it gets a budget tight enough to bite.+    #[test]+    fn the_streaming_producer_matches_under_a_tight_tile_budget() {+        let mut features = vec![line(+            &[(-122.45, 37.75), (-122.35, 37.85)],+            vec![("id", Value::String("long".into()))],+        )];+        for i in 0..200 {+            let d = i as f64 * 0.00005;+            features.push(line(+                &[(-122.40 + d, 37.80), (-122.3999 + d, 37.8001)],+                vec![("id", Value::String(format!("short{i}")))],+            ));+        }+        let mut opts = Options::new("l", 11, 11);+        opts.max_tile_bytes = 400;+        let (_, report) = build_archive(&features, &opts).unwrap();+        assert!(report[0].dropped > 0, "the fixture must drop: {:?}", report[0]);+        assert_identical("tight", &features, &opts, &StreamLimits::default());+    }++    /// The `over_budget` path: one feature that does not fit is kept anyway, and both+    /// producers must keep the same one and report it the same way.+    #[test]+    fn the_streaming_producer_matches_when_a_single_feature_is_over_budget() {+        let long: Vec<(f64, f64)> = (0..4000)+            .map(|i| (-122.42 + (i % 97) as f64 * 0.0001, 37.77 + (i % 89) as f64 * 0.0001))+            .collect();+        let features = vec![line(&long, vec![("name", Value::String("wiggly".into()))])];+        let mut opts = Options::new("l", 14, 14);+        opts.max_tile_bytes = 50;+        let (_, report) = build_archive(&features, &opts).unwrap();+        assert!(report[0].over_budget > 0, "the fixture must be over budget");+        assert_identical("overbudget", &features, &opts, &StreamLimits::default());+    }++    /// Re-partitioning a dense bucket is the expected path at planet scale, not an+    /// exotic one, so it gets its own byte-identity check rather than being trusted.+    ///+    /// Four buckets per level and a budget far below one zoom's spill forces recursion+    /// all the way down to single-tile ranges; the archive must not move by a byte.+    #[test]+    fn re_partitioning_does_not_perturb_a_byte() {+        let features = mixed_fixture();+        let opts = Options::new("l", 10, 12);+        let limits = StreamLimits {+            buckets: 4,+            // Well under one zoom's total spill and comfortably above one tile's, which+            // is what makes this a recursion test rather than an error test.+            bucket_budget_bytes: 2_000,+            max_repartition_depth: DEFAULT_MAX_REPARTITION_DEPTH,+        };+        assert_identical("recursion", &features, &opts, &limits);+    }++    /// The fixture whose drop policy actually bites: one long feature plus 200 short+    /// ones, at a budget that cannot hold them all.+    fn tight_fixture() -> Vec<Feature> {+        let mut features = vec![line(+            &[(-122.45, 37.75), (-122.35, 37.85)],+            vec![("id", Value::String("long".into()))],+        )];+        for i in 0..200 {+            let d = i as f64 * 0.00005;+            features.push(line(+                &[(-122.40 + d, 37.80), (-122.3999 + d, 37.8001)],+                vec![("id", Value::String(format!("short{i}")))],+            ));+        }+        features+    }++    /// The gate for threading the tilers: the thread count must change only how fast+    /// they run.+    ///+    /// Both producers, at 1, 2, 3 and 32 threads, against the serial result. Three is+    /// there on purpose — counts that divide neither the bucket count (256, or 4 in the+    /// recursion case) nor the batch length are the ones that catch an off-by-one in a+    /// chunked fold, and a count above the core count catches an ordering bug that a+    /// saturated pool would hide.+    ///+    /// Run over three cases, because they are three different code paths: the flat+    /// partition, the recursing one, and a budget tight enough that the drop policy+    /// runs — the last being the only one where a perturbed candidate order changes+    /// which features survive rather than merely where they land.+    #[test]+    fn the_thread_count_changes_no_bytes() {+        let recursing = StreamLimits {+            buckets: 4,+            bucket_budget_bytes: 2_000,+            max_repartition_depth: DEFAULT_MAX_REPARTITION_DEPTH,+        };+        let mut tight_opts = Options::new("l", 11, 11);+        tight_opts.max_tile_bytes = 400;++        let cases: Vec<(&str, Vec<Feature>, Options, StreamLimits)> = vec![+            (+                "flat",+                mixed_fixture(),+                Options::new("l", 10, 12),+                StreamLimits::default(),+            ),+            (+                "recursing",+                mixed_fixture(),+                Options::new("l", 10, 12),+                recursing,+            ),+            (+                "tight",+                tight_fixture(),+                tight_opts,+                StreamLimits::default(),+            ),+        ];++        for (tag, features, opts, limits) in cases {+            let run = |n: usize| {+                par::set_threads(n);+                let scratch = Scratch::new(&format!("threads_{tag}_{n}"));+                let (mem, mem_report) = build_archive(&features, &opts).unwrap();+                let out = scratch.0.join("streamed.pmtiles");+                let mut src = SliceSource::new(&features);+                let stream_report =+                    build_archive_to(&out, &scratch.0, &opts, &mut src, &limits).unwrap();+                (mem, mem_report, std::fs::read(&out).unwrap(), stream_report)+            };++            let (base_mem, base_mem_report, base_stream, base_stream_report) = run(1);+            // The property the whole crate rests on, restated at one thread so a+            // failure below cannot be blamed on the producers disagreeing.+            assert!(base_mem == base_stream, "{tag}: the producers disagree serially");++            for n in [2, 3, 32] {+                let (mem, mem_report, stream, stream_report) = run(n);+                assert_eq!(+                    mem_report, base_mem_report,+                    "{tag}: {n} threads changed the in-memory report"+                );+                assert_eq!(+                    stream_report, base_stream_report,+                    "{tag}: {n} threads changed the streamed report"+                );+                assert!(+                    mem == base_mem,+                    "{tag}: {n} threads perturbed the in-memory archive"+                );+                assert!(+                    stream == base_stream,+                    "{tag}: {n} threads perturbed the streamed archive"+                );+            }+        }+        par::clear_threads();+    }++    /// An unsplittable group over budget errors, naming the tile, rather than being+    /// loaded and killed by the OOM reaper. Capping candidates per tile instead would+    /// change which features survive, which is an output change.+    #[test]+    fn an_unsplittable_over_budget_tile_group_is_named_in_the_error() {+        let scratch = Scratch::new("unsplittable");+        let long: Vec<(f64, f64)> = (0..4000)+            .map(|i| (-122.42 + (i % 97) as f64 * 0.0001, 37.77 + (i % 89) as f64 * 0.0001))+            .collect();+        let features = vec![line(&long, vec![("name", Value::String("wiggly".into()))])];+        let opts = Options::new("l", 14, 14);+        let limits = StreamLimits {+            buckets: 4,+            bucket_budget_bytes: 64,+            max_repartition_depth: DEFAULT_MAX_REPARTITION_DEPTH,+        };+        let mut src = SliceSource::new(&features);+        let e = build_archive_to(+            scratch.0.join("out.pmtiles"),+            &scratch.0,+            &opts,+            &mut src,+            &limits,+        )+        .expect_err("an unsplittable over-budget group must error");+        let msg = e.to_string();+        assert!(msg.contains("z14/"), "the error must name the tile: {msg}");+        assert!(msg.contains("spill record(s)"), "and the record count: {msg}");+        assert!(+            msg.contains("--bucket-budget-bytes"),+            "and what to do about it: {msg}"+        );+    }++    /// An empty input is what catches the `Builder`/`StreamBuilder` default-bounds+    /// divergence: nothing overwrites the latitude fields, and they differ by three+    /// units between the two writers.+    #[test]+    fn an_empty_input_streams_to_an_empty_but_valid_archive() {+        let opts = Options::new("l", 10, 12);+        let bytes = assert_identical("empty", &[], &opts, &StreamLimits::default());+        let a = Archive::parse(&bytes).unwrap();+        assert_eq!(a.header.addressed_tiles, 0);+        assert_eq!(a.header.min_lat_e7, -850_511_290, "Builder's default, not StreamBuilder's");+        assert_eq!(a.header.max_lat_e7, 850_511_290);+    }++    #[test]+    fn two_streaming_runs_are_byte_identical() {+        let features = mixed_fixture();+        let opts = Options::new("l", 10, 12);+        let a = assert_identical("det_a", &features, &opts, &StreamLimits::default());+        let b = assert_identical("det_b", &features, &opts, &StreamLimits::default());+        assert_eq!(a, b, "determinism is a regression surface here");+    }++    #[test]+    fn the_streaming_producer_refuses_the_same_bad_options() {+        let scratch = Scratch::new("badopts");+        let features = vec![line(&[(0.0, 0.0), (1.0, 1.0)], vec![])];+        let limits = StreamLimits::default();+        for opts in [+            Options::new("l", 12, 10),+            Options { extent: 0, ..Options::new("l", 10, 12) },+        ] {+            let mut src = SliceSource::new(&features);+            assert!(+                build_archive_to(+                    scratch.0.join("out.pmtiles"),+                    &scratch.0,+                    &opts,+                    &mut src,+                    &limits+                )+                .is_err(),+                "bad options must be refused by both producers"+            );+        }+    }++    /// `--buckets 1` cannot narrow a range, so an over-budget bucket must fail fast+    /// rather than copy itself to disk once per level up to the depth cap.+    #[test]+    fn a_single_bucket_partition_fails_fast_instead_of_recursing() {+        let scratch = Scratch::new("onebucket");+        let features = mixed_fixture();+        let opts = Options::new("l", 10, 10);+        let limits = StreamLimits {+            buckets: 1,+            bucket_budget_bytes: 1,+            max_repartition_depth: DEFAULT_MAX_REPARTITION_DEPTH,+        };+        let mut src = SliceSource::new(&features);+        let e = build_archive_to(+            scratch.0.join("out.pmtiles"),+            &scratch.0,+            &opts,+            &mut src,+            &limits,+        )+        .expect_err("a one-bucket partition cannot split, so it must error");+        assert!(+            e.to_string().contains("cannot be split further"),+            "the error must say why: {e}"+        );+    }++    /// `zoom_base(max_zoom + 1)` overflows above z30, which only the streaming path+    /// computes. A message beats a panic.+    #[test]+    fn a_zoom_beyond_the_tile_id_range_is_refused() {+        let scratch = Scratch::new("deepzoom");+        let features = vec![line(&[(0.0, 0.0), (1.0, 1.0)], vec![])];+        // Refused before any zoom runs, so this costs nothing: a z30 bucket pass over a+        // one-degree line would touch millions of tiles.+        let opts = Options::new("l", 31, 31);+        let mut src = SliceSource::new(&features);+        let e = build_archive_to(+            scratch.0.join("out.pmtiles"),+            &scratch.0,+            &opts,+            &mut src,+            &StreamLimits::default(),+        )+        .expect_err("z31 must be refused");+        assert!(e.to_string().contains("above 30"), "{e}");+    }++    /// The production source is a file, and it must yield exactly what the slice-backed+    /// one does -- otherwise the byte-identity tests above are testing a path nothing+    /// ships.+    #[test]+    fn the_normalized_source_produces_the_same_archive_as_the_slice_one() {+        let scratch = Scratch::new("normsrc");+        let features = mixed_fixture();+        let opts = Options::new("l", 10, 12);+        let limits = StreamLimits::default();++        let (want, want_report) = build_archive(&features, &opts).unwrap();++        let norm = scratch.0.join("features.bin");+        let mut w = crate::spill::NormalizedWriter::create(&norm).unwrap();+        for f in &features {+            w.push(&f.geometry, &f.props).unwrap();+        }+        let summary = w.finish().unwrap();+        assert_eq!(summary.count, features.len() as u64);++        let out = scratch.0.join("out.pmtiles");+        let mut src = NormalizedSource::open(&norm, summary).unwrap();+        let report = build_archive_to(&out, &scratch.0, &opts, &mut src, &limits).unwrap();+        assert_eq!(report, want_report);+        assert!(+            std::fs::read(&out).unwrap() == want,+            "the file-backed source must produce the same bytes"+        );+    } }
scripts/maps/tile_build/src/spill.rs
diff --git a/scripts/maps/tile_build/src/spill.rs b/scripts/maps/tile_build/src/spill.rsnew file mode 100644index 0000000000..9d8d122438--- /dev/null+++ b/scripts/maps/tile_build/src/spill.rs@@ -0,0 +1,1649 @@+//! On-disk spill for the streaming tiler: a record format, and `tile_id`-range buckets.+//!+//! [`crate::pyramid::build_archive`] holds every feature, a second projected copy of+//! every geometry, and a whole zoom's `tile -> features` map. All three are+//! proportional to the input BYTES, which is why a `roads` layer — every OSM road,+//! z11-16, planet-wide — cannot be built by it: the `maxspeed` layer, which is only the+//! ways carrying a `maxspeed` tag and one zoom shallower, already produces an 8.3 GB+//! archive.+//!+//! This module is the disk that replaces that memory. It follows+//! `osm_ingest::chains`: manual little-endian encode and decode, a zero-filled reserved+//! tail so a field can be added without moving anything, counts cross-checked against+//! file length, and `Drop` cleanup so a run that dies mid-planet cannot strand tens of+//! gigabytes.+//!+//! Two files, for two different jobs:+//!+//! * **The normalized file** ([`NormalizedWriter`]) is the geojsonseq parsed exactly+//!   once into a compact binary. Every zoom then re-reads that instead of re-parsing+//!   JSON, which is the cheaper end of a trade that has to be made six times.+//! * **The bucket

Diff truncated.