Modern Apps git

← Modern-Apps.git

maps: spill classified features to disk instead of holding them

Commit
9ea84d2972a6eacb187fe8113aea8a3e5a48d146
Author
vayun-mathur <[email protected]>
When
2026-08-28 03:24 UTC (3 months ago)
Parents
fbdaba3

Diff

scripts/maps/mamaps_build/src/extract.rs
diff --git a/scripts/maps/mamaps_build/src/extract.rs b/scripts/maps/mamaps_build/src/extract.rsindex f3252ab792..c8da727a0b 100644--- a/scripts/maps/mamaps_build/src/extract.rs+++ b/scripts/maps/mamaps_build/src/extract.rs@@ -16,18 +16,19 @@ //! and peaks near 10 GB on California. A water-and-buildings build needs a few million nodes, so it //! pays tens of megabytes. -use std::collections::HashMap;+use std::collections::{HashMap, HashSet}; use std::path::Path;  use osm_ingest::nodeloc::{resolve_nodes, NodeLocations}; use osm_ingest::osm::{visit_block, Element, MEMBER_WAY}; use osm_ingest::pbf::{self, KIND_RELATIONS, KIND_WAYS};-use osm_ingest::proto::Result;+use osm_ingest::proto::{err, Result}; use osm_ingest::rings::{self, MemberWay, RingStats}; use osm_ingest::select::Select; use tile_build::geom::Geometry;  use crate::schema::{self, Class, Layers};+use crate::store::{Sink, Store};  /// One classified feature, in lon/lat, ready to tile. pub struct Feature {@@ -45,6 +46,8 @@ pub struct Stats {     /// relation's rings would not close.     pub geometry_failed: u64,     pub nodes_needed: u64,+    /// Land polygons read from a prepared coastline product, if one was given.+    pub land_polygons: u64,     pub rings: RingStats, } @@ -66,8 +69,16 @@ struct Relation {     area: bool, } -/// Read `input` and return every feature the schema classifies.-pub fn extract(input: &Path, layers: Layers) -> Result<(Vec<Feature>, Stats)> {+/// Read `input` and spill every feature the schema classifies to `spill_path`.+///+/// Features go to disk rather than into a `Vec`, because holding them was 4.9 GB of a measured+/// 10.03 GB California peak and nothing reads them until the tiler does. See [`crate::store`].+pub fn extract(+    input: &Path,+    layers: Layers,+    coastline: Option<&Path>,+    spill_path: &Path,+) -> Result<(Store, Stats)> {     let blobs = pbf::scan_blobs(input)?;     let select = Select::parse(&schema::filters(layers))?;     let mut stats = Stats::default();@@ -200,19 +211,37 @@ pub fn extract(input: &Path, layers: Layers) -> Result<(Vec<Feature>, Stats)> {     //     // Ways in **id order**, not hash order, because the output has to be reproducible and a     // `HashMap`'s iteration is not. The one place in this pipeline where that is a real risk.-    let mut out = Vec::with_capacity(ways.len() + relations.len());+    let mut sink = Sink::create(spill_path)?;+++    // Which ways a relation still needs. Everything else can have its refs freed the moment its own+    // geometry is built, which is what keeps the refs heap from staying resident for the whole pass+    // -- 1.4 GB of the California peak.+    let mut needed_by_relations: HashSet<i64> = HashSet::new();+    for relation in &relations {+        needed_by_relations.extend(relation.members.iter().map(|(id, _)| *id));+    }+     let mut ids: Vec<i64> = ways.keys().copied().collect();     ids.sort_unstable();     for id in ids {         let way = &ways[&id];         let line = table.line(&way.refs);-        match way_geometry(&line, way.class.area) {+        let (class, area) = (way.class, way.class.area);+        match way_geometry(&line, area) {             Some(geometry) => {-                out.push(Feature { class: way.class, geometry });+                sink.push(&class, &geometry)?;                 stats.features += 1;             }             None => stats.geometry_failed += 1,         }+        // Freed now rather than at the end of the pass. A way no relation refers to is finished with+        // the moment its geometry exists.+        if !needed_by_relations.contains(&id) {+            if let Some(way) = ways.get_mut(&id) {+                way.refs = Vec::new();+            }+        }     }     for relation in &relations {         let refs_of = |id: &i64| ways.get(id).map(|w| &w.refs).or_else(|| members.get(id));@@ -231,7 +260,7 @@ pub fn extract(input: &Path, layers: Layers) -> Result<(Vec<Feature>, Stats)> {                 stats.geometry_failed += 1;                 continue;             }-            out.push(Feature { class: relation.class, geometry: Geometry::Lines(lines) });+            sink.push(&relation.class, &Geometry::Lines(lines))?;             stats.features += 1;             continue;         }@@ -247,10 +276,29 @@ pub fn extract(input: &Path, layers: Layers) -> Result<(Vec<Feature>, Stats)> {             stats.geometry_failed += 1;             continue;         }-        out.push(Feature { class: relation.class, geometry: Geometry::Polygons(polygons) });+        sink.push(&relation.class, &Geometry::Polygons(polygons))?;         stats.features += 1;     }-    Ok((out, stats))+    // The mainland, last, because clipping it needs the extract's own bounding box and that is+    // only known once every OSM feature has been through the sink. Order in the file does not+    // matter: the tiler groups by layer id, so `earth` is the first layer of every body whenever it+    // was written.+    if let Some(path) = coastline {+        match sink.bbox_degrees() {+            Some(bbox) => {+                println!(+                    "reading land polygons within {:.3},{:.3} .. {:.3},{:.3}",+                    bbox.0, bbox.1, bbox.2, bbox.3,+                );+                stats.land_polygons = schema::earth::stream_prepared(path, bbox, &mut sink)?;+                stats.features += stats.land_polygons;+            }+            // Nothing to clip against. Land alone would be an archive of one layer, and the caller+            // almost certainly pointed at the wrong extract.+            None => return err("the extract produced no features to place land against".to_string()),+        }+    }+    Ok((sink.finish(spill_path)?, stats)) }  /// A node's location in lon/lat, which is the order [`rings::assemble`] and GeoJSON both want.
scripts/maps/mamaps_build/src/main.rs
diff --git a/scripts/maps/mamaps_build/src/main.rs b/scripts/maps/mamaps_build/src/main.rsindex e2abcd66d7..4a684da272 100644--- a/scripts/maps/mamaps_build/src/main.rs+++ b/scripts/maps/mamaps_build/src/main.rs@@ -24,7 +24,9 @@ use std::process::ExitCode;  mod extract; mod rings;+mod shapefile; mod schema;+mod store; mod tiler;  fn main() -> ExitCode {@@ -147,8 +149,19 @@ fn run(     let report = run.report.as_deref();     let started = std::time::Instant::now();     println!("reading {}", input.display());-    let (features, stats) =-        extract::extract(input, layers).map_err(|e| format!("{}: {e}", input.display()))?;+    // Features are spilled here rather than held: it was 4.9 GB of a measured 10.03 GB California+    // peak, and nothing reads them until the tiler does.+    let spill = out.with_extension("features.tmp");+    if run.coastline.is_some() && !layers.earth {+        return Err("--coastline was given but the earth layer is not selected".to_string());+    }+    if run.coastline.is_none() && layers.earth {+        // Said out loud, because a map with no mainland is a striking thing to discover later. It is+        // not an error: an island is real data and the renderer's backdrop is the water colour.+        println!("no --coastline given, so `earth` carries islands only and there is no mainland");+    }+    let (store, stats) = extract::extract(input, layers, run.coastline.as_deref(), &spill)+        .map_err(|e| format!("{}: {e}", input.display()))?;     println!(         "classified {} way(s) and {} relation(s) -> {} feature(s), {} node(s) resolved",         stats.ways_classified, stats.relations_classified, stats.features, stats.nodes_needed,@@ -159,35 +172,23 @@ fn run(         println!("  {} classified element(s) produced no geometry", stats.geometry_failed);     } +    if stats.land_polygons > 0 {+        println!("  including {} prepared land polygon(s)", stats.land_polygons);+    }+     // The build id identifies the *data*: change the input, the zoom range, the layer set or the     // simplification and every reader has to drop its cache. Derived rather than asked for, so a     // forgotten `--build-id` cannot silently republish under the old one.-    // The mainland, if a prepared polygon was given. `earth`'s islands come from the PBF like-    // everything else; only the continents need it.-    let mut features = features;-    if let Some(path) = &run.coastline {-        if !layers.earth {-            return Err("--coastline was given but the earth layer is not selected".to_string());-        }-        let land = schema::earth::read_prepared(path).map_err(|e| e.to_string())?;-        println!("read {} land polygon(s) from {}", land.len(), path.display());-        features.extend(land);-    } else if layers.earth {-        // Said out loud, because a map with no mainland is a striking thing to discover later. It is-        // not an error: an island is real data and the renderer's backdrop is the water colour.-        println!(-            "no --coastline given, so `earth` carries islands only and there is no mainland"-        );-    }-     let build_id = run.build_id.unwrap_or_else(|| {         derive_build_id(input, layers, min_zoom, max_zoom, simplification, stats.features)     });      let settings = tiler::Settings { min_zoom, max_zoom, simplification, build_id };-    let (bytes, per_zoom) = tiler::build(&features, &settings).map_err(|e| e.to_string())?;+    let (bytes, per_zoom) = tiler::build(&store, &settings).map_err(|e| e.to_string())?;     tiler::check_not_empty(&per_zoom).map_err(|e| e.to_string())?;     std::fs::write(out, &bytes).map_err(|e| format!("cannot write {}: {e}", out.display()))?;+    // The spill is scratch. Removed on success; left behind on failure, where it is evidence.+    let _ = std::fs::remove_file(&spill);      println!("\n{:<6}{:>10}{:>12}{:>12}{:>10}{:>12}", "zoom", "tiles", "features", "points", "dropped", "bytes");     for z in &per_zoom {
scripts/maps/mamaps_build/src/rings.rs
diff --git a/scripts/maps/mamaps_build/src/rings.rs b/scripts/maps/mamaps_build/src/rings.rsindex af4b251bfd..2ae1e9343b 100644--- a/scripts/maps/mamaps_build/src/rings.rs+++ b/scripts/maps/mamaps_build/src/rings.rs@@ -513,7 +513,8 @@ mod tests {             simplification: crate::tiler::DEFAULT_SIMPLIFICATION,             build_id: 1,         };-        let (bytes, stats) = crate::tiler::build(&features, &settings).expect("build");+        let store = crate::store::Store::of(&features).expect("spill");+        let (bytes, stats) = crate::tiler::build(&store, &settings).expect("build");          // The archive claims validity, so every tile in it had better be valid.         let header = tilecodec::mamaps::Header::parse(&bytes).expect("header");
scripts/maps/mamaps_build/src/schema/earth.rs
diff --git a/scripts/maps/mamaps_build/src/schema/earth.rs b/scripts/maps/mamaps_build/src/schema/earth.rsindex b45882c018..f192cf17c4 100644--- a/scripts/maps/mamaps_build/src/schema/earth.rs+++ b/scripts/maps/mamaps_build/src/schema/earth.rs@@ -54,46 +54,94 @@ pub fn classify(tags: &(impl TagSource + ?Sized)) -> Option<Class> {     None } -/// Read a prepared land polygon into `earth` features.+/// Stream a prepared land polygon into the feature sink, clipped to `bbox`. ///-/// One GeoJSON feature per line, as `tile_build`'s own reader expects, and every polygon becomes one-/// `earth` feature with no kind — which is what the style's unfiltered `earth` layer draws.-pub fn read_prepared(path: &Path) -> Result<Vec<crate::extract::Feature>> {-    let text = std::fs::read_to_string(path).map_err(|e| {-        osm_ingest::proto::Error(format!("cannot read {}: {e}", path.display()))-    })?;-    let mut out = Vec::new();-    for (line_number, line) in text.lines().enumerate() {-        if line.trim().is_empty() {-            continue;+/// Streamed rather than returned, because the planet product is 1.26 GB of geometry and collecting it+/// would undo the change this signature exists to serve.+///+/// `bbox` is `(min_lon, min_lat, max_lon, max_lat)` in degrees, and is **required**: the land polygon+/// product covers the whole planet, so a regional build that did not clip would tile every coastline+/// on Earth. That is not a slow build, it is a wrong one — the archive's bounding box would be the+/// globe and its tile count would be planetary.+///+/// Two formats, told apart by extension: an ESRI `.shp`, which is what the OSMCoastline product ships+/// as, and GeoJSON-seq, which is what a hand-made test fixture is easiest to write.+pub fn stream_prepared(+    path: &Path,+    bbox: (f64, f64, f64, f64),+    sink: &mut crate::store::Sink,+) -> Result<u64> {+    let class = Class::area(LAYER_EARTH, tilecodec::mamaps::dict::NONE, 0);+    let is_shapefile = path+        .extension()+        .and_then(|e| e.to_str())+        .is_some_and(|e| e.eq_ignore_ascii_case("shp"));++    let mut written = 0u64;+    if is_shapefile {+        let mut reader = crate::shapefile::ShapeReader::open(path)?;+        reader.clip_to(bbox);+        while let Some(rings) = reader.next()? {+            // One mamaps feature per polygon, not per record: a record can hold several islands, and+            // the tessellator wants one exterior with its own holes.+            for polygon in crate::shapefile::group(rings) {+                sink.push(&class, &Geometry::Polygons(vec![polygon]))?;+                written += 1;+            }         }-        let Some(feature) = tile_build::geojson::parse_feature(line) else {-            return err(format!(-                "{}:{}: not a GeoJSON feature",-                path.display(),-                line_number + 1,-            ));-        };-        // Polygons only. A prepared land product has nothing else in it, and a line in there would-        // be a sign the wrong file was handed over.-        let polygons = match feature.geometry {-            Geometry::Polygons(polygons) => polygons,-            _ => continue,-        };-        if polygons.is_empty() {-            continue;+        println!(+            "  {} land polygon(s) kept, {} outside the extract",+            written, reader.skipped,+        );+    } else {+        let text = std::fs::read_to_string(path).map_err(|e| {+            osm_ingest::proto::Error(format!("cannot read {}: {e}", path.display()))+        })?;+        for (line_number, line) in text.lines().enumerate() {+            if line.trim().is_empty() {+                continue;+            }+            let Some(feature) = tile_build::geojson::parse_feature(line) else {+                return err(format!(+                    "{}:{}: not a GeoJSON feature",+                    path.display(),+                    line_number + 1,+                ));+            };+            // Polygons only. A prepared land product has nothing else in it, and a line in there+            // would be a sign the wrong file was handed over.+            let Geometry::Polygons(polygons) = feature.geometry else { continue };+            for polygon in polygons {+                if polygon.is_empty() || !meets(&polygon, bbox) {+                    continue;+                }+                sink.push(&class, &Geometry::Polygons(vec![polygon]))?;+                written += 1;+            }         }-        out.push(crate::extract::Feature {-            // No kind: the mainland is what `earth`'s unfiltered layer draws, and giving it one-            // would put it behind a whitelist it is not in.-            class: Class::area(LAYER_EARTH, tilecodec::mamaps::dict::NONE, 0),-            geometry: Geometry::Polygons(polygons),-        });     }-    if out.is_empty() {-        return err(format!("{} holds no land polygons", path.display()));+    if written == 0 {+        return err(format!(+            "{} holds no land polygon meeting {bbox:?}; is it the right area?",+            path.display(),+        ));     }-    Ok(out)+    Ok(written)+}++/// Does a polygon's exterior meet `bbox`? Intersection, not containment: a polygon straddling the+/// extract's edge is land inside it.+fn meets(polygon: &[Vec<(f64, f64)>], bbox: (f64, f64, f64, f64)) -> bool {+    let Some(exterior) = polygon.first() else { return false };+    let (mut min_x, mut min_y) = (f64::MAX, f64::MAX);+    let (mut max_x, mut max_y) = (f64::MIN, f64::MIN);+    for &(x, y) in exterior {+        min_x = min_x.min(x);+        min_y = min_y.min(y);+        max_x = max_x.max(x);+        max_y = max_y.max(y);+    }+    !(max_x < bbox.0 || min_x > bbox.2 || max_y < bbox.1 || min_y > bbox.3) }  #[cfg(test)]@@ -140,23 +188,29 @@ mod tests {         assert!(classify_tags(&[("natural", "coastline")]).is_none());     } +    /// A land file that yields nothing is an error, not an empty layer. Silently shipping an+    /// oceanless world because a path was wrong is the failure this catches.     #[test]     fn a_missing_or_empty_prepared_polygon_is_an_error_rather_than_an_empty_layer() {+        let scratch = std::env::temp_dir().join("mamaps_land_sink.features");+        let mut sink = crate::store::Sink::create(&scratch).expect("sink");+         let missing = std::path::Path::new("no_such_land_polygons.geojsonseq");-        assert!(read_prepared(missing).is_err());+        assert!(stream_prepared(missing, (-180.0, -90.0, 180.0, 90.0), &mut sink).is_err());          let empty = std::env::temp_dir().join("mamaps_empty_land.geojsonseq");         std::fs::write(&empty, "\n\n").expect("write");-        let failure = match read_prepared(&empty) {+        let failure = match stream_prepared(&empty, (-180.0, -90.0, 180.0, 90.0), &mut sink) {             Ok(_) => panic!("an empty land file should be refused"),             Err(e) => e,         };-        assert!(failure.0.contains("no land polygons"), "{}", failure.0);+        assert!(failure.0.contains("no land polygon"), "{}", failure.0);         let _ = std::fs::remove_file(&empty);+        let _ = std::fs::remove_file(&scratch);     }      #[test]-    fn a_prepared_polygon_reads_as_an_unfiltered_earth_feature() {+    fn a_prepared_polygon_streams_in_as_an_unfiltered_earth_feature() {         let path = std::env::temp_dir().join("mamaps_land.geojsonseq");         std::fs::write(             &path,@@ -165,12 +219,62 @@ mod tests {              [-120.0,35.0]]]}}\n",         )         .expect("write");-        let features = read_prepared(&path).expect("read");-        assert_eq!(features.len(), 1);-        assert_eq!(features[0].class.layer, dict::LAYER_EARTH);+        let scratch = std::env::temp_dir().join("mamaps_land_out.features");+        let mut sink = crate::store::Sink::create(&scratch).expect("sink");+        assert_eq!(stream_prepared(&path, (-180.0, -90.0, 180.0, 90.0), &mut sink).expect("read"), 1);+        let store = sink.finish(&scratch).expect("finish");++        let feature = store+            .reader()+            .expect("reader")+            .next()+            .expect("read")+            .expect("a feature");+        assert_eq!(feature.class.layer, dict::LAYER_EARTH);         // No kind, so the style's unfiltered `earth` layer draws it.-        assert_eq!(features[0].class.kind, dict::NONE);-        assert_eq!(features[0].class.min_zoom, 0, "the mainland carries a world tile");+        assert_eq!(feature.class.kind, dict::NONE);+        assert_eq!(feature.class.min_zoom, 0, "the mainland carries a world tile");+        let _ = std::fs::remove_file(&path);+        let _ = std::fs::remove_file(&scratch);+    }+    /// **The bug this clip exists for.** The land polygon product covers the whole planet, so a+    /// California build that did not clip would tile every coastline on Earth: it ran for 37 minutes+    /// before being killed, and the archive it was building had a global bounding box.+    #[test]+    fn a_land_polygon_outside_the_build_area_is_not_carried() {+        let path = std::env::temp_dir().join("mamaps_land_clip.geojsonseq");+        // One polygon off California, one off Portugal.+        std::fs::write(+            &path,+            "{\"type\":\"Feature\",\"properties\":{},\"geometry\":{\"type\":\"Polygon\",\+             \"coordinates\":[[[-120.0,35.0],[-119.0,35.0],[-119.0,36.0],[-120.0,36.0],\+             [-120.0,35.0]]]}}\n\+             {\"type\":\"Feature\",\"properties\":{},\"geometry\":{\"type\":\"Polygon\",\+             \"coordinates\":[[[-9.0,38.0],[-8.0,38.0],[-8.0,39.0],[-9.0,39.0],[-9.0,38.0]]]}}\n",+        )+        .expect("write");++        let scratch = std::env::temp_dir().join("mamaps_land_clip.features");+        let mut sink = crate::store::Sink::create(&scratch).expect("sink");+        let california = (-125.0, 32.0, -114.0, 42.0);+        assert_eq!(+            stream_prepared(&path, california, &mut sink).expect("read"),+            1,+            "only the polygon meeting the build area is carried",+        );++        // Straddling the edge counts as inside: that is land in the extract, cut off at the border.+        let mut sink = crate::store::Sink::create(&scratch).expect("sink");+        let straddling = (-119.5, 35.5, -100.0, 45.0);+        assert_eq!(stream_prepared(&path, straddling, &mut sink).expect("read"), 1);++        // And an area with no land in it is an error rather than an empty layer, because it almost+        // certainly means the wrong file or the wrong extract.+        let mut sink = crate::store::Sink::create(&scratch).expect("sink");+        let pacific = (-160.0, 0.0, -150.0, 10.0);+        assert!(stream_prepared(&path, pacific, &mut sink).is_err());+         let _ = std::fs::remove_file(&path);+        let _ = std::fs::remove_file(&scratch);     } }
scripts/maps/mamaps_build/src/shapefile.rs
diff --git a/scripts/maps/mamaps_build/src/shapefile.rs b/scripts/maps/mamaps_build/src/shapefile.rsnew file mode 100644index 0000000000..10fc3cc7d7--- /dev/null+++ b/scripts/maps/mamaps_build/src/shapefile.rs@@ -0,0 +1,396 @@+//! A streaming reader for the one shapefile this project reads.+//!+//! # Why write this rather than shell out+//!+//! The OSMCoastline land polygons ship as an ESRI shapefile, and converting one normally means GDAL.+//! This repository has spent its whole life removing that class of dependency — osmium, tippecanoe+//! and Planetiler are all gone — and a polygon shapefile is a genuinely simple binary format: a+//! 100-byte header, then length-prefixed records of `f64` pairs. Reading it directly is about a+//! hundred lines, needs no toolchain, and streams, which matters when the file is 1.26 GB and the+//! whole point of the change it serves is to stop holding geometry in memory.+//!+//! Only what is needed is implemented: shape type 5, `Polygon`. A `PolygonZ` or a `PolyLine` in this+//! file would mean the wrong artefact was handed over, so those are refused rather than coerced.+//!+//! # Ring orientation is the opposite of GeoJSON's+//!+//! The ESRI specification orders an outer ring **clockwise** and a hole counter-clockwise — the+//! reverse of GeoJSON and of this pipeline. That does not matter for winding, because stage C+//! normalises it. It matters for **grouping**: a record holds a flat list of rings, and knowing which+//! are exteriors is the only way to tell one island with a lake from two separate islands.++use std::fs::File;+use std::io::{BufReader, Read};+use std::path::Path;++use osm_ingest::proto::{err, Error, Result};++/// `.shp` files start with this, big-endian.+const FILE_CODE: u32 = 9994;+const HEADER_BYTES: usize = 100;+const SHAPE_NULL: u32 = 0;+const SHAPE_POLYGON: u32 = 5;++/// A ring count no real land polygon comes close to, as a guard against a corrupt length driving a+/// huge allocation.+const MAX_PARTS: u32 = 1 << 20;+/// Likewise for points. The largest single land polygon in the *unsplit* product is a few million.+const MAX_POINTS: u32 = 1 << 26;++/// Streams `Polygon` records out of a `.shp`.+pub struct ShapeReader {+    input: BufReader<File>,+    /// Bytes of records left to read, from the header's file length.+    remaining: u64,+    buf: Vec<u8>,+    /// Only records whose own bounding box meets this one are parsed.+    ///+    /// **Not an optimisation — a correctness requirement.** The land polygon product covers the whole+    /// planet: 825 k polygons, of which a California build wants a few hundred. Without this, a+    /// regional build tiles every coastline on Earth, which takes hours and produces an archive whose+    /// bounding box is the globe.+    filter: Option<(f64, f64, f64, f64)>,+    /// How many records were skipped by the filter, for the build report.+    pub skipped: u64,+}++impl ShapeReader {+    pub fn open(path: &Path) -> Result<ShapeReader> {+        let file = File::open(path)+            .map_err(|e| Error(format!("cannot open {}: {e}", path.display())))?;+        let mut input = BufReader::with_capacity(1 << 20, file);+        let mut header = [0u8; HEADER_BYTES];+        input+            .read_exact(&mut header)+            .map_err(|e| Error(format!("{} is too short to be a shapefile: {e}", path.display())))?;++        if be32(&header[0..4]) != FILE_CODE {+            return err(format!("{} is not a shapefile", path.display()));+        }+        // The header states the file length in 16-bit words, including the header itself.+        let words = be32(&header[24..28]) as u64;+        let total = words * 2;+        if total < HEADER_BYTES as u64 {+            return err(format!("{} declares an impossible length", path.display()));+        }+        let shape_type = le32(&header[32..36]);+        if shape_type != SHAPE_POLYGON {+            return err(format!(+                "{} holds shape type {shape_type}, and only 5 (Polygon) is read; this is not the \+                 land polygon product",+                path.display(),+            ));+        }+        Ok(ShapeReader {+            input,+            remaining: total - HEADER_BYTES as u64,+            buf: Vec::new(),+            filter: None,+            skipped: 0,+        })+    }++    /// Keep only records meeting `(min_lon, min_lat, max_lon, max_lat)`, in degrees.+    pub fn clip_to(&mut self, bbox: (f64, f64, f64, f64)) {+        self.filter = Some(bbox);+    }++    /// The next record's rings, or `None` at the end of the file.+    ///+    /// Rings come back as `(ring, is_exterior)` in file order, so the caller can group them without+    /// re-deriving orientation.+    pub fn next(&mut self) -> Result<Option<Vec<(Vec<(f64, f64)>, bool)>>> {+        // A record header is 8 bytes; anything less than that left is the end.+        if self.remaining < 8 {+            return Ok(None);+        }+        let mut record_header = [0u8; 8];+        self.input+            .read_exact(&mut record_header)+            .map_err(|e| Error(format!("reading a record header: {e}")))?;+        // Content length is in 16-bit words, as everywhere else in this format.+        let content_len = be32(&record_header[4..8]) as u64 * 2;+        self.remaining -= 8;+        if content_len > self.remaining {+            return err("a record claims more content than the file has left".to_string());+        }+        self.remaining -= content_len;++        self.buf.clear();+        self.buf.resize(content_len as usize, 0);+        self.input+            .read_exact(&mut self.buf)+            .map_err(|e| Error(format!("reading a record body: {e}")))?;++        // Every Polygon record carries its own bounding box at bytes 4..36, so a record outside the+        // build's area is rejected for the cost of four `f64` comparisons rather than by decoding+        // however many thousand points it holds.+        if let Some(want) = self.filter {+            if self.buf.len() >= 36 && le32(&self.buf[0..4]) == SHAPE_POLYGON {+                let (min_x, min_y) = (le64(&self.buf[4..12]), le64(&self.buf[12..20]));+                let (max_x, max_y) = (le64(&self.buf[20..28]), le64(&self.buf[28..36]));+                // Intersection, not containment: a polygon straddling the extract's edge is land+                // inside it and has to be kept.+                let misses = max_x < want.0 || min_x > want.2 || max_y < want.1 || min_y > want.3;+                if misses {+                    self.skipped += 1;+                    return Ok(Some(Vec::new()));+                }+            }+        }+        parse_polygon(&self.buf)+    }+}++/// One record's rings.+fn parse_polygon(body: &[u8]) -> Result<Option<Vec<(Vec<(f64, f64)>, bool)>>> {+    if body.len() < 4 {+        return err("a record is too short to name its shape type".to_string());+    }+    match le32(&body[0..4]) {+        // A null shape is legal and means "no geometry here". Skipped, not an error.+        SHAPE_NULL => return Ok(Some(Vec::new())),+        SHAPE_POLYGON => {}+        other => return err(format!("record shape type {other} is not a Polygon")),+    }+    // 4..36 is the record's own bounding box, which is redundant with the points.+    if body.len() < 44 {+        return err("a Polygon record is too short to hold its counts".to_string());+    }+    let part_count = le32(&body[36..40]);+    let point_count = le32(&body[40..44]);+    if part_count > MAX_PARTS || point_count > MAX_POINTS {+        return err(format!("a record claims {part_count} part(s) and {point_count} point(s)"));+    }+    let parts_at = 44usize;+    let points_at = parts_at + part_count as usize * 4;+    let needed = points_at + point_count as usize * 16;+    if body.len() < needed {+        return err(format!("a Polygon record is {} bytes short", needed - body.len()));+    }++    // Each part is the index of its first point; the last runs to the end.+    let mut starts: Vec<usize> = Vec::with_capacity(part_count as usize);+    for i in 0..part_count as usize {+        starts.push(le32(&body[parts_at + i * 4..parts_at + i * 4 + 4]) as usize);+    }+    let point = |i: usize| -> (f64, f64) {+        let at = points_at + i * 16;+        (le64(&body[at..at + 8]), le64(&body[at + 8..at + 16]))+    };++    let mut rings = Vec::with_capacity(starts.len());+    for (i, &start) in starts.iter().enumerate() {+        let end = starts.get(i + 1).copied().unwrap_or(point_count as usize);+        if start >= end || end > point_count as usize {+            return err("a part's range is not inside the record's points".to_string());+        }+        let ring: Vec<(f64, f64)> = (start..end).map(point).collect();+        // Clockwise is an exterior in this format, which is a negative shoelace area with y up.+        let exterior = signed_area(&ring) < 0.0;+        rings.push((ring, exterior));+    }+    Ok(Some(rings))+}++/// A ring's signed area in degrees squared. Only its sign is used.+fn signed_area(ring: &[(f64, f64)]) -> f64 {+    let mut twice = 0.0;+    for pair in ring.windows(2) {+        twice += pair[0].0 * pair[1].1 - pair[1].0 * pair[0].1;+    }+    if let (Some(first), Some(last)) = (ring.first(), ring.last()) {+        if first != last {+            twice += last.0 * first.1 - first.0 * last.1;+        }+    }+    twice / 2.0+}++/// Group a record's rings into polygons: each exterior starts one, and the holes that follow are+/// its.+///+/// A file whose first ring is a hole is malformed; those holes have nothing to belong to and are+/// dropped rather than promoted, because promoting one would paint a lake as land.+pub fn group(rings: Vec<(Vec<(f64, f64)>, bool)>) -> Vec<Vec<Vec<(f64, f64)>>> {+    let mut out: Vec<Vec<Vec<(f64, f64)>>> = Vec::new();+    for (ring, exterior) in rings {+        // Three distinct points plus a closing one; less bounds no area.+        if ring.len() < 4 {+            continue;+        }+        if exterior || out.is_empty() {+            out.push(vec![ring]);+        } else {+            out.last_mut().expect("non-empty").push(ring);+        }+    }+    out+}++fn be32(bytes: &[u8]) -> u32 {+    u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])+}++fn le32(bytes: &[u8]) -> u32 {+    u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])+}++fn le64(bytes: &[u8]) -> f64 {+    f64::from_le_bytes([+        bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],+    ])+}++#[cfg(test)]+mod tests {+    use super::*;++    /// Build a one-record shapefile in memory, so the reader is tested against bytes rather than+    /// against a 1.26 GB download.+    fn shapefile(rings: &[Vec<(f64, f64)>]) -> Vec<u8> {+        let point_count: usize = rings.iter().map(|r| r.len()).sum();+        let mut content = Vec::new();+        content.extend_from_slice(&SHAPE_POLYGON.to_le_bytes());+        for _ in 0..4 {+            content.extend_from_slice(&0f64.to_le_bytes());+        }+        content.extend_from_slice(&(rings.len() as u32).to_le_bytes());+        content.extend_from_slice(&(point_count as u32).to_le_bytes());+        let mut at = 0u32;+        for ring in rings {+            content.extend_from_slice(&at.to_le_bytes());+            at += ring.len() as u32;+        }+        for ring in rings {+            for &(x, y) in ring {+                content.extend_from_slice(&x.to_le_bytes());+                content.extend_from_slice(&y.to_le_bytes());+            }+        }++        let mut out = vec![0u8; HEADER_BYTES];+        out[0..4].copy_from_slice(&FILE_CODE.to_be_bytes());+        out[32..36].copy_from_slice(&SHAPE_POLYGON.to_le_bytes());+        out.extend_from_slice(&1u32.to_be_bytes());+        out.extend_from_slice(&((content.len() / 2) as u32).to_be_bytes());+        out.extend_from_slice(&content);+        let words = (out.len() / 2) as u32;+        out[24..28].copy_from_slice(&words.to_be_bytes());+        out+    }++    fn write_temp(name: &str, bytes: &[u8]) -> std::path::PathBuf {+        let path = std::env::temp_dir()+            .join(format!("mamaps_shp_{}_{name}.shp", std::process::id()));+        std::fs::write(&path, bytes).expect("write");+        path+    }++    /// Clockwise in a y-up system, which the ESRI spec calls an exterior.+    fn clockwise() -> Vec<(f64, f64)> {+        vec![(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0), (0.0, 0.0)]+    }++    fn counter_clockwise() -> Vec<(f64, f64)> {+        let mut ring = clockwise();+        ring.reverse();+        ring+    }++    #[test]+    fn a_single_polygon_reads_back_with_its_points() {+        let path = write_temp("single", &shapefile(&[clockwise()]));+        let mut reader = ShapeReader::open(&path).expect("open");+        let rings = reader.next().expect("read").expect("a record");+        assert_eq!(rings.len(), 1);+        assert!(rings[0].1, "a clockwise ring is an exterior in this format");+        assert_eq!(rings[0].0, clockwise());+        assert!(reader.next().expect("read").is_none(), "and then the end");+        let _ = std::fs::remove_file(&path);+    }++    /// **The reason orientation is read at all.** One island with a lake and two separate islands+    /// have the same ring count and the same points; only the winding tells them apart.+    #[test]+    fn orientation_groups_rings_into_the_right_polygons() {+        // Exterior, hole, exterior -> two polygons, the first with a hole.+        let rings = vec![clockwise(), counter_clockwise(), clockwise()];+        let path = write_temp("grouped", &shapefile(&rings));+        let mut reader = ShapeReader::open(&path).expect("open");+        let polygons = group(reader.next().expect("read").expect("a record"));+        assert_eq!(polygons.len(), 2, "two islands");+        assert_eq!(polygons[0].len(), 2, "the first has a lake");+        assert_eq!(polygons[1].len(), 1, "the second does not");+        let _ = std::fs::remove_file(&path);++        // Two exteriors and no holes -> two separate polygons, not one with a hole.+        let path = write_temp("two", &shapefile(&[clockwise(), clockwise()]));+        let mut reader = ShapeReader::open(&path).expect("open");+        let polygons = group(reader.next().expect("read").expect("a record"));+        assert_eq!(polygons.len(), 2);+        assert!(polygons.iter().all(|p| p.len() == 1));+        let _ = std::fs::remove_file(&path);+    }++    #[test]+    fn a_degenerate_ring_is_dropped_and_a_leading_hole_does_not_become_land() {+        // A two-point ring bounds nothing.+        let rings = vec![(vec![(0.0, 0.0), (1.0, 1.0)], true)];+        assert!(group(rings).is_empty(), "a degenerate ring");++        // A record whose first ring is a hole is malformed. It must not be promoted to land, which+        // would paint a lake solid.+        let rings = vec![(counter_clockwise(), false), (clockwise(), true)];+        let polygons = group(rings);+        assert_eq!(polygons.len(), 2, "the stray hole stands alone rather than swallowing the land");+    }++    #[test]+    fn the_wrong_file_is_refused_rather_than_misread() {+        // Not a shapefile at all.+        let path = write_temp("garbage", b"this is not a shapefile, it is a sentence");+        assert!(ShapeReader::open(&path).is_err());+        let _ = std::fs::remove_file(&path);++        // A shapefile of the wrong shape type, which means the wrong artefact was downloaded.+        let mut bytes = shapefile(&[clockwise()]);+        bytes[32..36].copy_from_slice(&3u32.to_le_bytes()); // PolyLine+        let path = write_temp("polyline", &bytes);+        let failure = match ShapeReader::open(&path) {+            Ok(_) => panic!("a PolyLine shapefile should be refused"),+            Err(e) => e,+        };+        assert!(failure.0.contains("land polygon product"), "{}", failure.0);+        let _ = std::fs::remove_file(&path);+    }++    #[test]+    fn a_truncated_record_is_an_error_rather_than_a_silent_stop() {+        let mut bytes = shapefile(&[clockwise()]);+        bytes.truncate(bytes.len() - 40);+        let path = write_temp("truncated", &bytes);+        let mut reader = ShapeReader::open(&path).expect("open");+        assert!(reader.next().is_err(), "a half-read polygon must not look like the end of the file");+        let _ = std::fs::remove_file(&path);+    }++    #[test]+    fn a_null_shape_is_skipped_rather_than_failing_the_build() {+        let mut content = Vec::new();+        content.extend_from_slice(&SHAPE_NULL.to_le_bytes());+        let mut bytes = vec![0u8; HEADER_BYTES];+        bytes[0..4].copy_from_slice(&FILE_CODE.to_be_bytes());+        bytes[32..36].copy_from_slice(&SHAPE_POLYGON.to_le_bytes());+        bytes.extend_from_slice(&1u32.to_be_bytes());+        bytes.extend_from_slice(&((content.len() / 2) as u32).to_be_bytes());+        bytes.extend_from_slice(&content);+        let words = (bytes.len() / 2) as u32;+        bytes[24..28].copy_from_slice(&words.to_be_bytes());++        let path = write_temp("null", &bytes);+        let mut reader = ShapeReader::open(&path).expect("open");+        assert_eq!(reader.next().expect("read").expect("a record").len(), 0);+        let _ = std::fs::remove_file(&path);+    }+}
scripts/maps/mamaps_build/src/store.rs
diff --git a/scripts/maps/mamaps_build/src/store.rs b/scripts/maps/mamaps_build/src/store.rsnew file mode 100644index 0000000000..44fd05a114--- /dev/null+++ b/scripts/maps/mamaps_build/src/store.rs@@ -0,0 +1,351 @@+//! The feature store: classified features on **disk** rather than in memory.+//!+//! # Why this exists+//!+//! Measured on `california-latest.osm.pbf`, the generator peaked at 10.03 GB, and a `--max-zoom 12`+//! run peaked at 10.01 GB — so essentially none of it was the tiler. It was all stage A, where three+//! large things were alive at once:+//!+//! | | California |+//! |---|---|+//! | materialised features, lon/lat `f64` | ~4.9 GB |+//! | classified ways and their node refs | ~2.7 GB |+//! | node id -> location table | ~2.5 GB |+//!+//! The features were the largest and the only one that did not have to be resident: nothing reads+//! them until the tiler does, and the tiler reads them **once per zoom, in order**. So they go to a+//! file, and the tiler streams it fifteen times instead of holding it fifteen times over.+//!+//! # The format is `tile_build`'s, not a new one+//!+//! [`spill::NormalizedWriter`] already writes exactly this: a length-prefixed record per feature+//! holding a lon/lat geometry and a property list. Reusing it means the encoding is already tested,+//! already round-tripped, and already handles every geometry kind — and it costs one small+//! indirection: the [`Class`] is packed into a single integer property. That is the plan's own+//! suggestion, and it is why `spill.rs` needed no change.++use std::path::{Path, PathBuf};++use osm_ingest::proto::{err, Result};+use tile_build::geom::Geometry;+use tile_build::mvt::Value;+use tile_build::spill::{NormalizedReader, NormalizedWriter};++use crate::extract::Feature;+use crate::schema::Class;++/// The property key the packed [`Class`] travels under.+///+/// One byte, because it is written once per feature and 15.5 M allocations of a longer name is a+/// cost with nothing to show for it.+const CLASS_KEY: &str = "c";++/// A [`Class`] as one integer, so a feature's classification costs one property rather than seven.+///+/// | field | bits | width |+/// |---|---|---|+/// | `layer` | 0..3 | 7 layers |+/// | `kind` | 3..19 | `u16` |+/// | `kind_detail` | 19..35 | `u16` |+/// | `flags` | 35..43 | `u8` |+/// | `area` | 43..44 | one bit |+/// | `min_zoom` | 44..49 | 0..31 |+/// | `min_area_px` | 49..57 | 0..255, integral |+///+/// `min_area_px` is an `f64` in [`Class`] and a byte here. Every value the schema uses is a small+/// whole number of square pixels, and [`pack`] refuses anything else rather than rounding a+/// threshold silently.+fn pack(class: &Class) -> Result<u64> {+    if class.layer > 0b111 {+        return err(format!("layer {} does not fit the packed class", class.layer));+    }+    if class.min_zoom > 0b11111 {+        return err(format!("min_zoom {} does not fit the packed class", class.min_zoom));+    }+    // Refused rather than rounded: a threshold quietly changed is a layer quietly wrong.+    if class.min_area_px < 0.0+        || class.min_area_px > 255.0+        || class.min_area_px.fract() != 0.0+    {+        return err(format!(+            "min_area_px {} is not a whole number of square pixels in 0..=255",+            class.min_area_px,+        ));+    }+    Ok((class.layer as u64)+        | ((class.kind as u64) << 3)+        | ((class.kind_detail as u64) << 19)+        | ((class.flags as u64) << 35)+        | ((class.area as u64) << 43)+        | ((class.min_zoom as u64) << 44)+        | ((class.min_area_px as u64) << 49))+}++fn unpack(bits: u64) -> Class {+    Class {+        layer: (bits & 0b111) as u8,+        kind: ((bits >> 3) & 0xffff) as u16,+        kind_detail: ((bits >> 19) & 0xffff) as u16,+        flags: ((bits >> 35) & 0xff) as u8,+        area: (bits >> 43) & 1 == 1,+        min_zoom: ((bits >> 44) & 0b11111) as u8,+        min_area_px: ((bits >> 49) & 0xff) as f64,+    }+}++/// Accumulates features into a file, tracking the bounding box as it goes.+///+/// The bbox is computed here rather than in a pass of its own, because a pass of its own would be a+/// sixteenth read of a four-gigabyte file to learn four numbers.+pub struct Sink {+    writer: NormalizedWriter,+    props: Vec<(String, Value)>,+    count: u64,+    bbox: Option<(i32, i32, i32, i32)>,+}++impl Sink {+    pub fn create(path: impl AsRef<Path>) -> Result<Sink> {+        Ok(Sink {+            writer: NormalizedWriter::create(path.as_ref().to_path_buf())+                .map_err(|e| osm_ingest::proto::Error(e.to_string()))?,+            props: vec![(CLASS_KEY.to_string(), Value::Uint(0))],+            count: 0,+            bbox: None,+        })+    }++    pub fn push(&mut self, class: &Class, geometry: &Geometry) -> Result<()> {+        self.props[0].1 = Value::Uint(pack(class)?);+        self.writer+            .push(geometry, &self.props)+            .map_err(|e| osm_ingest::proto::Error(e.to_string()))?;+        self.count += 1;+        self.grow(geometry);+        Ok(())+    }++    /// Extend the bounding box by a geometry, in degrees times 1e7.+    fn grow(&mut self, geometry: &Geometry) {+        let mut visit = |&(lon, lat): &(f64, f64)| {+            let (x, y) = ((lon * 1e7) as i32, (lat * 1e7) as i32);+            match &mut self.bbox {+                None => self.bbox = Some((x, y, x, y)),+                Some(b) => {+                    b.0 = b.0.min(x);+                    b.1 = b.1.min(y);+                    b.2 = b.2.max(x);+                    b.3 = b.3.max(y);+                }+            }+        };+        match geometry {+            Geometry::Points(points) => points.iter().for_each(&mut visit),+            Geometry::Lines(lines) => lines.iter().flatten().for_each(&mut visit),+            Geometry::Polygons(polygons) => {+                polygons.iter().flatten().flatten().for_each(&mut visit)+            }+        }+    }++    pub fn finish(self, path: impl Into<PathBuf>) -> Result<Store> {+        let (count, bbox) = (self.count, self.bbox);+        self.writer.finish().map_err(|e| osm_ingest::proto::Error(e.to_string()))?;+        Ok(Store { path: path.into(), count, bbox: bbox.unwrap_or((0, 0, 0, 0)) })+    }++    /// The bounding box of everything pushed so far, in degrees.+    ///+    /// `None` until something has been pushed. Used to clip a planet-wide coastline product down to+    /// the area a build actually covers, which is why it is readable mid-stream.+    pub fn bbox_degrees(&self) -> Option<(f64, f64, f64, f64)> {+        let (min_x, min_y, max_x, max_y) = self.bbox?;+        Some((+            min_x as f64 * 1e-7,+            min_y as f64 * 1e-7,+            max_x as f64 * 1e-7,+            max_y as f64 * 1e-7,+        ))+    }+}++/// Features on disk, re-readable in order as many times as the tiler needs.+pub struct Store {+    path: PathBuf,+    count: u64,+    bbox: (i32, i32, i32, i32),+}++impl Store {+    /// How many features are in the file.+    #[cfg_attr(not(test), allow(dead_code))]+    pub fn len(&self) -> u64 {+        self.count+    }++    /// The bounding box of every feature, in degrees times 1e7, for the archive header.+    pub fn bbox(&self) -> (i32, i32, i32, i32) {+        self.bbox+    }++    /// Read every feature, in the order they were written.+    pub fn reader(&self) -> Result<Reader> {+        Ok(Reader {+            inner: NormalizedReader::open(self.path.clone())+                .map_err(|e| osm_ingest::proto::Error(e.to_string()))?,+        })+    }+}++impl Store {+    /// Spill features from memory into a temporary store.+    ///+    /// For tests only. The generator never has a `Vec<Feature>` to hand -- that is the entire point+    /// of this module -- but a test that had to write a file to state its case would be a worse test.+    #[cfg(test)]+    pub fn of(features: &[Feature]) -> Result<Store> {+        use std::sync::atomic::{AtomicU64, Ordering};+        static NEXT: AtomicU64 = AtomicU64::new(0);+        let path = std::env::temp_dir().join(format!(+            "mamaps_test_{}_{}.features",+            std::process::id(),+            NEXT.fetch_add(1, Ordering::Relaxed),+        ));+        let mut sink = Sink::create(&path)?;+        for feature in features {+            sink.push(&feature.class, &feature.geometry)?;+        }+        sink.finish(&path)+    }+}++pub struct Reader {+    inner: NormalizedReader,+}++impl Reader {+    /// The next feature, or `None` at the end of the file.+    ///+    /// A record whose class property is missing or is not an integer is a corrupt file rather than a+    /// feature to skip: everything in here was written by [`Sink::push`] one run ago, so anything+    /// else means the file is not the one we wrote.+    pub fn next(&mut self) -> Result<Option<Feature>> {+        let Some(record) =+            self.inner.next().map_err(|e| osm_ingest::proto::Error(e.to_string()))?+        else {+            return Ok(None);+        };+        let bits = match record.props.iter().find(|(key, _)| key == CLASS_KEY) {+            Some((_, Value::Uint(bits))) => *bits,+            _ => return err("a spilled feature carries no packed class".to_string()),+        };+        Ok(Some(Feature { class: unpack(bits), geometry: record.geometry }))+    }+}++#[cfg(test)]+mod tests {+    use super::*;+    use crate::schema;+    use tilecodec::mamaps::dict;++    fn temp(name: &str) -> PathBuf {+        std::env::temp_dir().join(format!("mamaps_store_{}_{name}", std::process::id()))+    }++    #[test]+    fn a_class_survives_being_packed_into_one_integer() {+        let class = Class {+            layer: dict::LAYER_ROADS,+            kind: 0xbeef,+            kind_detail: 0xcafe,+            flags: 0b1010_0101,+            area: true,+            min_zoom: 14,+            min_area_px: 8.0,+        };+        assert_eq!(unpack(pack(&class).expect("pack")), class);++        // And the zero case, which is most features.+        let plain = Class::line(dict::LAYER_WATER, 1, 0);+        assert_eq!(unpack(pack(&plain).expect("pack")), plain);+    }++    /// **Every class the schema can actually produce** has to round-trip, or a feature arrives at the+    /// tiler as something else. Cheaper to prove exhaustively than to trust the bit widths.+    #[test]+    fn every_class_the_schema_emits_round_trips() {+        let cases: &[&[(&str, &str)]] = &[+            &[("natural", "water")],+            &[("waterway", "river")],+            &[("building", "yes")],+            &[("building:part", "yes")],+            &[("highway", "motorway")],+            &[("highway", "motorway_link"), ("bridge", "yes"), ("tunnel", "yes")],+            &[("railway", "subway")],+            &[("boundary", "administrative"), ("admin_level", "2")],+            &[("boundary", "administrative"), ("admin_level", "8")],+            &[("natural", "wood")],+            &[("leisure", "park")],+            &[("leisure", "pitch")],+            &[("landuse", "residential")],+            &[("place", "island")],+            &[("natural", "cliff")],+        ];+        for tags in cases {+            let class =+                schema::classify(*tags, true, schema::Layers::all()).expect("classified");+            let bits = pack(&class).unwrap_or_else(|e| panic!("{tags:?} will not pack: {e:?}"));+            assert_eq!(unpack(bits), class, "{tags:?}");+        }+    }++    /// A threshold that cannot be represented is refused, not rounded. A minimum area quietly+    /// changed is a layer quietly wrong, and it would be invisible.+    #[test]+    fn an_unrepresentable_class_is_refused_rather_than_rounded() {+        let fractional = Class { min_area_px: 2.5, ..Class::area(0, 1, 0) };+        assert!(pack(&fractional).is_err(), "a fractional threshold");+        let huge = Class { min_area_px: 4096.0, ..Class::area(0, 1, 0) };+        assert!(pack(&huge).is_err(), "a threshold past a byte");+        let deep = Class { min_zoom: 32, ..Class::area(0, 1, 0) };+        assert!(pack(&deep).is_err(), "a zoom past five bits");+    }++    #[test]+    fn features_written_come_back_in_order_with_their_geometry() {+        let path = temp("roundtrip");+        let mut sink = Sink::create(&path).expect("create");+        let square = vec![vec![+            (-120.0, 35.0),+            (-119.0, 35.0),+            (-119.0, 36.0),+            (-120.0, 36.0),+            (-120.0, 35.0),+        ]];+        let lake = Class::area(dict::LAYER_WATER, schema::kind("lake"), 6);+        let road = Class::line(dict::LAYER_ROADS, schema::kind("highway"), 3);+        sink.push(&lake, &Geometry::Polygons(vec![square.clone()])).expect("push");+        sink.push(&road, &Geometry::Lines(vec![vec![(-120.0, 35.0), (-119.5, 35.5)]]))+            .expect("push");+        let store = sink.finish(&path).expect("finish");++        assert_eq!(store.len(), 2);+        // The bbox came for free, rather than from a pass of its own over the whole file.+        assert_eq!(store.bbox(), (-1_200_000_000, 350_000_000, -1_190_000_000, 360_000_000));++        let mut reader = store.reader().expect("reader");+        let first = reader.next().expect("read").expect("a feature");+        assert_eq!(first.class, lake);+        assert!(matches!(first.geometry, Geometry::Polygons(ref p) if p[0] == square));+        let second = reader.next().expect("read").expect("a feature");+        assert_eq!(second.class, road);+        assert!(matches!(second.geometry, Geometry::Lines(_)));+        assert!(reader.next().expect("read").is_none(), "and then the end");++        // Re-readable, because the tiler reads it once per zoom.+        let mut again = store.reader().expect("reader");+        assert_eq!(again.next().expect("read").expect("a feature").class, lake);+        let _ = std::fs::remove_file(&path);+    }+}
scripts/maps/mamaps_build/src/tiler.rs
diff --git a/scripts/maps/mamaps_build/src/tiler.rs b/scripts/maps/mamaps_build/src/tiler.rsindex 573f94656b..6f13d6b089 100644--- a/scripts/maps/mamaps_build/src/tiler.rs+++ b/scripts/maps/mamaps_build/src/tiler.rs@@ -40,6 +40,7 @@ use tilecodec::pmtiles::tile_id; use tilecodec::proto::{err, Result};  use crate::extract::Feature;+use crate::store::Store;  /// The tile grid, matching MVT's so nothing downstream rescales. pub const EXTENT: u32 = 4096;@@ -69,8 +70,13 @@ pub struct Settings { }  /// Tile every feature and write the archive.-pub fn build(features: &[Feature], settings: &Settings) -> Result<(Vec<u8>, Vec<ZoomStats>)> {-    let bbox = bounds_e7(features);+/// Tile every feature in `store` into a `.mamaps` archive.+///+/// The store is read **once per zoom**, in order, rather than held in memory for all of them. Fifteen+/// sequential passes over a file cost seconds on any modern disk; holding the features cost 4.9 GB of+/// a measured 10.03 GB California peak.+pub fn build(store: &Store, settings: &Settings) -> Result<(Vec<u8>, Vec<ZoomStats>)> {+    let bbox = store.bbox();     let mut writer = StreamWriter::new(Options {         min_zoom: settings.min_zoom,         max_zoom: settings.max_zoom,@@ -99,7 +105,9 @@ pub fn build(features: &[Feature], settings: &Settings) -> Result<(Vec<u8>, Vec<         let buffer = geom::buffer_for(EXTENT);         let mut touched: Vec<(u64, u64)> = Vec::new(); -        for feature in features {+        // The store speaks osm_ingest's error type and the tiler tile_build's; both wrap a string.+        let mut reader = store.reader().map_err(|e| tile_build::proto::Error(e.to_string()))?;+        while let Some(feature) = reader.next().map_err(|e| tile_build::proto::Error(e.to_string()))? {             if z < feature.class.min_zoom {                 continue;             }@@ -125,7 +133,7 @@ pub fn build(features: &[Feature], settings: &Settings) -> Result<(Vec<u8>, Vec<                     .or_default()                     .entry(feature.class.layer)                     .or_insert_with(|| BodyLayer::new(feature.class.layer));-                let added = push(layer, feature, &local);+                let added = push(layer, &feature, &local);                 stats.features += added.0;                 stats.points += added.1;             }@@ -281,36 +289,7 @@ fn is_empty(g: &Geometry<SigPt>) -> bool {     } } -/// The bounding box of everything, in degrees times 1e7, for the archive header.-fn bounds_e7(features: &[Feature]) -> (i32, i32, i32, i32) {-    let mut out = (i32::MAX, i32::MAX, i32::MIN, i32::MIN);-    let mut seen = false;-    for feature in features {-        for (lon, lat) in coords(&feature.geometry) {-            seen = true;-            let (x, y) = ((lon * 1e7) as i32, (lat * 1e7) as i32);-            out.0 = out.0.min(x);-            out.1 = out.1.min(y);-            out.2 = out.2.max(x);-            out.3 = out.3.max(y);-        }-    }-    if seen {-        out-    } else {-        (0, 0, 0, 0)-    }-} -fn coords(g: &Geometry) -> Vec<(f64, f64)> {-    match g {-        Geometry::Points(points) => points.clone(),-        Geometry::Lines(lines) => lines.iter().flatten().copied().collect(),-        Geometry::Polygons(polygons) => {-            polygons.iter().flatten().flatten().copied().collect()-        }-    }-}  /// A build that produced nothing is a build whose schema matched nothing, which is worth failing on /// rather than publishing an empty archive.@@ -324,6 +303,12 @@ pub fn check_not_empty(stats: &[ZoomStats]) -> Result<()> { #[cfg(test)] mod tests {     use super::*;++    /// The tests hold features in memory and the tiler reads them from a file, so they spill+    /// first. Keeps a test about tiling from reading like a test about plumbing.+    fn spilled(features: &[Feature]) -> crate::store::Store {+        crate::store::Store::of(features).expect("spill")+    }     use crate::schema::Class;     use tilecodec::mamaps::dict; @@ -351,7 +336,7 @@ mod tests {     #[test]     fn a_lake_tiles_and_reads_back_out_of_the_archive() {         let features = vec![lake(-120.0, 35.0, 0.5, 0)];-        let (bytes, stats) = build(&features, &settings(0, 6)).expect("build");+        let (bytes, stats) = build(&spilled(&features), &settings(0, 6)).expect("build");         check_not_empty(&stats).expect("not empty");          let entries = tilecodec::mamaps::read::read_all(&bytes).expect("read back");@@ -371,7 +356,7 @@ mod tests {     #[test]     fn a_feature_is_not_written_above_its_own_min_zoom() {         let features = vec![lake(-120.0, 35.0, 0.01, 10)];-        let (_, stats) = build(&features, &settings(0, 11)).expect("build");+        let (_, stats) = build(&spilled(&features), &settings(0, 11)).expect("build");         for s in &stats {             if s.zoom < 10 {                 assert_eq!(s.tiles, 0, "z{} should be empty", s.zoom);@@ -393,8 +378,8 @@ mod tests {                 geometry: square(-120.1, 35.1, 0.02),             },         ];-        let first = build(&features, &settings(0, 8)).expect("first").0;-        let second = build(&features, &settings(0, 8)).expect("second").0;+        let first = build(&spilled(&features), &settings(0, 8)).expect("first").0;+        let second = build(&spilled(&features), &settings(0, 8)).expect("second").0;         assert_eq!(first, second, "two runs of the same input");          let entries = tilecodec::mamaps::read::read_all(&first).expect("read");@@ -417,7 +402,7 @@ mod tests {                 geometry: square(-120.005, 35.005, 0.002),             },         ];-        let (bytes, _) = build(&features, &settings(14, 14)).expect("build");+        let (bytes, _) = build(&spilled(&features), &settings(14, 14)).expect("build");         let entries = tilecodec::mamaps::read::read_all(&bytes).expect("read");         let both = entries.iter().any(|(_, _, body)| {             let body = Body::parse(body).expect("parse");@@ -430,7 +415,7 @@ mod tests {     fn a_build_that_matched_nothing_fails_rather_than_publishing_an_empty_archive() {         let stats = vec![ZoomStats { zoom: 0, ..ZoomStats::default() }];         assert!(check_not_empty(&stats).is_err());-        assert!(build(&[], &settings(0, 2)).is_err(), "the writer refuses an empty archive");+        assert!(build(&spilled(&[]), &settings(0, 2)).is_err(), "the writer refuses an empty archive");     }      /// Simplification is per zoom, so a shallow tile holds fewer points for the same shape. If this@@ -445,7 +430,7 @@ mod tests {             class: Class::line(dict::LAYER_WATER, crate::schema::kind("river"), 0),             geometry: Geometry::Lines(vec![points]),         }];-        let (_, stats) = build(&features, &settings(6, 14)).expect("build");+        let (_, stats) = build(&spilled(&features), &settings(6, 14)).expect("build");         let at = |z: u8| stats.iter().find(|s| s.zoom == z).expect("zoom").points;         assert!(at(6) < at(14), "z6 has {} points, z14 has {}", at(6), at(14));     }