Modern Apps git

← Modern-Apps.git

maps: various fixes

Commit
635c07691ec7cbbf8f0653ac5462c2c18423e8af
Author
vayun-mathur <[email protected]>
When
2026-09-02 16:04 UTC (3 months ago)
Parents
51cff9a

Diff

.gitignore
diff --git a/.gitignore b/.gitignoreindex c1fe7d0ced..b60eea7638 100644--- a/.gitignore+++ b/.gitignore@@ -75,3 +75,5 @@ health/src/main/assets/staging.db wtfps-experiment/ wtfps/ planet_out/+waterh_analysis+renpho_analysis
gradle/libs.versions.toml
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex 084e7bf0d2..0641131dc5 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -121,6 +121,7 @@ ringrtcAndroid = "2.71.0"  # XML kxml2 = "2.3.0"+robolectric = "4.14.1"  # Payments, telephony & auth stripe = "21.12.0"@@ -284,18 +285,6 @@ quickjs-kt = { module = "io.github.dokar3:quickjs-kt", version.ref = "quickjs" } # Git jgit = { module = "org.eclipse.jgit:org.eclipse.jgit", version.ref = "jgit" } -# On-device AI: nothing here.-#-# Every model in this tree runs on `:library:ml`, our own Vulkan compute runtime, reading `.maml`-# weights. `com.microsoft.onnxruntime:onnxruntime-android` and the reduced rebuild of it,-# `io.github.vayun-mathur:onnxruntime-reduced-android`, were the last third-party inference runtimes-# and both are gone: TinyCLIP (`photos`) and whisper-base (`speech`) were the two remaining users.-#-# The reduced build is worth remembering as a shape of dependency to avoid. It was our own rebuild of-# upstream with `--include_ops_by_config` against an operator list generated from the very models it-# ran, so re-exporting a model meant regenerating the AAR by hand or watching session creation fail.-# Nothing in `.maml` has that coupling: the container carries tensors and the forward pass is Rust.- # Crypto, security & credential storage cryptography-core = { module = "dev.whyoleg.cryptography:cryptography-core", version.ref = "cryptographyCore" } cryptography-provider-jdk = { module = "dev.whyoleg.cryptography:cryptography-provider-jdk", version.ref = "cryptographyCore" }@@ -306,6 +295,9 @@ ringrtc-android = { module = "org.signal:ringrtc-android", version.ref = "ringrt # XML kxml2 = { module = "net.sf.kxml:kxml2", version.ref = "kxml2" } +# Testing+robolectric = { module = "org.robolectric:robolectric", version.ref = "robolectric" }+ # Payments, telephony & auth stripe-android = { module = "com.stripe:stripe-android", version.ref = "stripe" } appauth = { group = "net.openid", name = "appauth", version.ref = "appauth" }
interpret.rs
diff --git a/interpret.rs b/interpret.rsnew file mode 100644index 0000000000..e69de29bb2
library/tilecodec/src/main/rust/src/mamaps/body.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/body.rs b/library/tilecodec/src/main/rust/src/mamaps/body.rsindex 9e39ca4095..94a748e8c0 100644--- a/library/tilecodec/src/main/rust/src/mamaps/body.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/body.rs@@ -52,6 +52,7 @@ pub const BODY_HEADER_LEN: usize = 16; pub const LAYER_INDEX_LEN: usize = 12; pub const FEATURE_RECORD_LEN: usize = 16; pub const PART_ENTRY_LEN: usize = 12;+pub const BODY_FLAG_EXTENDED_COUNTS: u8 = 0x01;  /// A feature whose geometry is one or more open paths. pub const GEOM_LINE: u8 = 1;@@ -194,7 +195,7 @@ impl Body {     }      /// Body header: `0..4` magic-and-version, `4..8` raw_len, `8..10` extent, `10` layer_count,-    /// `11` flags, `12..16` reserved.+    /// `11` flags, `12..16` reserved. Flag `0x01` means extended feature counts follow the layer index.     pub fn parse(buf: &[u8]) -> Result<Body> {         if buf.len() < BODY_HEADER_LEN {             return err("a .mamaps body is shorter than its own header");@@ -217,14 +218,29 @@ impl Body {             return err("a .mamaps body has a zero extent");         }         let layer_count = buf[10] as usize;-        if u32::from_le_bytes([buf[12], buf[13], buf[14], buf[15]]) != 0 {+        let body_flags = buf[11];+        if body_flags & !BODY_FLAG_EXTENDED_COUNTS != 0 {+            return err(format!("unknown body flags {:#04x}", body_flags));+        }+        // Reserved word must be zero unless extended flag is set; extended uses it as spill for counts.+        if body_flags & BODY_FLAG_EXTENDED_COUNTS == 0+            && u32::from_le_bytes([buf[12], buf[13], buf[14], buf[15]]) != 0+        {             return err("a .mamaps body has a non-zero reserved word");         } -        let index_end = BODY_HEADER_LEN + layer_count * LAYER_INDEX_LEN;+        let has_extended = (body_flags & BODY_FLAG_EXTENDED_COUNTS) != 0;+        let mut index_end = BODY_HEADER_LEN + layer_count * LAYER_INDEX_LEN;+        if has_extended {+            index_end = index_end.checked_add(layer_count * 4).ok_or_else(|| {+                crate::proto::Error("extended counts overflow".to_string())+            })?;+        }         if index_end > buf.len() {             return err("a .mamaps body's layer index runs past its end");         }+        // Extended counts live right after the layer index, one u32 LE per layer in order.+        let ext_at = BODY_HEADER_LEN + layer_count * LAYER_INDEX_LEN;         let mut layers = Vec::with_capacity(layer_count);         let mut previous: Option<u8> = None;         for i in 0..layer_count {@@ -239,7 +255,16 @@ impl Body {                 return err("a .mamaps body's layers are not ordered by id");             }             previous = Some(layer_id);-            let feature_count = u16::from_le_bytes([buf[at + 2], buf[at + 3]]) as usize;+            let feature_count = if has_extended {+                u32::from_le_bytes([+                    buf[ext_at + i * 4],+                    buf[ext_at + i * 4 + 1],+                    buf[ext_at + i * 4 + 2],+                    buf[ext_at + i * 4 + 3],+                ]) as usize+            } else {+                u16::from_le_bytes([buf[at + 2], buf[at + 3]]) as usize+            };             let (offset, length) = (u32_at(4) as usize, u32_at(8) as usize);             let end = offset.checked_add(length).ok_or_else(|| {                 crate::proto::Error("a .mamaps layer's extent overflows".to_string())@@ -382,7 +407,7 @@ pub(crate) fn align4(at: usize) -> usize { #[derive(Default)] pub struct Scratch {     payloads: Vec<Vec<u8>>,-    meta: Vec<(u8, u16)>,+    meta: Vec<(u8, u32)>,     out: Vec<u8>, } @@ -400,8 +425,9 @@ pub fn serialize_into<'s>(body: &Body, scratch: &'s mut Scratch) -> Result<&'s [     if layers.windows(2).any(|pair| pair[0].layer_id == pair[1].layer_id) {         return err("a .mamaps body cannot carry two layers with the same id");     }+    let needs_extended = layers.iter().any(|l| l.features.len() > u16::MAX as usize);     for layer in &layers {-        if layer.features.len() > u16::MAX as usize {+        if !needs_extended && layer.features.len() > u16::MAX as usize {             return err(format!(                 "layer {} has {} features, past the {} a .mamaps body can index",                 layer.layer_id,@@ -409,6 +435,13 @@ pub fn serialize_into<'s>(body: &Body, scratch: &'s mut Scratch) -> Result<&'s [                 u16::MAX,             ));         }+        if layer.features.len() > u32::MAX as usize {+            return err(format!(+                "layer {} has {} features, past u32",+                layer.layer_id,+                layer.features.len()+            ));+        }         // The arena is written in parts-table order with no offsets of its own, so a part has to         // start exactly where the one before it ended. Checked here rather than trusted, because a         // caller that got it wrong would produce a body that round-trips to different geometry.@@ -445,7 +478,10 @@ pub fn serialize_into<'s>(body: &Body, scratch: &'s mut Scratch) -> Result<&'s [         }     } -    let index_end = BODY_HEADER_LEN + layers.len() * LAYER_INDEX_LEN;+    let mut index_end = BODY_HEADER_LEN + layers.len() * LAYER_INDEX_LEN;+    if needs_extended {+        index_end += layers.len() * 4;+    }     // Both fields at once, which needs the struct broken apart: the payloads are built first and     // then copied into the output, and each wants its own mutable borrow.     let Scratch { payloads, meta, out: assembled } = scratch;@@ -498,7 +534,7 @@ pub fn serialize_into<'s>(body: &Body, scratch: &'s mut Scratch) -> Result<&'s [                 (px, py) = (x as i32, y as i32);             }         }-        meta.push((layer.layer_id, layer.features.len() as u16));+        meta.push((layer.layer_id, layer.features.len() as u32));     }      let mut offset = align4(index_end);@@ -510,16 +546,30 @@ pub fn serialize_into<'s>(body: &Body, scratch: &'s mut Scratch) -> Result<&'s [     assembled.extend_from_slice(&0u32.to_le_bytes());     assembled.extend_from_slice(&body.extent.to_le_bytes());     assembled.push(layers.len() as u8);-    assembled.push(0);+    assembled.push(if needs_extended { BODY_FLAG_EXTENDED_COUNTS } else { 0 });     assembled.extend_from_slice(&0u32.to_le_bytes());     for (i, (layer_id, feature_count)) in meta.iter().enumerate() {         assembled.push(*layer_id);         assembled.push(0);-        assembled.extend_from_slice(&feature_count.to_le_bytes());+        // For extended, write sentinel-limited low 16 (old readers see at most 65534+        // and reject on payload bound); real count is the u32 after the index.+        let fc: u16 = if needs_extended {+            (*feature_count as usize).min(0xFFFE) as u16+        } else {+            // Non-extended path is byte-identical to the old format: u16 carry+            // validated above to be ≤65535.+            u16::try_from(*feature_count).expect("feature count fits u16 in non-extended body")+        };+        assembled.extend_from_slice(&fc.to_le_bytes());         assembled.extend_from_slice(&(offset as u32).to_le_bytes());         assembled.extend_from_slice(&(payloads[i].len() as u32).to_le_bytes());         offset += payloads[i].len();     }+    if needs_extended {+        for layer in &layers {+            assembled.extend_from_slice(&(layer.features.len() as u32).to_le_bytes());+        }+    }     while assembled.len() % 4 != 0 {         assembled.push(0);     }@@ -909,4 +959,40 @@ mod tests {         reordered.layers.reverse();         assert_eq!(serialize(&sample()).expect("a"), serialize(&reordered).expect("b"));     }++    #[test]+    fn a_layer_with_more_than_65535_features_round_trips_via_extended_encoding() {+        let mut layer = Layer::new(10);+        let n = 70000usize;+        for i in 0..n {+            layer.features.push(Feature {+                kind: 1,+                kind_detail: 0,+                geom_type: GEOM_LINE,+                flags: 0,+                parts_offset: i as u32,+                part_count: 1,+            });+            layer.parts.push(Part { coord_start: (i * 2) as u32, point_count: 2, winding: WINDING_OUTER });+            layer.coords.push((0, 0));+            layer.coords.push((1, 1));+        }+        let body = Body { extent: DEFAULT_EXTENT, layers: vec![layer] };+        let bytes = serialize(&body).expect("extended tile must serialize");+        assert_eq!(bytes[11], BODY_FLAG_EXTENDED_COUNTS, "extended flag set");+        let parsed = Body::parse(&bytes).expect("must parse extended");+        assert_eq!(parsed.layers[0].features.len(), n);+        assert_eq!(parsed.layers[0].parts.len(), n);+        // Non-extended path stays byte-identical for common case.+        let small_body = Body { extent: DEFAULT_EXTENT, layers: vec![{+            let mut l = Layer::new(10);+            l.features.push(Feature { kind: 1, kind_detail: 0, geom_type: GEOM_LINE, flags: 0, parts_offset: 0, part_count: 1 });+            l.parts.push(Part { coord_start: 0, point_count: 2, winding: WINDING_OUTER });+            l.coords.extend_from_slice(&[(0, 0), (1, 1)]);+            l+        }] };+        let small_bytes = serialize(&small_body).expect("small tile");+        assert_eq!(small_bytes[11], 0, "common path no flag, byte-identical");+        assert_eq!(small_bytes[12..16], [0, 0, 0, 0], "reserved still zero for common path");+    } }
library/tilecodec/src/main/rust/src/mamaps/header.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/header.rs b/library/tilecodec/src/main/rust/src/mamaps/header.rsindex 7565b41645..7f2f0df772 100644--- a/library/tilecodec/src/main/rust/src/mamaps/header.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/header.rs@@ -29,9 +29,14 @@ pub const FLAG_RUN_LENGTH_PRESENT: u16 = 1 << 1; /// What lets `tess::fill`'s repair pass be skipped: with this set, every polygon part group has /// exactly one CCW outer and its holes are CW and strictly inside it. pub const FLAG_RINGS_VALIDATED: u16 = 1 << 2;+/// The leaf index exceeds 4 GiB (planet scale: ~268M bodies ×16 B ≈4.29 GB).+/// When set, bytes 72..80 of the header hold leaf_len as a little-endian u64+/// (instead of u32 leaf_len at 72..76 plus 0-reserved at 76..80). Common+/// path (NA ~418 MB) stays flag 0 + u32 + 0 — byte-identical to v1.+pub const FLAG_LEAF_LEN_64: u16 = 1 << 3;  const KNOWN_FLAGS: u16 =-    FLAG_BODIES_COMPRESSED | FLAG_RUN_LENGTH_PRESENT | FLAG_RINGS_VALIDATED;+    FLAG_BODIES_COMPRESSED | FLAG_RUN_LENGTH_PRESENT | FLAG_RINGS_VALIDATED | FLAG_LEAF_LEN_64;  /// Bodies stored as written. pub const COMPRESSION_NONE: u8 = 0;@@ -77,7 +82,10 @@ pub struct Header {     pub root_len: u32,     pub leaf_count: u32,     pub leaf_offset: u64,-    pub leaf_len: u32,+    /// Leaf index length. u64 on the wire when FLAG_LEAF_LEN_64 is set+    /// (planet: ~4.29 GB); otherwise the 72..76 u32 plus 76..80 zero+    /// reserved — so NA/us-west stay byte-identical.+    pub leaf_len: u64,     pub data_offset: u64,     pub data_len: u64,     /// Tiles that resolve to a body, counting every id a run covers.@@ -150,11 +158,26 @@ impl Header {         if flags & !KNOWN_FLAGS != 0 {             return err(format!("a .mamaps header sets unknown flags {:#06X}", flags & !KNOWN_FLAGS));         }-        // Reserved bytes are checked rather than skipped, so a later version cannot put a field-        // here and have this reader silently ignore it.-        if u32_at(76) != 0 {-            return err("a .mamaps header has a non-zero reserved word");-        }+        // Bytes 72..80 hold leaf_len: 72..76 low 32, 76..80 high 32 when+        // FLAG_LEAF_LEN_64 is set, otherwise 76..80 must be zero (v1 reserved).+        // Common path (NA ~418 MB) stays flag 0 + u32 + 0 — byte-identical to v1.+        let leaf_len = if (flags & FLAG_LEAF_LEN_64) != 0 {+            let lo = u32_at(72) as u64;+            let hi = u32_at(76) as u64;+            let v = lo | (hi << 32);+            if v <= u32::MAX as u64 {+                return err(format!(+                    "a .mamaps header sets FLAG_LEAF_LEN_64 but leaf_len {} fits u32",+                    v+                ));+            }+            v+        } else {+            if u32_at(76) != 0 {+                return err("a .mamaps header has a non-zero reserved word");+            }+            u32_at(72) as u64+        };         let header = Header {             flags,             compression: buf[12],@@ -170,7 +193,7 @@ impl Header {             root_len: u32_at(56),             leaf_count: u32_at(60),             leaf_offset: u64_at(64),-            leaf_len: u32_at(72),+            leaf_len,             data_offset: u64_at(80),             data_len: u64_at(88),             tiles_addressed: u64_at(96),@@ -274,8 +297,15 @@ impl Header {         out.extend_from_slice(&self.root_len.to_le_bytes());         out.extend_from_slice(&self.leaf_count.to_le_bytes());         out.extend_from_slice(&self.leaf_offset.to_le_bytes());-        out.extend_from_slice(&self.leaf_len.to_le_bytes());-        out.extend_from_slice(&0u32.to_le_bytes());+        // 72..76 is always low 32 of leaf_len; 76..80 is high 32 when extended,+        // otherwise reserved zero. Common path (<4 GiB): high 32 == 0 → byte-identical to v1 (u32 + 0).+        out.extend_from_slice(&(self.leaf_len as u32).to_le_bytes());+        if (self.flags & FLAG_LEAF_LEN_64) != 0 {+            // Extended: 76..80 holds high 32 of the true u64 leaf_len (planet ~4.29 GB).+            out.extend_from_slice(&((self.leaf_len >> 32) as u32).to_le_bytes());+        } else {+            out.extend_from_slice(&0u32.to_le_bytes());+        }         out.extend_from_slice(&self.data_offset.to_le_bytes());         out.extend_from_slice(&self.data_len.to_le_bytes());         out.extend_from_slice(&self.tiles_addressed.to_le_bytes());@@ -403,4 +433,57 @@ mod tests {         header.data_len = 64;         assert!(Header::parse(&header.serialize()).is_err(), "the end wraps");     }++    /// Planet scale: leaf index is ~268M bodies ×16 B ≈4.29 GB > u32::MAX,+    /// overflowing the old 4 GiB leaf_len field by 1257 B in the failed run.+    /// Extended encoding uses FLAG_LEAF_LEN_64 and the formerly-reserved+    /// 76..80 word as high 32 of a u64 leaf_len (72..76 low 32). Common path+    /// (NA ~418 MB < u32::MAX) stays flag 0 + u32 + 0 → byte-identical to v1.+    #[test]+    fn a_leaf_len_past_u32_max_round_trips_and_common_path_stays_byte_identical() {+        // The leaf field itself round-trips via Header serialization; use a+        // large file_len so the overall header check (sections fit) doesn't+        // reject the test file. NA's file_len is 418 MB leaf_len + data, but+        // plausible() is 4096 B — enlarge for the planet-sized leaf.+        let planet_leaf: u64 = u32::MAX as u64 + 1257;+        // Extended: flag set, high word carries the overflow.+        let mut extended = Header {+            leaf_len: planet_leaf,+            flags: FLAG_BODIES_COMPRESSED | FLAG_LEAF_LEN_64,+            ..plausible()+        };+        extended.data_offset = extended.leaf_offset + extended.leaf_len;+        extended.file_len = extended.data_offset + extended.data_len;+        let bytes_ext = extended.serialize();+        assert_eq!(bytes_ext.len(), HEADER_LEN);+        assert_ne!(bytes_ext[10] & 0x08, 0, "extended flag must be set");+        assert_ne!(&bytes_ext[76..80], &[0, 0, 0, 0], "high word must carry overflow (1257 beyond 4 GiB)");+        let parsed = Header::parse(&bytes_ext).expect("extended must parse");+        assert_eq!(parsed.leaf_len, planet_leaf);+        assert_eq!(parsed.flags & FLAG_LEAF_LEN_64, FLAG_LEAF_LEN_64);+        // Common path (NA ~418 MB) stays byte-identical to v1: flag 0, reserved 0, low 32 only.+        let na_leaf: u64 = 418 * 1024 * 1024;+        let mut common = Header {+            leaf_len: na_leaf,+            ..plausible()+        };+        common.data_offset = common.leaf_offset + common.leaf_len;+        common.file_len = common.data_offset + common.data_len;+        let bytes_common = common.serialize();+        assert_eq!(bytes_common.len(), HEADER_LEN);+        assert_eq!(bytes_common[10] & FLAG_LEAF_LEN_64 as u8, 0, "common flag must be 0");+        assert_eq!(&bytes_common[76..80], &[0, 0, 0, 0], "reserved must stay 0 for <4 GiB");+        assert_eq!(Header::parse(&bytes_common).expect("common must parse").leaf_len, na_leaf);+        // Byte-identity: common bytes up to leaf_len are identical to what v1+        // would have written (low 32 + 0 reserved); extended differs only in flag + high word.+        // Extended canonical: flag set but value fits u32 is rejected+        let mut bad = Header {+            leaf_len: 100,+            flags: FLAG_BODIES_COMPRESSED | FLAG_LEAF_LEN_64,+            ..plausible()+        };+        bad.data_offset = bad.leaf_offset + bad.leaf_len;+        bad.file_len = bad.data_offset + bad.data_len;+        assert!(Header::parse(&bad.serialize()).is_err(), "extended with small leaf_len must be rejected");+    } }
library/tilecodec/src/main/rust/src/mamaps/write.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/write.rs b/library/tilecodec/src/main/rust/src/mamaps/write.rsindex 82e4517ad7..d28a53109d 100644--- a/library/tilecodec/src/main/rust/src/mamaps/write.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/write.rs@@ -441,6 +441,15 @@ impl StreamWriter {          let leaf_bytes: Vec<u8> =             leaves.iter().flat_map(|leaf| index::serialize_leaf(leaf)).collect();+        let leaf_len = leaf_bytes.len() as u64;+        // Planet scale: ~268M bodies ×16 B ≈4.29 GB > u32::MAX (1257 B overflow+        // in the failed run). Common path (NA ~418 MB, CA ~tens of MB) stays+        // flag 0 + u32 + 0 — byte-identical to v1. Extended path uses+        // FLAG_LEAF_LEN_64 and the 72..80 u64 slot (was u32+reserved).+        let needs_leaf64 = leaf_len > u32::MAX as u64;+        if needs_leaf64 {+            flags |= crate::mamaps::header::FLAG_LEAF_LEN_64;+        }         let root_bytes = index::serialize_root(&root);         let dict_offset = HEADER_LEN as u64;         let root_offset = dict_offset + dictionary.len() as u64;@@ -463,7 +472,7 @@ impl StreamWriter {             root_len: root_bytes.len() as u32,             leaf_count: root.len() as u32,             leaf_offset,-            leaf_len: leaf_bytes.len() as u32,+            leaf_len,             data_offset,             data_len,             tiles_addressed: self.tiles_addressed,
robustness_tests.rs
diff --git a/robustness_tests.rs b/robustness_tests.rsnew file mode 100644index 0000000000..e69de29bb2
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 4c173b3a0c..6236f7492e 100644--- a/scripts/maps/mamaps_build/src/extract.rs+++ b/scripts/maps/mamaps_build/src/extract.rs@@ -24,6 +24,21 @@ //! in ascending id order so no sort is needed to read them back in the order the archive wants. //! What stays resident is the set a sequential file cannot serve: the refs of the ways that some //! relation lists as a member, because a relation reaches those by id in its own order.+//!+//! # Collecting the needed ids: two shapes, one switch+//!+//! Pass 3 needs the ids sorted and unique, and there are two ways to get there. The obvious one --+//! one `Vec<i64>` of every ref **with duplicates**, sorted and deduped in place -- is what+//! [`collect_needed_in_memory`] does, and it is right up to a point: it is exact, it needs no+//! assumption about the ids, and on anything smaller than a continent it is smaller than the+//! alternative. Past that point it is the largest thing in the whole build. North-america is ~19 GB+//! of it; planet projects to ~96 GB and a sort of 12 G elements.+//!+//! [`collect_needed_by_bitset`] is the other shape, taken above [`REFS_IN_MEMORY`]: a bit per node+//! id, which is at most ~1.7 GB *for any extract, forever*, because OSM's node ids are monotonic and+//! near 13 G. Walking it low to high yields sorted unique ids directly, so it removes the vector and+//! the sort together, in one streaming pass with no extra I/O. Both paths must produce the same+//! sequence and `the_two_ref_collectors_agree_on_the_same_input` holds them to it.  use std::collections::HashMap; use std::path::Path;@@ -182,7 +197,7 @@ pub fn extract(             Ok(())         },     )?;-    let WayCounts { ways: ways_classified, refs: way_refs } = ways.finish()?;+    let WayCounts { ways: ways_classified, refs: way_refs, max_ref: way_max_ref } = ways.finish()?;     stats.ways_classified = ways_classified;     stats.relations_classified = relations.len() as u64; @@ -231,29 +246,19 @@ pub fn extract(      // --- pass 3: the coordinates those two asked for --------------------------------------     //-    // The classified ways are read off disk instead of walked in memory. Order does not matter here-    // — `NodeLocations::new` sorts and dedups — so this is a plain streaming pass over the spill.-    //-    // Sized exactly rather than grown into. This is ~200 M ids on California, and a `Vec` that-    // doubles its way there holds the old and the new allocation at once across the last realloc:-    // 1.1 GB plus 2.1 GB, for a length both passes already know.+    // The classified ways are read off disk instead of walked in memory. Order does not matter to+    // either path below, so this is a plain streaming pass over the spill.     let member_refs: usize = members.values().map(|refs| refs.len()).sum();-    let mut needed: Vec<i64> = Vec::with_capacity(way_refs as usize + member_refs);-    {-        let mut reader = WayReader::open(&ways_path)?;-        let mut refs: Vec<i64> = Vec::new();-        while reader.next(&mut refs)?.is_some() {-            needed.extend_from_slice(&refs);-        }-    }-    // A member way that pass 1 also classified already contributed its refs above; `members` adds-    // the ones — the great majority, since a multipolygon's rings usually carry no tags of their-    // own — that nothing else asked for.-    for refs in members.values() {-        needed.extend_from_slice(refs);-    }-    mark("refs collected");-    let table = NodeLocations::new(needed)?;+    let refs_total = way_refs as usize + member_refs;+    let max_ref = members+        .values()+        .flat_map(|refs| refs.iter().copied())+        .fold(way_max_ref, i64::max);+    let table = if refs_total <= REFS_IN_MEMORY {+        collect_needed_in_memory(&ways_path, &members, refs_total, &mark)?+    } else {+        collect_needed_by_bitset(&ways_path, &members, max_ref, &mark)?+    };     mark("id index built, refs freed");     stats.nodes_needed = table.len() as u64;     let table = resolve_nodes(input, &blobs, &blob_kinds, "Pass 3: nodes", table)?;@@ -404,6 +409,160 @@ pub fn extract(     Ok((store, stats)) } +/// Node refs, duplicates included, above which the bitset replaces the sorted vector.+///+/// 256 M refs is a 2 GB `Vec<i64>` plus a sort of 256 M elements, and it is roughly a us-west+/// extract. Below it the vector is smaller than the bitset and this stays exactly as it always was;+/// above it the vector is the largest thing in stage A and the bitset is a constant.+const REFS_IN_MEMORY: usize = 256 << 20;++/// The node id a bitset will not be sized past.+///+/// OSM assigns node ids monotonically and is near 13 G, so this is roughly 4x today's high-water+/// mark and 2.6 GB of bitset. It is a bound on the *data*, and a synthetic or non-OSM input with one+/// sparse enormous id would otherwise ask for a bitset the size of the id, so it is an error rather+/// than a clamp: a clamp would silently drop the nodes above it.+const MAX_NODE_ID: i64 = 48 << 30;++/// The ids pass 3 must resolve, collected the way stage A always did.+///+/// One exactly-sized vector, then [`NodeLocations::new`] sorts and dedups it in place. Sized rather+/// than grown into because a `Vec` that doubles its way to 200 M ids holds the old and the new+/// allocation at once across the last realloc -- 1.1 GB plus 2.1 GB, for a length both earlier passes+/// already know.+fn collect_needed_in_memory(+    ways_path: &Path,+    members: &HashMap<i64, Vec<i64>>,+    refs_total: usize,+    mark: &dyn Fn(&str),+) -> Result<NodeLocations> {+    let mut needed: Vec<i64> = Vec::with_capacity(refs_total);+    {+        let mut reader = WayReader::open(ways_path)?;+        let mut refs: Vec<i64> = Vec::new();+        while reader.next(&mut refs)?.is_some() {+            needed.extend_from_slice(&refs);+        }+    }+    // A member way that pass 1 also classified already contributed its refs above; `members` adds+    // the ones — the great majority, since a multipolygon's rings usually carry no tags of their+    // own — that nothing else asked for.+    for refs in members.values() {+        needed.extend_from_slice(refs);+    }+    mark("refs collected");+    NodeLocations::new(needed)+}++/// The same ids, through a bitset over the node id space.+///+/// The vector above is `way_refs + member_refs` entries of eight bytes **with duplicates**, then a+/// sort of all of them. On a north-america extract that is ~19 GB; on a planet one it projects to+/// ~96 GB and a sort of 12 G elements, which is the second of the two things that stopped a planet+/// build before anything else got the chance to.+///+/// A bit per node id costs `max_id / 8` and **does not scale with the extract**: OSM node ids are+/// assigned monotonically and top out near 13 G, so this is at most ~1.7 GB for any extract, forever.+/// Streaming the refs into it and then walking it low to high yields sorted unique ids directly --+/// which removes the vector *and* the sort in one pass, with no extra I/O.+///+/// Not an external merge sort of the ref stream. That is the general answer and needs no assumption+/// about the ids, and it costs ~96 GB written and ~96 GB read at planet scale to compute what this+/// gets in one pass. The bound that makes the bitset safe -- monotonic, bounded ids -- is a property+/// of OSM's data rather than a hope about it, and [`MAX_NODE_ID`] is where that property is enforced.+fn collect_needed_by_bitset(+    ways_path: &Path,+    members: &HashMap<i64, Vec<i64>>,+    max_ref: i64,+    mark: &dyn Fn(&str),+) -> Result<NodeLocations> {+    let mut bits = NeededBits::new(max_ref)?;+    {+        let mut reader = WayReader::open(ways_path)?;+        let mut refs: Vec<i64> = Vec::new();+        while reader.next(&mut refs)?.is_some() {+            for &id in &refs {+                bits.set(id)?;+            }+        }+    }+    for refs in members.values() {+        for &id in refs {+            bits.set(id)?;+        }+    }+    mark("refs collected");+    // Ascending and unique by construction, which is `from_sorted`'s whole precondition.+    NodeLocations::from_sorted(bits.ids(), bits.len())+}++/// One bit per node id in `0..=max_id`.+struct NeededBits {+    words: Vec<u64>,+    /// `max_id + 1`. Kept because the last word is padded and a ref landing in that padding is out+    /// of range, not merely addressable.+    bits: usize,+    count: usize,+}++impl NeededBits {+    fn new(max_id: i64) -> Result<NeededBits> {+        if max_id > MAX_NODE_ID {+            return err(format!(+                "node id {max_id} is past the {MAX_NODE_ID} this build will size a bitset for; \+                 OSM's own ids are near 13 billion, so this input is not an OSM extract"+            ));+        }+        // `max_id` is a maximum, not a count, so the space is one larger.+        let bits = max_id.max(0) as usize + 1;+        Ok(NeededBits { words: vec![0u64; bits.div_ceil(64)], bits, count: 0 })+    }++    fn set(&mut self, id: i64) -> Result<()> {+        // A negative ref is not a node this planet has. Refused rather than skipped: it means the+        // spill or the PBF is not what it claims, and skipping would show as a way with a gap in it.+        if id < 0 {+            return err(format!("node ref {id} is negative"));+        }+        let at = id as usize;+        if at >= self.bits {+            return err(format!(+                "node ref {id} is past the {} the bitset was sized for",+                self.bits - 1+            ));+        }+        let word = &mut self.words[at / 64];+        let bit = 1u64 << (at % 64);+        if *word & bit == 0 {+            *word |= bit;+            self.count += 1;+        }+        Ok(())+    }++    /// How many distinct ids were set. The `len` [`NodeLocations::from_sorted`] sizes from.+    fn len(&self) -> usize {+        self.count+    }++    /// Every set id, ascending. `trailing_zeros` on a word at a time, so an empty stretch of the id+    /// space -- which is most of it, since a needed set is a subset of a subset -- costs one compare+    /// per 64 ids rather than one per id.+    fn ids(&self) -> impl Iterator<Item = i64> + '_ {+        self.words.iter().enumerate().flat_map(|(w, word)| {+            let mut rest = *word;+            std::iter::from_fn(move || {+                if rest == 0 {+                    return None;+                }+                let bit = rest.trailing_zeros() as usize;+                rest &= rest - 1;+                Some((w * 64 + bit) as i64)+            })+        })+    }+}+ /// A node's location in lon/lat, which is the order [`rings::assemble`] and GeoJSON both want. /// /// [`NodeLocations::get`] returns lat/lon, matching the PBF's own field order.@@ -439,6 +598,119 @@ fn way_geometry(line: &[(f64, f64)], area: bool) -> Option<Geometry> { mod tests {     use super::*; +    /// The claim the bitset path rests on: it yields exactly the sequence the vector path's sort and+    /// dedup would, for the same input. Everything downstream -- the id index, the positions the node+    /// pass writes coordinates at -- follows from that one equality.+    #[test]+    fn the_bitset_yields_what_a_sort_and_dedup_would() {+        // Deliberately awkward: duplicates, a run of consecutive ids inside one word, gaps that skip+        // whole words, both ends of the space, and ids past `u32::MAX`.+        let refs: Vec<i64> = vec![+            0, 63, 64, 65, 1, 1, 1, 4_294_967_295, 4_294_967_296, 12_345_678_901, 128, 127, 2, 63,+            12_345_678_901, 500_000, 499_999, 0,+        ];+        let mut want = refs.clone();+        want.sort_unstable();+        want.dedup();++        let max = *refs.iter().max().expect("refs");+        let mut bits = NeededBits::new(max).expect("size the bitset");+        for &id in &refs {+            bits.set(id).expect("set a bit");+        }+        assert_eq!(bits.ids().collect::<Vec<i64>>(), want);+        assert_eq!(bits.len(), want.len(), "the count must match what `from_sorted` is sized with");+    }++    /// The empty and single-id cases, which the word-at-a-time walk makes easy to get wrong.+    #[test]+    fn an_empty_or_single_id_bitset_is_not_a_special_case() {+        let empty = NeededBits::new(0).expect("size");+        assert_eq!(empty.len(), 0);+        assert!(empty.ids().next().is_none());++        let mut one = NeededBits::new(0).expect("size");+        one.set(0).expect("set");+        assert_eq!(one.ids().collect::<Vec<i64>>(), vec![0]);+        assert_eq!(one.len(), 1);++        // The maximum is inclusive, so a bitset sized for it must hold it.+        let mut edge = NeededBits::new(64).expect("size");+        edge.set(64).expect("the maximum is in range");+        assert_eq!(edge.ids().collect::<Vec<i64>>(), vec![64]);+    }++    /// The bound that makes the bitset affordable is a property of OSM's ids, so an input that+    /// breaks it has to say so rather than ask for an allocation the size of one id.+    #[test]+    fn an_id_outside_osms_own_range_is_refused_rather_than_sized_for() {+        assert!(NeededBits::new(MAX_NODE_ID + 1).is_err(), "a wild maximum was sized for");+        assert!(NeededBits::new(i64::MAX).is_err(), "`i64::MAX` was sized for");++        let mut bits = NeededBits::new(100).expect("size");+        assert!(bits.set(-1).is_err(), "a negative ref was accepted");+        assert!(bits.set(101).is_err(), "a ref past the maximum was accepted");+        assert!(bits.set(100).is_ok());+    }++    /// End to end over a real ways spill: the two collectors must agree on the set they hand pass 3.+    #[test]+    fn the_two_ref_collectors_agree_on_the_same_input() {+        let path = std::env::temp_dir().join(format!(+            "mamaps_refcollect_{}_{:?}.ways.tmp",+            std::process::id(),+            std::thread::current().id(),+        ));+        let class = schema::Class::area(+            tilecodec::mamaps::dict::LAYER_WATER,+            schema::kind("lake"),+            0,+        );+        let mut sink = WaySink::create(&path).expect("create the ways spill");+        // Ascending way ids, as pass 1 produces; overlapping refs, as real ways have.+        for way in 0..64i64 {+            let refs: Vec<i64> = (0..8).map(|i| way * 5 + i).collect();+            sink.push(way + 1, &class, &refs).expect("push");+        }+        let counts = sink.finish().expect("finish");++        let mut members: HashMap<i64, Vec<i64>> = HashMap::new();+        // One member whose refs overlap the spill's, and one that is entirely new.+        members.insert(7, vec![30, 31, 32, 30]);+        members.insert(9, vec![10_000, 9_999, 10_000]);+        let member_refs: usize = members.values().map(|refs| refs.len()).sum();+        let max_ref = members+            .values()+            .flat_map(|refs| refs.iter().copied())+            .fold(counts.max_ref, i64::max);++        let quiet = |_: &str| {};+        let in_memory =+            collect_needed_in_memory(&path, &members, counts.refs as usize + member_refs, &quiet)+                .expect("the in-memory path");+        let by_bitset =+            collect_needed_by_bitset(&path, &members, max_ref, &quiet).expect("the bitset path");++        assert_eq!(+            in_memory.len(),+            by_bitset.len(),+            "the two paths disagree on how many distinct nodes are needed",+        );+        // And the same ids, not merely the same count: both tables must answer for every ref and+        // for nothing between them that was never asked for.+        for id in [0i64, 1, 30, 31, 32, 319, 9_999, 10_000] {+            assert_eq!(+                in_memory.contains(id),+                by_bitset.contains(id),+                "the two paths disagree about node {id}",+            );+        }+        assert!(in_memory.contains(10_000), "a member-only ref is missing");+        assert!(!in_memory.contains(5_000), "an id nothing asked for is present");++        let _ = std::fs::remove_file(&path);+    }+     #[test]     fn an_open_way_is_a_line_and_a_closed_one_an_area_only_if_tagged() {         let square = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0), (0.0, 0.0)];
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 753dacf18d..d03aa154f1 100644--- a/scripts/maps/mamaps_build/src/main.rs+++ b/scripts/maps/mamaps_build/src/main.rs@@ -37,6 +37,7 @@ mod shapefile; mod schema; mod store; mod tiler;+mod tilespill;  /// The allocator, replaced because the default one was three quarters of the build. ///@@ -273,7 +274,14 @@ fn run(         derive_build_id(input, layers, min_zoom, max_zoom, simplification, stats.features)     }); -    let settings = tiler::Settings { min_zoom, max_zoom, simplification, build_id };+    let settings = tiler::Settings {+        min_zoom,+        max_zoom,+        simplification,+        build_id,+        // Beside the archive, as the feature spill is. One zoom at a time, removed as each finishes.+        scratch: scratch_path(out),+    };     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()))?;@@ -330,6 +338,27 @@ fn run(         );     }     let (stage_c, serialize, deflate) = tiler::encode_seconds();+    // How close the archive came to the 65,535-feature cap on one tile-layer. Printed rather than+    // asserted because the answer is what decides whether the field has to widen, and widening it is+    // a `FORMAT_VERSION` bump and a matching renderer change.+    let widest = tiler::widest_layers();+    if !widest.is_empty() {+        let dict = tilecodec::mamaps::dict::Dictionary::schema();+        let worst = widest.iter().map(|(_, n)| *n).max().unwrap_or(0);+        let named: Vec<String> = widest+            .iter()+            .map(|(id, n)| {+                let name = dict.layer_name(*id).unwrap_or("?");+                format!("{name} {n}")+            })+            .collect();+        println!(+            "       widest tile-layer: {} (cap {}, {:.0}% used)",+            named.join(", "),+            u16::MAX,+            worst as f64 / u16::MAX as f64 * 100.0,+        );+    }     println!(         "total  map {:.1}s (of which {:.1}s deserialising the spill, on one thread)  merge {:.1}s  encode {:.1}s  append {:.1}s   ({:.0}% of tiling is serial)",         map as f64 / 1000.0,@@ -364,6 +393,17 @@ fn run(     Ok(()) } +/// Where the tiler parks one zoom's chunks while it merges them.+///+/// Beside the archive, as `<out>.tilechunks`, matching where the feature spill is placed. Appended+/// to the whole file name rather than replacing an extension, so `world.mamaps` and `world.tmp`+/// cannot collide on one path.+fn scratch_path(out: &std::path::Path) -> PathBuf {+    let mut p = out.as_os_str().to_owned();+    p.push(".tilechunks");+    PathBuf::from(p)+}+ /// Hash the inputs that decide what an archive contains. /// /// The input's **length and modification time** rather than its bytes: digesting 1.3 GB to decide a
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 03c6c1095f..5095c88e8f 100644--- a/scripts/maps/mamaps_build/src/rings.rs+++ b/scripts/maps/mamaps_build/src/rings.rs@@ -587,6 +587,8 @@ mod tests {             max_zoom: 10,             simplification: crate::tiler::DEFAULT_SIMPLIFICATION,             build_id: 1,+            scratch: std::env::temp_dir()+                .join(format!("mamaps_rings_{}.tilechunks", std::process::id())),         };         let store = crate::store::Store::of(&features).expect("spill");         let (bytes, stats) = crate::tiler::build(&store, &settings).expect("build");
scripts/maps/mamaps_build/src/store.rs
diff --git a/scripts/maps/mamaps_build/src/store.rs b/scripts/maps/mamaps_build/src/store.rsindex eaf68ed439..d115d27057 100644--- a/scripts/maps/mamaps_build/src/store.rs+++ b/scripts/maps/mamaps_build/src/store.rs@@ -456,6 +456,44 @@ impl Store {         )     } +    pub fn wanted_chunks_for_zoom(&self, z: u8) -> Vec<usize> {+        self.chunk_mins+            .iter()+            .enumerate()+            .filter(|(_, min)| **min <= z)+            .map(|(i, _)| i)+            .collect()+    }++    pub fn wanted_len_for_zoom(&self, z: u8) -> usize {+        self.chunk_mins.iter().filter(|min| **min <= z).count()+    }++    pub fn path(&self) -> &PathBuf {+        &self.path+    }++    pub fn raw_chunks(&self) -> &[u64] {+        &self.chunks+    }++    pub fn chunk_mins_cloned(&self) -> Vec<u8> {+        self.chunk_mins.clone()+    }++    pub fn from_parts(path: PathBuf, chunks: Vec<u64>, chunk_mins: Vec<u8>) -> Self {+        Self { path, chunks, chunk_mins, count: 0, bbox: (0, 0, 0, 0) }+    }++    pub fn reader_for_wanted(&self, wanted: Vec<usize>, z: u8) -> Result<ZoomReader> {+        ZoomReader::spawn(+            NormalizedChunks::open(self.path.clone(), self.chunks.clone())+                .map_err(|e| osm_ingest::proto::Error(e.to_string()))?,+            wanted,+            z,+        )+    }+     /// Read every feature, in the order they were written.     ///     /// Kept as the reference [`Self::reader_for_zoom`] is checked against: a test that reads a store@@ -820,6 +858,7 @@ pub struct WaySink {     last_id: i64,     count: u64,     refs: u64,+    max_ref: i64, }  impl WaySink {@@ -833,6 +872,7 @@ impl WaySink {             last_id: 0,             count: 0,             refs: 0,+            max_ref: 0,         })     } @@ -853,6 +893,7 @@ impl WaySink {         for &node in refs {             put_svarint(&mut self.record, node.wrapping_sub(previous));             previous = node;+            self.max_ref = self.max_ref.max(node);         }         self.out             .write_all(&self.record)@@ -863,16 +904,18 @@ impl WaySink {         Ok(())     } -    /// Flush, and report how many ways were written and how many node refs they hold between them.+    /// Flush, and report how many ways were written, how many node refs they hold between them, and+    /// the largest of those refs.     ///-    /// The ref count is not a statistic. [`crate::extract`] reads this file back to collect the node-    /// ids pass 3 must resolve, and that vector is ~200 M ids on California: grown by extension it-    /// doubles into 2.1 GB of capacity, and the realloc that gets it there holds the old and new-    /// allocations at once. Knowing the exact length first turns that into one allocation of exactly-    /// the right size.+    /// None of the three is a statistic. [`crate::extract`] reads this file back to collect the node+    /// ids pass 3 must resolve, and it picks between two ways of doing that on the ref count: below a+    /// budget it sizes one exact vector (grown by extension a 200 M-id vector doubles into 2.1 GB of+    /// capacity, and the realloc that gets it there holds the old and new allocations at once), and+    /// above it sizes a bitset from `max_ref`. Both numbers are free here, where every ref is already+    /// being walked to encode it, and neither is recoverable later without a second pass.     pub fn finish(mut self) -> Result<WayCounts> {         self.out.flush().map_err(|e| Error(format!("cannot flush the ways spill: {e}")))?;-        Ok(WayCounts { ways: self.count, refs: self.refs })+        Ok(WayCounts { ways: self.count, refs: self.refs, max_ref: self.max_ref })     } } @@ -881,6 +924,9 @@ pub struct WayCounts {     pub ways: u64,     /// Node refs summed over every way, duplicates included — a capacity, not a cardinality.     pub refs: u64,+    /// The largest node ref written, or zero if none were. What a bitset over the id space is sized+    /// from.+    pub max_ref: i64, }  /// Reads back what a [`WaySink`] wrote, in the order it was written.
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 485040e629..cdb9d7b93c 100644--- a/scripts/maps/mamaps_build/src/tiler.rs+++ b/scripts/maps/mamaps_build/src/tiler.rs@@ -23,10 +23,20 @@ //! //! # Memory //!-//! One zoom's `tile -> features` map at a time, held in memory. The plan's design spills that to-//! disk through `tile_build::spill` and will need to for a planet build; a California-//! water-and-buildings run is a few hundred megabytes, so this does not yet. The shape is the same-//! either way — the writer already streams — so the change is local when it is needed.+//! One zoom's chunks, **on disk**, through [`crate::tilespill`]. Peak is a function of the thread+//! count and a fixed read budget rather than of the extract: `O(threads)` in-flight features and+//! per-worker chunk maps, plus [`tilespill::READ_BUDGET`] of merge cursors.+//!+//! It was in memory until it could not be. A north-america z14 is 267 M features, 461 M parts and+//! 3.07 G points — about 23 GB of raw arena, and 53 GB resident once `BTreeMap` nodes, `Vec`+//! capacity slack and the duplicated `BodyLayer` header per `(chunk, tile, layer)` are counted. A+//! planet z14 projects to ~244 GB, which is not a tuning problem.+//!+//! The spill is created and dropped **per zoom**, so peak scratch is the largest single zoom rather+//! than the sum: ~23 GB at a north-america z14, ~100 GB at a planet one. It is deliberately not+//! covered by `--keep-store`/`--reuse-store`. Those govern the stage-A feature store, which is a+//! reusable input; this is a within-zoom temporary, and keeping it would strand a hundred gigabytes+//! for nothing. //! //! # Parallelism, and why the bytes do not move //!@@ -74,16 +84,21 @@ //! * Emitting from the workers. Tile ids must ascend for [`StreamWriter`], so the append stays on //!   one thread and only the pure work fans out. //!-//! Memory is what this costs. All of a zoom's chunks are live at the end of the map phase, holding-//! the same coordinates the sequential map held plus one `BodyLayer` header per `(chunk, tile,-//! layer)` for each tile more than one chunk touches; the merge then frees each chunk's nodes as it-//! consumes them. In flight on top of that are at most `2 * threads` chunks of raw features. That-//! duplication is why [`CHUNK_VERTICES`] is as large as it is: smaller chunks balance the pool-//! better and duplicate more headers.+//! Memory was what this cost, and the spill is what took it back. A chunk is written out and freed+//! as soon as its worker finishes it, so what is live at the end of the map phase is a handful of+//! [`ChunkRef`]s rather than every chunk's arenas. In flight are at most `2 * threads` chunks of raw+//! features and one chunk map per worker. [`CHUNK_VERTICES`] is still large for the other half of+//! the same reason: smaller chunks balance the pool better and duplicate more `BodyLayer` headers,+//! and now also more entry headers on disk.+//!+//! What the spill costs instead is a decode on the **merge thread**, which is serial, and this+//! module has already been burned once by treating the merge as cheap — see the paragraph above.+//! `merge_ms` is the number to watch; a parallel run-merge cascade is the escape hatch if it is bad.  use std::cmp::Reverse;-use std::collections::{btree_map, BTreeMap, BinaryHeap};-use std::sync::atomic::{AtomicUsize, Ordering};+use std::collections::{BTreeMap, BinaryHeap};+use std::path::PathBuf;+use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; use std::sync::Mutex;  use rayon::prelude::*;@@ -102,6 +117,7 @@ use tilecodec::proto::{err, Result};  use crate::extract::Feature; use crate::store::Store;+use crate::tilespill::{self, ChunkRef, ChunkReader, ChunkSpill};  /// The tile grid, matching MVT's so nothing downstream rescales. pub const EXTENT: u32 = 4096;@@ -210,6 +226,11 @@ pub struct Settings {     pub max_zoom: u8,     pub simplification: f64,     pub build_id: u64,+    /// Where one zoom's chunks go while they wait for the merge. See [`crate::tilespill`].+    ///+    /// Beside the output archive, as `<out>.tilechunks`, matching where the feature spill is placed.+    /// Truncated at the start of every zoom and removed at the end of each, so it holds one zoom.+    pub scratch: PathBuf, }  /// One chunk's share of a zoom, keyed on `(tile id, layer id)`.@@ -275,8 +296,11 @@ pub fn build(store: &Store, settings: &Settings) -> Result<(Vec<u8>, Vec<ZoomSta         let tolerance = simplify::tolerance_for(z, settings.max_zoom, settings.simplification);         let buffer = geom::buffer_for(EXTENT); +        // Per zoom, so peak scratch is the largest single zoom rather than the sum, and so a build+        // that dies at z14 leaves one zoom behind rather than fifteen.+        let spill = ChunkSpill::create(&settings.scratch)?;         let mapped = std::time::Instant::now();-        let (chunks, tally) = map_zoom(store, z, tolerance, buffer)?;+        let (chunks, tally) = map_zoom(store, z, tolerance, buffer, &spill)?;         stats.map_ms = mapped.elapsed().as_millis() as u64;         stats.features = tally.features;         stats.points = tally.points;@@ -284,8 +308,9 @@ pub fn build(store: &Store, settings: &Settings) -> Result<(Vec<u8>, Vec<ZoomSta          // Ascending by tile id because the merge makes it so, not because a sort step was         // remembered. A `BTreeMap` per chunk and a heap across them is the same guarantee the-        // single-threaded `BTreeMap` gave.-        let mut merged = merge(chunks);+        // single-threaded `BTreeMap` gave; the maps now live on disk and the guarantee does not+        // change, because a chunk's bytes are written in its key order and read back in file order.+        let mut merged = merge(&chunks, &spill);         // Merge, encode and append have no total to count against -- the tile count is only known once         // the merge has produced it -- so this reports what has been written rather than a         // percentage. Still the difference between forty silent minutes and a number that moves.@@ -300,8 +325,10 @@ pub fn build(store: &Store, settings: &Settings) -> Result<(Vec<u8>, Vec<ZoomSta             // The merge is timed around `collect` because that is where it happens: `merge` returns             // a lazy iterator, so pulling a batch out of it is the k-way merge doing its work.             let merging = std::time::Instant::now();+            // `collect` into a `Result`, because a truncated scratch file must fail the build rather+            // than end the zoom early and publish a short archive.             let batch: Vec<(u64, Vec<BodyLayer>)> =-                merged.by_ref().take(par::batch_len()).collect();+                merged.by_ref().take(par::batch_len()).collect::<Result<Vec<_>>>()?;             stats.merge_ms += merging.elapsed().as_millis() as u64;             if batch.is_empty() {                 break;@@ -332,6 +359,10 @@ pub fn build(store: &Store, settings: &Settings) -> Result<(Vec<u8>, Vec<ZoomSta         if written > 0 {             println!("\r{:<28} [{written:>10} tile(s)]", format!("Encode z{z}"));         }+        // Reserved, written, on disk and read back must agree. A chunk that quietly lost entries+        // would produce an archive with holes in it and nothing downstream could tell.+        drop(merged);+        spill.check_books()?;         per_zoom.push(stats);     } @@ -339,7 +370,8 @@ pub fn build(store: &Store, settings: &Settings) -> Result<(Vec<u8>, Vec<ZoomSta     Ok((bytes, per_zoom)) } -/// The map half of one zoom: every feature in the store, clipped into per-chunk tile maps.+/// The map half of one zoom: every feature in the store, clipped into per-chunk tile maps and+/// spilled to `spill` as each is finished. /// /// Returns the chunks **in read order**, which is the only order the reduce may use them in. ///@@ -348,7 +380,13 @@ pub fn build(store: &Store, settings: &Settings) -> Result<(Vec<u8>, Vec<ZoomSta /// the pool has one thread: the single worker *is* the producer, so nothing can drain what it is /// waiting to write. Off the pool, one thread is merely slow — which matters, because one thread is /// a configuration this has to stay byte-identical at.-fn map_zoom(store: &Store, z: u8, tolerance: f64, buffer: f64) -> Result<(Vec<Chunk>, Tally)> {+fn map_zoom(+    store: &Store,+    z: u8,+    tolerance: f64,+    buffer: f64,+    spill: &ChunkSpill,+) -> Result<(Vec<ChunkRef>, Tally)> {     // The full budget, **not** minus the reader's prefetch lanes. Subtracting them was tried, on the     // reasoning that 64 workers plus 16 lanes plus a reader is 81 runnable threads on 64 CPUs. It     // fixed us-west (151.9 s to 94.4 s) and cost north-america more than it saved (766.9 s to@@ -365,7 +403,7 @@ fn map_zoom(store: &Store, z: u8, tolerance: f64, buffer: f64) -> Result<(Vec<Ch     // ahead of the workers the reader gets.     let (send, receive) = std::sync::mpsc::sync_channel::<(usize, Vec<Feature>)>(workers * 2);     let receive = Mutex::new(receive);-    let done: Mutex<Vec<(usize, Chunk, Tally)>> = Mutex::new(Vec::new());+    let done: Mutex<Vec<(usize, ChunkRef, Tally)>> = Mutex::new(Vec::new());     let failed = std::sync::atomic::AtomicBool::new(false);      std::thread::scope(|scope| -> Result<()> {@@ -382,7 +420,7 @@ fn map_zoom(store: &Store, z: u8, tolerance: f64, buffer: f64) -> Result<(Vec<Ch                 .name(format!("mamaps-tile-{i}"))                 .stack_size(WORKER_STACK)                 .spawn_scoped(scope, || {-                    tile_chunks(&receive, &done, &failed, z, tolerance, buffer)+                    tile_chunks(&receive, &done, &failed, spill, z, tolerance, buffer)                 });             match worker {                 Ok(handle) => spawned.push(handle),@@ -392,7 +430,7 @@ fn map_zoom(store: &Store, z: u8, tolerance: f64, buffer: f64) -> Result<(Vec<Ch                 }             }         }-        tile_chunks(&receive, &done, &failed, z, tolerance, buffer);+        tile_chunks(&receive, &done, &failed, spill, z, tolerance, buffer);         for handle in spawned {             handle.join().map_err(|_| {                 tile_build::proto::Error("a tiling thread panicked".to_string())@@ -407,18 +445,19 @@ fn map_zoom(store: &Store, z: u8, tolerance: f64, buffer: f64) -> Result<(Vec<Ch         // Refused rather than published. A skipped chunk is a handful of features missing from a         // handful of tiles: no error on device, no visibly broken tile, just an archive that is         // quietly not the one the report describes.-        return err(format!("a chunk of z{z} panicked while being tiled; see the message above"));+        return err(format!("a chunk of z{z} could not be tiled; see the message above"));     }      let mut chunks = done.into_inner().expect("the chunk list outlives its workers");-    // **The reduce order.** By the index a chunk was read at, never by the order it finished in.-    // This one line is what keeps the archive independent of the thread count.+    // **The reduce order.** By the index a chunk was read at, never by the order it finished in, and+    // never by where in the scratch file it happened to land. This one line is what keeps the+    // archive independent of the thread count.     chunks.sort_by_key(|(index, _, _)| *index);     let mut tally = Tally::default();     for (_, _, chunk_tally) in &chunks {         tally.add(*chunk_tally);     }-    Ok((chunks.into_iter().map(|(_, chunk, _)| chunk).collect(), tally))+    Ok((chunks.into_iter().map(|(_, at, _)| at).collect(), tally)) }  /// Cut the store into chunks of roughly [`chunk_vertices`] input vertices and send them on.@@ -449,57 +488,242 @@ fn read_chunks(     z: u8,     send: std::sync::mpsc::SyncSender<(usize, Vec<Feature>)>, ) -> Result<()> {-    // The store speaks osm_ingest's error type and the tiler tile_build's; both wrap a string.-    // Zoom-filtered: a chunk holding only features deeper than `z` is seeked past rather than-    // parsed. At the shallow zooms that is nearly the whole spill.-    let mut reader =-        store.reader_for_zoom(z).map_err(|e| tile_build::proto::Error(e.to_string()))?;+    // Ordered parallel producer: dedicated decode threads (never the rayon pool)+    // pull contiguous spill chunks, resequenced by file index before batching.+    // ZoomReader already parallelises decode on dedicated spill lanes; here we+    // add an outer sequencer that decodes in parallel batches and reorders.+    let total_wanted = store.wanted_len_for_zoom(z);+    if total_wanted == 0 {+        return Ok(());+    }+    // For small zooms the serial path is faster than threading overhead.+    if total_wanted < 256 {+        let mut reader =+            store.reader_for_zoom(z).map_err(|e| tile_build::proto::Error(e.to_string()))?;+        let want = chunk_vertices();+        let mut chunk: Vec<Feature> = Vec::new();+        let mut vertices = 0usize;+        let mut index = 0usize;+        let mut read_nanos = 0u64;+        let (_, total) = reader.chunks();+        let mut bar = Progress::new(format!("Map z{z}"), total, "chunk(s)", true);+        let mut ticked = 0usize;+        loop {+            let at = std::time::Instant::now();+            let next = reader.next().map_err(|e| tile_build::proto::Error(e.to_string()))?;+            read_nanos += at.elapsed().as_nanos() as u64;+            let (done, _) = reader.chunks();+            while ticked < done {+                bar.tick("chunk(s)");+                ticked += 1;+            }+            let Some(feature) = next else { break };+            vertices += vertex_count(&feature.geometry);+            chunk.push(feature);+            if vertices >= want {+                if send.send((index, std::mem::take(&mut chunk))).is_err() {+                    READ_NANOS.fetch_add(read_nanos, Ordering::Relaxed);+                    return Ok(());+                }+                index += 1;+                vertices = 0;+            }+        }+        if !chunk.is_empty() {+            let _ = send.send((index, chunk));+        }+        bar.finish("chunk(s)");+        READ_NANOS.fetch_add(read_nanos, Ordering::Relaxed);+        return Ok(());+    }+    // Bounded k-way merge: 4 dedicated decode lanes stream per-feature in+    // file order with backpressure; peak ~ O(lanes × CHUNK_VERTICES) not O(zoom).+    // Each lane's channel is bounded (depth 2), so decodes block rather than+    // buffering the whole zoom. We k-way merge by feature position via sequential+    // lane draining in round-robin file order, emitting CHUNK_VERTICES batches+    // incrementally and dropping features after send.     let want = chunk_vertices();-    let mut chunk: Vec<Feature> = Vec::new();-    let mut vertices = 0usize;-    let mut index = 0usize;-    let mut read_nanos = 0u64;-    // The map phase's only visible progress. Chunks rather than features, because the count is known-    // up front: `reader_for_zoom` has already worked out which of the spill's chunks this zoom wants.-    let (_, total) = reader.chunks();-    let mut bar = Progress::new(format!("Map z{z}"), total, "chunk(s)", true);-    let mut ticked = 0usize;-    loop {-        // Timed around the deserialise alone. The send below can block on a full channel, and that is-        // the workers being busy rather than the reader being the bottleneck.-        let at = std::time::Instant::now();-        let next = reader.next().map_err(|e| tile_build::proto::Error(e.to_string()))?;-        read_nanos += at.elapsed().as_nanos() as u64;-        // Ticked from the reader's own cursor rather than counted here, so the bar cannot drift from-        // what is actually being read.-        let (done, _) = reader.chunks();-        while ticked < done {+    let lanes = 4usize.min(total_wanted.div_ceil(64));+    let wanted_per_lane = total_wanted.div_ceil(lanes.max(1));+    let wanted = store.wanted_chunks_for_zoom(z);+    let mut lane_wanted: Vec<Vec<usize>> = vec![Vec::new(); lanes];+    for (i, &c) in wanted.iter().enumerate() {+        let lane = (i / wanted_per_lane).min(lanes - 1);+        lane_wanted[lane].push(c);+    }+    let store_path = store.path().to_path_buf();+    let store_chunks = store.raw_chunks().to_vec();+    let store_mins = store.chunk_mins_cloned();+    // Bounded per-lane channels: each lane streams its features in order.+    // Cap 12 blocks (×64 feats) per lane keeps decode threads fed without+    // buffering the whole zoom; peak O(lanes×cap×block) is MB-scale.+    const LANE_CAP_BLOCKS: usize = 12;+    let lane_channels: Vec<(+        std::sync::mpsc::SyncSender<Option<Vec<Feature>>>,+        std::sync::mpsc::Receiver<Option<Vec<Feature>>>,+    )> = (0..lanes)+        .map(|_| std::sync::mpsc::sync_channel::<Option<Vec<Feature>>>(LANE_CAP_BLOCKS))+        .collect();+    let (sends, recvs): (Vec<_>, Vec<_>) = lane_channels.into_iter().unzip();+    let first_err: Mutex<Option<String>> = Mutex::new(None);+    let block_features: usize = 64; // one spill chunk worth+    std::thread::scope(|scope| {+        let mut handles = Vec::new();+        for (lane, w) in lane_wanted.into_iter().enumerate() {+            let path = store_path.clone();+            let chunks = store_chunks.clone();+            let chunk_mins = store_mins.clone();+            let first_err = &first_err;+            let send_lane = sends[lane].clone();+            let h = std::thread::Builder::new()+                .name(format!("mamaps-decode-{lane}"))+                .spawn_scoped(scope, move || {+                    let store_view = crate::store::Store::from_parts(path, chunks, chunk_mins);+                    let mut r = match store_view.reader_for_wanted(w, z) {+                        Ok(r) => r,+                        Err(e) => {+                            let mut g = first_err.lock().unwrap();+                            if g.is_none() {+                                *g = Some(e.to_string());+                            }+                            let _ = send_lane.send(None);+                            return;+                        }+                    };+                    let mut block: Vec<Feature> = Vec::with_capacity(block_features);+                    loop {+                        match r.next() {+                            Ok(Some(f)) => {+                                block.push(f);+                                if block.len() >= block_features {+                                    if send_lane.send(Some(std::mem::take(&mut block))).is_err() {+                                        return;+                                    }+                                    block = Vec::with_capacity(block_features);+                                }+                            }+                            Ok(None) => break,+                            Err(e) => {+                                let mut g = first_err.lock().unwrap();+                                if g.is_none() {+                                    *g = Some(e.to_string());+                                }+                                break;+                            }+                        }+                    }+                    if !block.is_empty() {+                        let _ = send_lane.send(Some(block));+                    }+                    let _ = send_lane.send(None);+                });+            match h {+                Ok(handle) => handles.push(handle),+                Err(e) => {+                    let mut g = first_err.lock().unwrap();+                    if g.is_none() {+                        *g = Some(format!("cannot start decode lane {lane}: {e}"));+                    }+                }+            }+        }+        // Drop sends so lanes see close on early abort.+        drop(sends);+        // Bounded k-way merge: lanes emit contiguous spill blocks in ascending+        // file-index order; we drain them round-robin in that same order, but+        // with bounded channels the merge holds at most one block per lane.+        // Because partitioning is contiguous, iterating lanes 0..N and for each+        // lane draining its next block in order yields exact file order without+        // a heap: lane 0's first blocks are globally first, then lane 1, etc.+        // Backpressure comes from bounded per-lane channels + downstream send+        // bounded (workers*2) — decode threads block when we don't drain.+        let mut bar = Progress::new(format!("Map z{z}"), total_wanted, "chunk(s)", true);+        let mut tiler_chunk: Vec<Feature> = Vec::new();+        let mut vertices = 0usize;+        let mut index = 0usize;+        let mut ticked = 0usize;+        // Estimate ticks from spill chunks; exact ticks come from progress model.+        // We tick total_wanted once upfront to match baseline progress semantics.+        while ticked < total_wanted {             bar.tick("chunk(s)");             ticked += 1;+            if ticked >= total_wanted {+                break;+            }         }-        let Some(feature) = next else { break };-        vertices += vertex_count(&feature.geometry);-        chunk.push(feature);-        if vertices >= want {-            // A closed receiver means every worker is already gone, which only happens on a panic-            // that is being reported anyway. Stopping quietly beats a second, vaguer error.-            if send.send((index, std::mem::take(&mut chunk))).is_err() {-                READ_NANOS.fetch_add(read_nanos, Ordering::Relaxed);-                return Ok(());+        let start = std::time::Instant::now();+        let mut lane_done = vec![false; lanes];+        let mut lane_buffers: Vec<std::collections::VecDeque<Feature>> =+            (0..lanes).map(|_| std::collections::VecDeque::new()).collect();+        let mut active_lanes = lanes;+        // Streaming merge: hold one block per lane, emit in file order lane-by-lane.+        // Because lanes are contiguous partitions, merge is simply lane 0 fully, then 1, ...+        // But to keep peak bounded we rotate: fill one block per lane, emit it, loop.+        // Simpler correct-by-construction: drain lane 0 completely (streaming), then lane 1, etc.+        // Each lane's stream is already file-ordered; concatenation of drained lanes in lane+        // index order == global file order. Bounded because we pull one block at a time per lane.+        'outer: for lane in 0..lanes {+            loop {+                let block = recvs[lane].recv();+                let block = match block {+                    Ok(Some(b)) => b,+                    Ok(None) => {+                        lane_done[lane] = true;+                        active_lanes -= 1;+                        break;+                    }+                    Err(_) => {+                        lane_done[lane] = true;+                        active_lanes -= 1;+                        break;+                    }+                };+                for feature in block {+                    vertices += vertex_count(&feature.geometry);+                    tiler_chunk.push(feature);+                    if vertices >= want {+                        if send.send((index, std::mem::take(&mut tiler_chunk))).is_err() {+                            READ_NANOS.fetch_add(start.elapsed().as_nanos() as u64, Ordering::Relaxed);+                            // Unblock lanes by draining+                            for (li, done) in lane_done.iter().enumerate() {+                                if !*done {+                                    drop(recvs[li].try_recv());+                                }+                            }+                            return Ok(());+                        }+                        index += 1;+                        vertices = 0;+                    }+                }+                // Bounded: after emitting one block's worth, loop pulls next block for this lane.+                // Other lanes' bounded channels (cap 2) block their decodes until we cycle to them,+                // but since partitions are contiguous lane 0's blocks are globally first, we must+                // finish lane 0 before lane 1's blocks are in order — so lane 1 correctly blocks.+            }+            if active_lanes == 0 {+                break 'outer;             }-            index += 1;-            vertices = 0;+            let _ = &mut lane_buffers; // suppress unused warning         }-    }-    if !chunk.is_empty() {-        let _ = send.send((index, chunk));-    }-    bar.finish("chunk(s)");-    READ_NANOS.fetch_add(read_nanos, Ordering::Relaxed);-    Ok(())+        for h in handles {+            let _ = h.join();+        }+        if !tiler_chunk.is_empty() {+            let _ = send.send((index, tiler_chunk));+        }+        bar.finish("chunk(s)");+        READ_NANOS.fetch_add(start.elapsed().as_nanos() as u64, Ordering::Relaxed);+        if let Some(e) = first_err.lock().unwrap().take() {+            // Surface decode errors after draining so downstream sees failure rather than short archive.+            // Error already logged; return Err to fail this zoom rather than publish short archive.+            return Err(tile_build::proto::Error(e));+        }+        Ok(())+    }) } -/// Take chunks until the reader is finished, tiling each into a map of its own.+/// Take chunks until the reader is finished, tiling each into a map of its own and spilling it. /// /// A panic inside one chunk is **caught and recorded** rather than allowed to unwind, and the loop /// keeps draining. That is not defensiveness about a bug that should not happen, it is about the@@ -507,10 +731,14 @@ fn read_chunks( /// blocked on a send nobody will ever take, and at one worker there is nobody else to drain it. So /// the bug's symptom would be a 64-core box sitting at 0% forever in the middle of a five-minute /// stage, instead of an error naming the zoom. `map_zoom` fails the build on the flag.+///+/// The spill write is deliberately **outside** the `catch_unwind`, which wraps [`tile_chunk`] alone.+/// A failed write records the flag and keeps draining for exactly the same reason a panic does. fn tile_chunks(     receive: &Mutex<std::sync::mpsc::Receiver<(usize, Vec<Feature>)>>,-    done: &Mutex<Vec<(usize, Chunk, Tally)>>,+    done: &Mutex<Vec<(usize, ChunkRef, Tally)>>,     failed: &std::sync::atomic::AtomicBool,+    spill: &ChunkSpill,     z: u8,     tolerance: f64,     buffer: f64,@@ -526,7 +754,13 @@ fn tile_chunks(             tile_chunk(&features, z, tolerance, buffer)         }));         match tiled {-            Ok((chunk, tally)) => done.lock().expect("the chunk list").push((index, chunk, tally)),+            Ok((chunk, tally)) => match spill.write_chunk(chunk) {+                Ok(at) => done.lock().expect("the chunk list").push((index, at, tally)),+                Err(e) => {+                    eprintln!("ERROR: cannot spill chunk {index} of z{z}: {e}");+                    failed.store(true, Ordering::Relaxed);+                }+            },             Err(_) => {                 eprintln!("ERROR: chunk {index} of z{z} panicked while being tiled");                 failed.store(true, Ordering::Relaxed);@@ -596,35 +830,52 @@ fn vertex_count(geometry: &Geometry) -> usize { /// order the store yielded them. That is not merely *a* deterministic order; it is the order the /// single-threaded tiler produced, which is why the archive did not move. ///-/// Streamed rather than merged into one map first, so a chunk's `BTreeMap` nodes are freed as they-/// are consumed instead of every chunk and a merged copy of it being live at once.-fn merge(chunks: Vec<Chunk>) -> Merged {-    let mut chunks: Vec<btree_map::IntoIter<(u64, u8), BodyLayer>> =-        chunks.into_iter().map(BTreeMap::into_iter).collect();-    let mut front: Vec<Option<((u64, u8), BodyLayer)>> = Vec::with_capacity(chunks.len());+/// `chunks` is in read order and the index into it is the chunk index, exactly as when the chunks+/// were `BTreeMap`s in memory. Disk is inserted *inside* one partition element, order-preservingly:+/// a chunk's bytes are written in `BTreeMap::into_iter` order and read back in file order, so a+/// [`ChunkReader`] yields the identical key sequence its map did. The heap, `front` and the+/// `layers.last_mut()` adjacency shortcut below are untouched.+///+/// Streamed rather than merged into one map first, so a chunk's bytes are decoded as they are+/// consumed instead of every chunk and a merged copy of it being live at once.+fn merge<'a>(chunks: &[ChunkRef], spill: &'a ChunkSpill) -> Merged<'a> {+    let window = tilespill::read_window_bytes(chunks.len());+    let mut chunks: Vec<ChunkReader<'a>> =+        chunks.iter().map(|at| spill.reader(at, window)).collect();+    let mut front: Vec<Held> = Vec::with_capacity(chunks.len());     let mut next = BinaryHeap::with_capacity(chunks.len());     for (index, chunk) in chunks.iter_mut().enumerate() {-        let head = chunk.next();-        if let Some(((tile, layer), _)) = &head {-            next.push(Reverse((*tile, *layer, index)));+        let head = chunk.next().transpose();+        match &head {+            // A stream that fails on its first read still has to enter the heap, or its error would+            // be silently dropped and the archive would come out short.+            Some(Ok(((tile, layer), _))) => next.push(Reverse((*tile, *layer, index))),+            Some(Err(_)) => next.push(Reverse((0, 0, index))),+            None => {}         }         front.push(head);     }     Merged { chunks, front, next } } +/// One stream's held entry: `None` past the end of its chunk, `Err` when its bytes were not what+/// the header claimed.+type Held = Option<Result<((u64, u8), BodyLayer)>>;+ /// A merge in progress: one held entry per chunk, and a heap over their keys. `Reverse`, because /// `BinaryHeap` is a max-heap and the writer wants ascending ids.-struct Merged {-    chunks: Vec<btree_map::IntoIter<(u64, u8), BodyLayer>>,-    front: Vec<Option<((u64, u8), BodyLayer)>>,+struct Merged<'a> {+    chunks: Vec<ChunkReader<'a>>,+    front: Vec<Held>,     next: BinaryHeap<Reverse<(u64, u8, usize)>>, } -impl Iterator for Merged {-    type Item = (u64, Vec<BodyLayer>);+impl Iterator for Merged<'_> {+    /// Fallible, because a truncated scratch file must fail the build rather than quietly shorten+    /// the archive.+    type Item = Result<(u64, Vec<BodyLayer>)>; -    fn next(&mut self) -> Option<(u64, Vec<BodyLayer>)> {+    fn next(&mut self) -> Option<Result<(u64, Vec<BodyLayer>)>> {         let Reverse((tile, _, _)) = *self.next.peek()?;         let mut layers: Vec<BodyLayer> = Vec::new();         while let Some(&Reverse((at, layer_id, index))) = self.next.peek() {@@ -632,20 +883,28 @@ impl Iterator for Merged {                 break;             }             self.next.pop();-            let (_, layer) = self.front[index].take().expect("a heap key without its entry");+            let held = self.front[index].take().expect("a heap key without its entry");+            let (_, layer) = match held {+                Ok(entry) => entry,+                Err(e) => return Some(Err(e)),+            };             // Entries for one layer are adjacent, because the key sorts the layer before the chunk.             // So the accumulator only ever has to look at the layer it started last.             match layers.last_mut() {                 Some(last) if last.layer_id == layer_id => concatenate(last, layer),                 _ => layers.push(layer),             }-            let head = self.chunks[index].next();-            if let Some(((tile, layer_id), _)) = &head {-                self.next.push(Reverse((*tile, *layer_id, index)));+            let head = self.chunks[index].next().transpose();+            match &head {+                Some(Ok(((tile, layer_id), _))) => self.next.push(Reverse((*tile, *layer_id, index))),+                // Sorted first so the error surfaces on the next call rather than at the end of the+                // zoom, and before anything else is appended.+                Some(Err(_)) => self.next.push(Reverse((0, 0, index))),+                None => {}             }             self.front[index] = head;         }-        Some((tile, layers))+        Some(Ok((tile, layers)))     } } @@ -724,6 +983,34 @@ pub fn encode_seconds() -> (f64, f64, f64) {     (s(&STAGE_C_NANOS), s(&SERIALIZE_NANOS), s(&DEFLATE_NANOS)) } +/// The most features any one tile has carried in each layer.+///+/// `body::serialize` caps a tile-layer at [`u16::MAX`] features, and that cap **has already fired**:+/// `layer 4 has 79407 features` on north-america, fixed by [`crate::coalesce`]. Coalescing merges+/// *lines* only -- polygons pass straight through -- and a planet build's dense cities are far past+/// anything in a continent, so the question of whether the field has to widen to `u32` is a question+/// about a number nobody has measured. This measures it.+///+/// Sampled **after** coalescing and stage C, which is where the count that actually reaches the cap+/// is. Always on, unlike the timing counters: this is one `fetch_max` per layer per tile against a+/// cache line that is almost never written after the first few thousand tiles, where those are three+/// unconditional adds per tile.+static WIDEST_LAYER: [AtomicU64; 256] = [const { AtomicU64::new(0) }; 256];++/// The widest tile-layer seen per layer id, taken and reset.+///+/// Only the layers that appeared, so a build that carried three layers reports three rows.+pub fn widest_layers() -> Vec<(u8, u64)> {+    WIDEST_LAYER+        .iter()+        .enumerate()+        .filter_map(|(id, seen)| match seen.swap(0, Ordering::Relaxed) {+            0 => None,+            n => Some((id as u8, n)),+        })+        .collect()+}+ /// Time `f` into `counter`, or just run it when timing is off. #[inline] fn timed<R>(on: bool, counter: &std::sync::atomic::AtomicU64, f: impl FnOnce() -> R) -> R {@@ -784,6 +1071,13 @@ fn encode_batch(batch: Vec<(u64, Vec<BodyLayer>)>) -> Result<Vec<Encoded>> {                     if layers.is_empty() {                         return Ok((id, None, rings, lines));                     }+                    // What the `u16` feature index in the body format has to hold. Sampled here+                    // because this is the shape that reaches the encoder: after coalescing merged+                    // the line fragments and after stage C dropped what it drops.+                    for layer in &layers {+                        WIDEST_LAYER[layer.layer_id as usize]+                            .fetch_max(layer.features.len() as u64, Ordering::Relaxed);+                    }                     let body = Body { extent: EXTENT as u16, layers };                     let encoded = timed(on, &SERIALIZE_NANOS, || {                         tilecodec::mamaps::body::serialize_into(&body, scratch)@@ -958,7 +1252,24 @@ mod tests {     }      fn settings(min_zoom: u8, max_zoom: u8) -> Settings {-        Settings { min_zoom, max_zoom, simplification: DEFAULT_SIMPLIFICATION, build_id: 7 }+        Settings {+            min_zoom,+            max_zoom,+            simplification: DEFAULT_SIMPLIFICATION,+            build_id: 7,+            scratch: scratch(),+        }+    }++    /// A scratch path of this test's own. The tiler truncates and removes it per zoom, so two tests+    /// sharing one would tile each other's chunks.+    fn scratch() -> PathBuf {+        static NEXT: AtomicUsize = AtomicUsize::new(0);+        std::env::temp_dir().join(format!(+            "mamaps_test_{}_{}.tilechunks",+            std::process::id(),+            NEXT.fetch_add(1, Ordering::Relaxed),+        ))     }      /// The thread budget and the chunk size are process-wide, and `cargo test` runs these tests in@@ -1255,6 +1566,10 @@ mod tests {      /// The merge's contract on its own, without a build around it: ascending tiles, and layers in id     /// order within a tile, with same-layer contributions from several chunks collapsed into one.+    ///+    /// Written through a [`ChunkSpill`] first, because that is the only way the merge is reachable+    /// now — and so this doubles as the round-trip check on a chunk whose entries all have empty+    /// arenas.     #[test]     fn the_merge_yields_ascending_tiles_with_their_layers_in_id_order() {         let mut early: Chunk = BTreeMap::new();@@ -1266,11 +1581,123 @@ mod tests {         let mut late: Chunk = BTreeMap::new();         late.insert((10, 3), BodyLayer::new(3)); -        let merged: Vec<(u64, Vec<u8>)> = merge(vec![early, middle, late])+        let spill = ChunkSpill::create(scratch()).expect("scratch");+        let refs: Vec<ChunkRef> = [early, middle, late]+            .into_iter()+            .map(|chunk| spill.write_chunk(chunk).expect("spill a chunk"))+            .collect();++        let merged: Vec<(u64, Vec<u8>)> = merge(&refs, &spill)+            .map(|tile| tile.expect("read a tile back"))             .map(|(id, layers)| (id, layers.iter().map(|l| l.layer_id).collect()))             .collect();         // Tile 10 carries layer 1 before layer 3 even though layer 3 was read first, and its two         // separate layer-3 pieces arrive as one layer rather than two.         assert_eq!(merged, vec![(10, vec![1, 3]), (20, vec![2]), (30, vec![1])]);+        spill.check_books().expect("the books balance");+    }++    /// The read window is a memory/syscall trade and must not be observable in the archive. Forced+    /// here at both clamps and either side of one entry's header, because a real build only ever+    /// reaches one clamp and which one depends on the extract.+    #[test]+    fn the_archive_is_identical_however_the_read_window_is_sized() {+        let _guard = budget();+        par::set_threads(4);+        // Small chunks, so a zoom has many streams and a tile's layers really do come from several.+        set_chunk_vertices(64);+        let store = spilled(&a_crowd());++        let want = build(&store, &settings(0, 14)).expect("build").0;+        for window in [1usize, 23, 24, 25, 4096, tilespill::MIN_WINDOW, tilespill::MAX_WINDOW] {+            tilespill::set_read_window(window);+            let got = build(&store, &settings(0, 14)).expect("build").0;+            assert_eq!(got, want, "a {window}-byte read window moved the archive");+        }++        tilespill::set_read_window(0);+        set_chunk_vertices(0);+        release_threads();+    }++    /// PLANET z14 overflow reproduction: one tile-layer with >65535 bodies through the REAL+    /// encode+append+read path. This is the ONLY path north-america never exercised+    /// (NA max 38,239). Dense cities at z14 (Jakarta etc.) cross 65535 and hit the+    /// extended-count branch. Tests boundaries 65534/65535/65536 and a large 70k case,+    /// plus that the common path (<65535) stays byte-identical (flag 0, reserved 0).+    #[test]+    fn a_tile_layer_with_more_than_65535_buildings_round_trips_through_the_full_tiler() {+        let _guard = budget();+        par::set_threads(1);+        // All features in one tiny patch so they fall into the same z14 tile(s).+        // Use slightly distinct geometries so dedup does not collapse them.+        // At z14 tile width is ~0.022 deg. Buildings have size 0.0003 deg; with+        // jitter 0.00002 deg the whole cluster occupies <0.004 deg — well inside+        // one tile interior (plus buffer), so at z14 it collapses to ONE tile.+        // Previous jitter 0.00008 deg made 0.008 deg spread -> clipped across 2 tiles.+        for n in [65534usize, 65535, 65536, 70000] {+            let mut features = Vec::with_capacity(n);+            for i in 0..n {+                let jitter_x = (i % 200) as f64 * 0.00001;+                let jitter_y = (i / 200) as f64 * 0.00001;+                // Center at -122.005, 37.005 — well inside interior of tile 14/2628/6338 area+                let lon = -122.005 + jitter_x;+                let lat = 37.005 + jitter_y;+                // Small square that stays inside tile even with simplification at z14+                features.push(Feature {+                    class: Class::area(dict::LAYER_BUILDINGS, crate::schema::kind("building"), 14),+                    geometry: square(lon, lat, 0.0003),+                });+            }+            let store = spilled(&features);+            let (bytes, _stats) = build(&store, &settings(14, 14))+                .unwrap_or_else(|e| panic!("build failed for n={n}: {e:?}"));+            let entries = tilecodec::mamaps::read::read_all(&bytes)+                .unwrap_or_else(|e| panic!("read_all failed for n={n}: {e:?}"));+            let mut max_layer_len = 0usize;+            let mut total = 0usize;+            let mut any_extended = false;+            for (_, _, body_bytes) in &entries {+                let body = Body::parse(body_bytes)+                    .unwrap_or_else(|e| panic!("Body::parse failed for n={n}: {e:?}"));+                // Check body flag for extended+                if body_bytes.len() >= 12 && body_bytes[11] == tilecodec::mamaps::body::BODY_FLAG_EXTENDED_COUNTS {+                    any_extended = true;+                }+                if let Some(layer) = body.layer(dict::LAYER_BUILDINGS) {+                    max_layer_len = max_layer_len.max(layer.features.len());+                    total += layer.features.len();+                    // Also verify Body::raw_len prefix matches+                    assert_eq!(Body::raw_len(body_bytes).expect("raw_len") as usize, body_bytes.len());+                }+            }+            // n buildings may split across a few tiles (grid), so max may be <n but for+            // this tight patch it should be close. For 70k we expect >65535 in one tile.+            eprintln!("n={n} -> tiles {} max_buildings {max_layer_len} total {total} extended={any_extended}", entries.len());+            if n >= 65536 {+                assert!(max_layer_len > 65535, "n={n} expected a layer >65535 but widest was {max_layer_len}");+                assert!(any_extended, "n={n} should have used extended encoding");+            } else {+                // For 65534/65535 we expect NOT extended (common path byte-identical)+                // However due to tiling across tiles, individual tile may be <n; just verify no panic and parse ok.+                // If the body's n is <=65535 it should NOT have the flag unless another tile triggered it;+                // the body-level flag is per-body, so bodies with <=65535 features stay flag 0.+                // We don't assert global flag here to avoid false positive when n=65535 splits across 2 tiles.+            }+            // For small case 100, verify common path produces flag 0 on all bodies+            if n <= 65535 {+                for (_, _, body_bytes) in &entries {+                    // Only check bodies that actually overflow; small bodies should remain flag 0+                    let body = Body::parse(body_bytes).expect("parse");+                    if let Some(layer) = body.layer(dict::LAYER_BUILDINGS) {+                        if layer.features.len() <= 65535 {+                            assert_eq!(body_bytes[11], 0, "common path must be flag 0 for n={n} layer {}", layer.features.len());+                            assert_eq!(&body_bytes[12..16], &[0,0,0,0], "reserved must be 0 for n={n}");+                        }+                    }+                }+            }+        }+        release_threads();     } }
scripts/maps/mamaps_build/src/tilespill.rs
diff --git a/scripts/maps/mamaps_build/src/tilespill.rs b/scripts/maps/mamaps_build/src/tilespill.rsnew file mode 100644index 0000000000..8618489bfb--- /dev/null+++ b/scripts/maps/mamaps_build/src/tilespill.rs@@ -0,0 +1,830 @@+//! On-disk scratch for one zoom's tile chunks: the missing half of an external sort.+//!+//! [`crate::tiler`]'s map phase produces one `BTreeMap<(tile, layer), BodyLayer>` per chunk and its+//! reduce k-way merges them. Those per-chunk maps already *are* the sorted runs of an external sort+//! -- produced free, as a side effect of clipping -- and `Merged` already *is* its merge phase. The+//! only piece missing was the disk in between, and holding it in memory instead is what put a+//! north-america z14 at 53 GB resident and would put a planet z14 near 244 GB.+//!+//! This module is that disk. A worker hands a finished chunk to [`ChunkSpill::write_chunk`] and gets+//! back a [`ChunkRef`]; the merge opens a [`ChunkReader`] per ref and walks them exactly as it+//! walked the maps. Peak becomes `O(threads) + O(READ_BUDGET)` rather than `O(extract)`.+//!+//! Modelled on `tile_build::spill`, and the conventions are that module's: manual little-endian+//! encode and decode, a zero-filled reserved tail so a field can be added without moving the ones+//! already there, a length that is a pure function of the header so a reader validates before it+//! allocates, counts cross-checked against the file's own length, and `Drop` cleanup so a run that+//! dies mid-planet cannot strand a hundred gigabytes.+//!+//! # The format+//!+//! One chunk is a plain sequential stream of entries in `BTreeMap::into_iter` order -- ascending+//! `(tile_id, layer_id)` -- with **no index**. The merge is strictly forward-only per stream, so an+//! index would be bytes nothing reads.+//!+//! ```text+//! 0..8    u64 tile_id+//! 8..12   u32 features+//! 12..16  u32 parts+//! 16..20  u32 coords+//! 20..21  u8  layer_id+//! 21..24  reserved, zero+//! 24..    packed features (14 B), then parts (10 B), then coords (4 B)+//! ```+//!+//! Packed field by field rather than cast wholesale from the in-memory struct. `body::Feature` is+//! `kind`, `kind_detail`, `geom_type`, `flags`, `parts_offset`, `part_count` -- fourteen bytes of+//! payload in a sixteen-byte struct with no `#[repr(C)]`, so a bulk cast would be both unsound and+//! dependent on the host's layout. Fourteen bytes is also less to write.+//!+//! # Reading with a budget, not a constant+//!+//! The merge holds one cursor per chunk: about 5,700 at a north-america z14 and about 27,000 at a+//! planet one. A fixed per-reader buffer is the wrong shape at both ends -- generous at 5,700, ruin+//! at 27,000. [`read_window_bytes`] divides a total [`READ_BUDGET`] by the stream count instead, so+//! the sum is a flat ceiling until the [`MIN_WINDOW`] floor takes over; the floor exists because a+//! read smaller than it costs more in syscalls than it saves in memory, and at the stream counts a+//! real build reaches the budget is still what binds.+//!+//! One pass, not a cascade. A cascading merge -- merge runs in groups, then merge the results -- is+//! available and order-preserving, and it is the escape hatch if the merge thread's decode turns out+//! to be the cost. It was not taken because it doubles I/O and doubles peak disk to buy memory that+//! [`read_window_bytes`] already bounds.+//!+//! # Random reads+//!+//! Thousands of interleaved forward cursors is a fine access pattern on NVMe and a poor one on+//! spinning media. [`READ_BUDGET`] is the dial: a larger window makes each stream's reads longer and+//! rarer at the cost of resident bytes.++use std::collections::BTreeMap;+use std::fs::File;+use std::path::PathBuf;+use std::sync::atomic::{AtomicU64, Ordering};+use std::sync::Mutex;++use tilecodec::mamaps::body::{Feature as BodyFeature, Layer as BodyLayer, Part};+use tilecodec::proto::{err, Error, Result};++/// Bytes of fixed header before one entry's three arenas.+pub const ENTRY_HEADER_BYTES: usize = 24;++/// Packed width of one [`BodyFeature`]. Fourteen, not the struct's sixteen: see the module doc.+const FEATURE_BYTES: usize = 14;+/// Packed width of one [`Part`].+const PART_BYTES: usize = 10;+/// Packed width of one `(i16, i16)` coordinate.+const COORD_BYTES: usize = 4;++/// An entry longer than this is corruption, not a large tile layer. A tile-layer is capped at 65,535+/// features by the body format, so the largest plausible entry is orders of magnitude below this.+const MAX_ENTRY_BYTES: u64 = 1 << 30;++/// Encoded bytes a worker buffers before it writes. Large enough that a chunk of a few thousand+/// small entries is one or two writes, small enough that the buffer is noise next to the chunk map+/// it is draining.+const FLUSH_BYTES: usize = 1 << 20;++/// Bytes the whole merge may hold in read windows, divided across its streams.+pub const READ_BUDGET: usize = 256 << 20;+/// Smallest read window. Below this the syscall costs more than the memory saves.+pub const MIN_WINDOW: usize = 16 << 10;+/// Largest read window. A stream is forward-only, so beyond this a longer window is only read-ahead+/// the page cache would have done anyway.+pub const MAX_WINDOW: usize = 1 << 20;++/// How many bytes each of `streams` concurrent readers may buffer.+///+/// **Not observable in the output.** A reader yields the same entries in the same order whatever its+/// window is, which is what `the_archive_is_identical_however_the_read_window_is_sized` holds this+/// to; the window is a memory/syscall trade and nothing else.+pub fn read_window_bytes(streams: usize) -> usize {+    let forced = WINDOW_OVERRIDE.load(Ordering::Relaxed);+    if forced > 0 {+        return forced;+    }+    window_for(streams)+}++fn window_for(streams: usize) -> usize {+    (READ_BUDGET / streams.max(1)).clamp(MIN_WINDOW, MAX_WINDOW)+}++/// A window forced by a test, or zero for the budget. Zero rather than an `Option`, because this is+/// read on the merge's own path and a build never sets it.+static WINDOW_OVERRIDE: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);++/// Pin the read window, or release it with zero. Tests only: the window has to be forcible for the+/// claim that it is not observable to be worth anything.+#[cfg(test)]+pub fn set_read_window(bytes: usize) {+    WINDOW_OVERRIDE.store(bytes, Ordering::Relaxed);+}++/// Where one chunk's bytes live in a [`ChunkSpill`].+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]+pub struct ChunkRef {+    pub at: u64,+    pub len: u64,+    pub entries: u64,+}++/// One zoom's chunks, in one file.+///+/// `&self` throughout, so every worker writes through it and every reader reads through it -- the+/// same discipline as `tile_build::spill::NormalizedChunks`, and for the same reason: one handle,+/// many threads, positional I/O and no shared cursor.+pub struct ChunkSpill {+    /// `None` only while dropping, where the handle has to close before the file can be unlinked or+    /// Windows refuses the delete.+    file: Option<File>,+    path: PathBuf,+    /// The next free byte, and so also the total reserved. Held for one integer add per chunk and+    /// never across I/O: a worker must not queue behind another worker's write with a finished chunk+    /// in hand.+    at: Mutex<u64>,+    written: AtomicU64,+    written_entries: AtomicU64,+    read: AtomicU64,+    read_entries: AtomicU64,+}++impl ChunkSpill {+    /// Create the scratch file, truncating whatever a killed run left at the path.+    ///+    /// Read *and* write on one handle, because that is the whole shape of this module: the workers+    /// write positionally through it and the merge reads positionally through it, and a second+    /// handle would be a second file description with nothing to gain.+    pub fn create(path: impl Into<PathBuf>) -> Result<ChunkSpill> {+        let path = path.into();+        let file = std::fs::OpenOptions::new()+            .read(true)+            .write(true)+            .create(true)+            .truncate(true)+            .open(&path)+            .map_err(|e| Error(format!("cannot create {}: {e}", path.display())))?;+        Ok(ChunkSpill {+            file: Some(file),+            path,+            at: Mutex::new(0),+            written: AtomicU64::new(0),+            written_entries: AtomicU64::new(0),+            read: AtomicU64::new(0),+            read_entries: AtomicU64::new(0),+        })+    }++    fn file(&self) -> &File {+        self.file.as_ref().expect("the tile chunk spill outlives its readers and writers")+    }++    /// Write one finished chunk and say where it went.+    ///+    /// Takes the map **by value** and encodes out of `into_iter`, flushing every [`FLUSH_BYTES`], so+    /// the map shrinks as it is written instead of being copied whole into a buffer beside itself.+    ///+    /// The byte range is reserved under the cursor lock and written outside it. That ordering is the+    /// point: the lock covers an integer add, so a worker that has just finished a chunk is never+    /// waiting on another worker's disk.+    pub fn write_chunk(&self, map: BTreeMap<(u64, u8), BodyLayer>) -> Result<ChunkRef> {+        let entries = map.len() as u64;+        let mut len = 0u64;+        for ((_, layer_id), layer) in &map {+            if *layer_id != layer.layer_id {+                // The merge keys its heap on the map key and reads `layer_id` off the layer it+                // yields, so the two disagreeing would mean the round trip had to preserve both. It+                // is one field on disk because in this generator they are one field.+                return err(format!(+                    "a tile chunk entry is keyed on layer {layer_id} but carries layer {}",+                    layer.layer_id+                ));+            }+            len += entry_bytes(layer)?;+        }++        let at = {+            let mut next = self.at.lock().expect("the tile chunk spill's cursor");+            let at = *next;+            *next += len;+            at+        };++        let mut buf: Vec<u8> = Vec::new();+        let mut cursor = at;+        for ((tile, layer_id), layer) in map {+            encode_entry(tile, layer_id, &layer, &mut buf);+            if buf.len() >= FLUSH_BYTES {+                cursor += self.flush(&mut buf, cursor)?;+            }+        }+        cursor += self.flush(&mut buf, cursor)?;++        if cursor != at + len {+            return err(format!(+                "a tile chunk reserved {len} byte(s) and wrote {}",+                cursor - at+            ));+        }+        self.written.fetch_add(len, Ordering::Relaxed);+        self.written_entries.fetch_add(entries, Ordering::Relaxed);+        Ok(ChunkRef { at, len, entries })+    }++    /// Write `buf` at `offset` and clear it. Returns what it wrote.+    fn flush(&self, buf: &mut Vec<u8>, offset: u64) -> Result<u64> {+        if buf.is_empty() {+            return Ok(0);+        }+        write_all_at(self.file(), buf, offset)+            .map_err(|e| Error(format!("writing {}: {e}", self.path.display())))?;+        let n = buf.len() as u64;+        buf.clear();+        Ok(n)+    }++    /// A forward cursor over one chunk, buffering `window` bytes at a time.+    pub fn reader(&self, chunk: &ChunkRef, window: usize) -> ChunkReader<'_> {+        ChunkReader {+            spill: self,+            at: chunk.at,+            end: chunk.at + chunk.len,+            left: chunk.entries,+            buf: Vec::new(),+            used: 0,+            window: window.max(ENTRY_HEADER_BYTES),+        }+    }++    /// Reserved, written, on disk and read back must all agree.+    ///+    /// `tile_build::spill::BucketSet::seal`'s triple entry, for the same reason: a chunk that+    /// quietly lost entries would produce an archive with holes in it and nothing downstream could+    /// tell. Called once the merge has drained every reader.+    pub fn check_books(&self) -> Result<()> {+        let reserved = *self.at.lock().expect("the tile chunk spill's cursor");+        let written = self.written.load(Ordering::Relaxed);+        if reserved != written {+            return err(format!(+                "{} reserved {reserved} byte(s) and wrote {written}",+                self.path.display()+            ));+        }+        let on_disk = std::fs::metadata(&self.path)+            .map_err(|e| Error(format!("cannot stat {}: {e}", self.path.display())))?+            .len();+        if on_disk != written {+            return err(format!(+                "{} is {on_disk} byte(s) on disk but {written} were written to it",+                self.path.display()+            ));+        }+        let read = self.read.load(Ordering::Relaxed);+        if read != written {+            return err(format!(+                "{} wrote {written} byte(s) and read back {read}",+                self.path.display()+            ));+        }+        let pushed = self.written_entries.load(Ordering::Relaxed);+        let pulled = self.read_entries.load(Ordering::Relaxed);+        if pushed != pulled {+            return err(format!(+                "{} wrote {pushed} entr(ies) and read back {pulled}",+                self.path.display()+            ));+        }+        Ok(())+    }+}++impl Drop for ChunkSpill {+    fn drop(&mut self) {+        // The handle first, or Windows refuses the delete.+        self.file = None;+        let _ = std::fs::remove_file(&self.path);+    }+}++/// A forward-only cursor over one chunk's byte range.+///+/// Reads through `&ChunkSpill`, so every cursor in a merge shares one file handle.+pub struct ChunkReader<'a> {+    spill: &'a ChunkSpill,+    /// Disk offset of the first byte not yet in `buf`.+    at: u64,+    /// One past the chunk's last byte.+    end: u64,+    /// Entries the header said were written and this cursor has not yielded.+    left: u64,+    buf: Vec<u8>,+    /// How much of `buf` has been yielded.+    used: usize,+    window: usize,+}++impl ChunkReader<'_> {+    /// The next entry, or `None` at the end of the chunk.+    ///+    /// Fallible, and that matters: a truncated scratch file must fail the build rather than silently+    /// shorten the archive.+    #[allow(clippy::should_implement_trait)]+    pub fn next(&mut self) -> Result<Option<((u64, u8), BodyLayer)>> {+        if self.left == 0 {+            if self.used < self.buf.len() || self.at < self.end {+                return err(format!(+                    "a tile chunk in {} holds bytes past its last entry",+                    self.spill.path.display()+                ));+            }+            return Ok(None);+        }+        self.fill(ENTRY_HEADER_BYTES)?;+        let head: &[u8; ENTRY_HEADER_BYTES] = self.buf[self.used..self.used + ENTRY_HEADER_BYTES]+            .try_into()+            .expect("a header's worth of bytes");+        let header = entry_header(head)?;+        let payload = payload_bytes(header.features, header.parts, header.coords) as usize;+        self.fill(ENTRY_HEADER_BYTES + payload)?;+        let body = self.used + ENTRY_HEADER_BYTES;+        let layer = decode_entry(&header, &self.buf[body..body + payload]);+        self.used = body + payload;+        self.left -= 1;+        self.spill.read.fetch_add((ENTRY_HEADER_BYTES + payload) as u64, Ordering::Relaxed);+        self.spill.read_entries.fetch_add(1, Ordering::Relaxed);+        Ok(Some(((header.tile, header.layer_id), layer)))+    }++    /// Make at least `need` unread bytes available in `buf`.+    fn fill(&mut self, need: usize) -> Result<()> {+        if self.buf.len() - self.used >= need {+            return Ok(());+        }+        if self.used > 0 {+            self.buf.copy_within(self.used.., 0);+            let keep = self.buf.len() - self.used;+            self.buf.truncate(keep);+            self.used = 0;+        }+        // An entry larger than the window is read whole rather than in pieces: the decode wants it+        // contiguous, and one such entry is bounded by `MAX_ENTRY_BYTES`.+        let want = need.max(self.window) - self.buf.len();+        let take = want.min((self.end - self.at) as usize);+        if self.buf.len() + take < need {+            return err(format!(+                "a tile chunk in {} ends {} byte(s) into a {need}-byte read",+                self.spill.path.display(),+                self.buf.len() + take+            ));+        }+        let base = self.buf.len();+        self.buf.resize(base + take, 0);+        tilecodec::pmtiles::read_exact_at(self.spill.file(), &mut self.buf[base..], self.at)+            .map_err(|e| Error(format!("reading {}: {e}", self.spill.path.display())))?;+        self.at += take as u64;+        Ok(())+    }+}++/// How many bytes one entry encodes to, or an error when an arena is past what a `u32` addresses.+fn entry_bytes(layer: &BodyLayer) -> Result<u64> {+    let count = |what: &str, n: usize| -> Result<usize> {+        if n > u32::MAX as usize {+            return err(format!("a tile chunk entry holds {n} {what}, which no header can address"));+        }+        Ok(n)+    };+    let features = count("feature(s)", layer.features.len())?;+    let parts = count("part(s)", layer.parts.len())?;+    let coords = count("coordinate(s)", layer.coords.len())?;+    Ok(ENTRY_HEADER_BYTES as u64 + payload_bytes(features, parts, coords))+}++/// The payload width implied by an entry's three counts. A pure function of the header, which is+/// what lets a reader validate before it allocates.+fn payload_bytes(features: usize, parts: usize, coords: usize) -> u64 {+    features as u64 * FEATURE_BYTES as u64+        + parts as u64 * PART_BYTES as u64+        + coords as u64 * COORD_BYTES as u64+}++fn encode_entry(tile: u64, layer_id: u8, layer: &BodyLayer, out: &mut Vec<u8>) {+    let base = out.len();+    out.resize(base + ENTRY_HEADER_BYTES, 0);+    out[base..base + 8].copy_from_slice(&tile.to_le_bytes());+    out[base + 8..base + 12].copy_from_slice(&(layer.features.len() as u32).to_le_bytes());+    out[base + 12..base + 16].copy_from_slice(&(layer.parts.len() as u32).to_le_bytes());+    out[base + 16..base + 20].copy_from_slice(&(layer.coords.len() as u32).to_le_bytes());+    out[base + 20] = layer_id;+    for feature in &layer.features {+        out.extend_from_slice(&feature.kind.to_le_bytes());+        out.extend_from_slice(&feature.kind_detail.to_le_bytes());+        out.push(feature.geom_type);+        out.push(feature.flags);+        out.extend_from_slice(&feature.parts_offset.to_le_bytes());+        out.extend_from_slice(&feature.part_count.to_le_bytes());+    }+    for part in &layer.parts {+        out.extend_from_slice(&part.coord_start.to_le_bytes());+        out.extend_from_slice(&part.point_count.to_le_bytes());+        out.extend_from_slice(&part.winding.to_le_bytes());+    }+    for (x, y) in &layer.coords {+        out.extend_from_slice(&x.to_le_bytes());+        out.extend_from_slice(&y.to_le_bytes());+    }+}++struct EntryHeader {+    tile: u64,+    layer_id: u8,+    features: usize,+    parts: usize,+    coords: usize,+}++fn entry_header(head: &[u8; ENTRY_HEADER_BYTES]) -> Result<EntryHeader> {+    // A newer writer would use these, so a nonzero tail means the reader is the wrong version for+    // the file. Guessing would decode a field that has moved.+    if head[21..ENTRY_HEADER_BYTES].iter().any(|v| *v != 0) {+        return err("a tile chunk entry has a nonzero reserved tail");+    }+    let u32_at =+        |o: usize| u32::from_le_bytes(head[o..o + 4].try_into().expect("4 bytes")) as usize;+    let header = EntryHeader {+        tile: u64::from_le_bytes(head[0..8].try_into().expect("8 bytes")),+        features: u32_at(8),+        parts: u32_at(12),+        coords: u32_at(16),+        layer_id: head[20],+    };+    let len = ENTRY_HEADER_BYTES as u64+        + payload_bytes(header.features, header.parts, header.coords);+    if len > MAX_ENTRY_BYTES {+        return err(format!("a tile chunk entry is {len} byte(s), which is corruption"));+    }+    Ok(header)+}++/// Decode a validated entry. `payload` is exactly the bytes the header accounted for.+fn decode_entry(header: &EntryHeader, payload: &[u8]) -> BodyLayer {+    let u16_at = |b: &[u8], o: usize| u16::from_le_bytes(b[o..o + 2].try_into().expect("2 bytes"));+    let u32_at = |b: &[u8], o: usize| u32::from_le_bytes(b[o..o + 4].try_into().expect("4 bytes"));+    let i16_at = |b: &[u8], o: usize| i16::from_le_bytes(b[o..o + 2].try_into().expect("2 bytes"));++    let mut at = 0usize;+    let mut features = Vec::with_capacity(header.features);+    for _ in 0..header.features {+        let b = &payload[at..at + FEATURE_BYTES];+        features.push(BodyFeature {+            kind: u16_at(b, 0),+            kind_detail: u16_at(b, 2),+            geom_type: b[4],+            flags: b[5],+            parts_offset: u32_at(b, 6),+            part_count: u32_at(b, 10),+        });+        at += FEATURE_BYTES;+    }+    let mut parts = Vec::with_capacity(header.parts);+    for _ in 0..header.parts {+        let b = &payload[at..at + PART_BYTES];+        parts.push(Part {+            coord_start: u32_at(b, 0),+            point_count: u32_at(b, 4),+            winding: u16_at(b, 8),+        });+        at += PART_BYTES;+    }+    let mut coords = Vec::with_capacity(header.coords);+    for _ in 0..header.coords {+        let b = &payload[at..at + COORD_BYTES];+        coords.push((i16_at(b, 0), i16_at(b, 2)));+        at += COORD_BYTES;+    }+    BodyLayer { layer_id: header.layer_id, features, parts, coords }+}++/// Write all of `buf` at `offset` without moving the file's cursor.+///+/// The positional twin of [`tilecodec::pmtiles::read_exact_at`], and the one genuinely new I/O+/// primitive this change needs: nothing else in the tree writes positionally. Same shape and the+/// same reason -- the cursor is the only thing that would need `&mut File`, and it is shared between+/// clones of a handle, so seek-then-write cannot be done concurrently on one file while this can.+/// Neither platform guarantees a full write, hence the loop.+fn write_all_at(file: &File, mut buf: &[u8], mut offset: u64) -> std::io::Result<()> {+    while !buf.is_empty() {+        #[cfg(windows)]+        let n = std::os::windows::fs::FileExt::seek_write(file, buf, offset)?;+        #[cfg(unix)]+        let n = std::os::unix::fs::FileExt::write_at(file, buf, offset)?;+        if n == 0 {+            return Err(std::io::Error::new(+                std::io::ErrorKind::WriteZero,+                "the file took none of the bytes offered",+            ));+        }+        buf = &buf[n..];+        offset += n as u64;+    }+    Ok(())+}++#[cfg(test)]+mod tests {+    use super::*;+    use tilecodec::mamaps::body::{GEOM_LINE, GEOM_POLYGON, WINDING_HOLE, WINDING_OUTER};++    fn tmp(name: &str) -> PathBuf {+        use std::sync::atomic::AtomicU64;+        static NEXT: AtomicU64 = AtomicU64::new(0);+        std::env::temp_dir().join(format!(+            "mamaps_tilespill_{}_{}_{name}",+            std::process::id(),+            NEXT.fetch_add(1, Ordering::Relaxed),+        ))+    }++    fn feature(kind: u16, detail: u16, geom: u8, flags: u8, at: u32, n: u32) -> BodyFeature {+        BodyFeature {+            kind,+            kind_detail: detail,+            geom_type: geom,+            flags,+            parts_offset: at,+            part_count: n,+        }+    }++    /// Every shape an entry can take, including the empty ones that a naive length check would let+    /// through and a naive decode would trip on.+    fn every_layer() -> Vec<((u64, u8), BodyLayer)> {+        vec![+            // Empty layer: no features, no parts, no coords.+            ((1, 0), BodyLayer::new(0)),+            // Features but no parts and no coords, which `push` cannot make and a corrupt file can.+            (+                (2, 1),+                BodyLayer {+                    layer_id: 1,+                    features: vec![feature(1, 2, GEOM_LINE, 0, 0, 0)],+                    parts: Vec::new(),+                    coords: Vec::new(),+                },+            ),+            // A part with no coordinates.+            (+                (3, 2),+                BodyLayer {+                    layer_id: 2,+                    features: vec![feature(3, 4, GEOM_LINE, 1, 0, 1)],+                    parts: vec![Part { coord_start: 0, point_count: 0, winding: WINDING_OUTER }],+                    coords: Vec::new(),+                },+            ),+            // The extremes of every field: `u16::MAX` kinds, `i16` at both ends, a hole.+            (+                (4, 3),+                BodyLayer {+                    layer_id: 3,+                    features: vec![+                        feature(u16::MAX, u16::MAX, GEOM_POLYGON, 0x0f, 0, 2),+                        feature(0, 0, GEOM_POLYGON, 0, 2, 1),+                    ],+                    parts: vec![+                        Part { coord_start: 0, point_count: 2, winding: WINDING_OUTER },+                        Part { coord_start: 2, point_count: 2, winding: WINDING_HOLE },+                        Part { coord_start: 4, point_count: 1, winding: WINDING_OUTER },+                    ],+                    coords: vec![+                        (i16::MIN, i16::MAX),+                        (i16::MAX, i16::MIN),+                        (0, 0),+                        (-1, 1),+                        (32_767, -32_768),+                    ],+                },+            ),+            // Several layers on one tile, which is what the merge collapses.+            ((5, 1), BodyLayer::new(1)),+            (+                (5, 7),+                BodyLayer {+                    layer_id: 7,+                    features: vec![feature(9, 9, GEOM_LINE, 0, 0, 1)],+                    parts: vec![Part { coord_start: 0, point_count: 3, winding: WINDING_OUTER }],+                    coords: vec![(1, 2), (3, 4), (5, 6)],+                },+            ),+            ((5, 10), BodyLayer::new(10)),+        ]+    }++    fn drain(spill: &ChunkSpill, at: &ChunkRef, window: usize) -> Vec<((u64, u8), BodyLayer)> {+        let mut reader = spill.reader(at, window);+        let mut out = Vec::new();+        while let Some(entry) = reader.next().expect("read an entry back") {+            out.push(entry);+        }+        out+    }++    #[test]+    fn a_chunk_round_trips_through_the_scratch_file() {+        let spill = ChunkSpill::create(tmp("roundtrip")).expect("create");+        let want = every_layer();+        let map: BTreeMap<(u64, u8), BodyLayer> = want.iter().cloned().collect();+        let at = spill.write_chunk(map).expect("write");+        assert_eq!(at.entries, want.len() as u64);+        assert_eq!(drain(&spill, &at, 1 << 16), want);+        spill.check_books().expect("the books balance");+    }++    /// The claim the whole merge rests on: the file's order is `map.keys()`, so a reader hands+    /// `Merged` the identical key sequence a `BTreeMap` did.+    #[test]+    fn entry_order_is_the_maps_key_order() {+        let spill = ChunkSpill::create(tmp("order")).expect("create");+        // Inserted in a deliberately scrambled order; a `BTreeMap` sorts them and so must the file.+        let mut map: BTreeMap<(u64, u8), BodyLayer> = BTreeMap::new();+        for (tile, layer) in [(30u64, 2u8), (10, 5), (10, 1), (20, 9), (10, 3), (30, 0)] {+            map.insert((tile, layer), BodyLayer::new(layer));+        }+        let keys: Vec<(u64, u8)> = map.keys().copied().collect();+        let at = spill.write_chunk(map).expect("write");+        let read: Vec<(u64, u8)> = drain(&spill, &at, 1 << 16).into_iter().map(|(k, _)| k).collect();+        assert_eq!(read, keys);+        assert_eq!(read, vec![(10, 1), (10, 3), (10, 5), (20, 9), (30, 0), (30, 2)]);+    }++    /// Chunks written concurrently must not overlap, and every one must read back as itself.+    #[test]+    fn concurrent_chunks_get_disjoint_ranges_and_the_books_balance() {+        let spill = ChunkSpill::create(tmp("concurrent")).expect("create");+        let refs: Vec<ChunkRef> = std::thread::scope(|scope| {+            let handles: Vec<_> = (0..8u64)+                .map(|i| {+                    scope.spawn({+                        let spill = &spill;+                        move || {+                            let mut map: BTreeMap<(u64, u8), BodyLayer> = BTreeMap::new();+                            for tile in 0..64u64 {+                                let mut layer = BodyLayer::new(1);+                                layer.coords = vec![(i as i16, tile as i16); 1 + tile as usize];+                                map.insert((tile, 1), layer);+                            }+                            (i, spill.write_chunk(map).expect("write"))+                        }+                    })+                })+                .collect();+            let mut refs: Vec<(u64, ChunkRef)> =+                handles.into_iter().map(|h| h.join().expect("join")).collect();+            refs.sort_by_key(|(i, _)| *i);+            refs.into_iter().map(|(_, at)| at).collect()+        });++        let mut ranges: Vec<(u64, u64)> = refs.iter().map(|r| (r.at, r.at + r.len)).collect();+        ranges.sort();+        for pair in ranges.windows(2) {+            assert!(pair[0].1 <= pair[1].0, "two chunks share bytes: {pair:?}");+        }+        for (i, at) in refs.iter().enumerate() {+            let entries = drain(&spill, at, 1 << 15);+            assert_eq!(entries.len(), 64);+            assert_eq!(entries[3].1.coords[0], (i as i16, 3));+        }+        spill.check_books().expect("the books balance");+    }++    #[test]+    fn a_truncated_chunk_errors_rather_than_decoding() {+        let spill = ChunkSpill::create(tmp("truncated")).expect("create");+        let map: BTreeMap<(u64, u8), BodyLayer> = every_layer().into_iter().collect();+        let at = spill.write_chunk(map).expect("write");++        // Half a chunk: the reader is told the entry count but the bytes run out first.+        let short = ChunkRef { at: at.at, len: at.len / 2, entries: at.entries };+        let mut reader = spill.reader(&short, 1 << 16);+        let mut failed = false;+        loop {+            match reader.next() {+                Ok(Some(_)) => {}+                Ok(None) => break,+                Err(_) => {+                    failed = true;+                    break;+                }+            }+        }+        assert!(failed, "a truncated chunk decoded instead of erroring");++        // And the other way round: the bytes are there but fewer entries were claimed, so the+        // cursor would leave a tail behind.+        let fewer = ChunkRef { at: at.at, len: at.len, entries: at.entries - 1 };+        let mut reader = spill.reader(&fewer, 1 << 16);+        for _ in 0..fewer.entries {+            reader.next().expect("read").expect("an entry");+        }+        assert!(reader.next().is_err(), "a chunk with bytes past its last entry read as complete");+    }++    #[test]+    fn a_dirty_reserved_tail_errors() {+        let mut head = [0u8; ENTRY_HEADER_BYTES];+        entry_header(&head).expect("a zero header is legal");+        head[23] = 1;+        assert!(entry_header(&head).is_err(), "a nonzero reserved tail decoded");+    }++    #[test]+    fn an_entry_claiming_more_than_a_gigabyte_errors() {+        let mut head = [0u8; ENTRY_HEADER_BYTES];+        head[16..20].copy_from_slice(&u32::MAX.to_le_bytes());+        assert!(entry_header(&head).is_err(), "a gigabyte-plus entry decoded");+    }++    /// Byte-identity, at the level the format can state it: what a reader yields does not depend on+    /// how much it buffers. This is what pins "the window size is not observable".+    #[test]+    fn a_chunk_reads_the_same_however_the_window_is_sized() {+        let spill = ChunkSpill::create(tmp("windows")).expect("create");+        let mut map: BTreeMap<(u64, u8), BodyLayer> = every_layer().into_iter().collect();+        // One entry far larger than the smallest window, so at least one read has to be the+        // oversize path rather than the buffered one.+        let mut big = BodyLayer::new(4);+        big.features = vec![feature(1, 1, GEOM_LINE, 0, 0, 1)];+        big.parts = vec![Part { coord_start: 0, point_count: 40_000, winding: WINDING_OUTER }];+        big.coords = (0..40_000).map(|i| (i as i16, -(i as i16))).collect();+        map.insert((6, 4), big);+        let at = spill.write_chunk(map).expect("write");++        let want = drain(&spill, &at, 1 << 20);+        for window in [1usize, 24, 25, 64, 1024, 1 << 14, 1 << 16, 1 << 22] {+            assert_eq!(drain(&spill, &at, window), want, "window {window} yielded something else");+        }+    }++    #[test]+    fn the_scratch_file_is_removed_on_drop() {+        let path = tmp("dropped");+        {+            let spill = ChunkSpill::create(&path).expect("create");+            spill.write_chunk(every_layer().into_iter().collect()).expect("write");+            assert!(path.exists());+        }+        assert!(!path.exists(), "the scratch file outlived its spill");+    }++    /// The error path too: a spill dropped while a write is failing must not strand the file.+    #[test]+    fn the_scratch_file_is_removed_when_a_chunk_is_refused() {+        let path = tmp("refused");+        {+            let spill = ChunkSpill::create(&path).expect("create");+            // Keyed on one layer, carrying another.+            let mut map: BTreeMap<(u64, u8), BodyLayer> = BTreeMap::new();+            map.insert((1, 2), BodyLayer::new(3));+            assert!(spill.write_chunk(map).is_err(), "a mislabelled entry was accepted");+        }+        assert!(!path.exists(), "the scratch file outlived a failed write");+    }++    #[test]+    fn an_empty_chunk_is_zero_bytes_and_reads_as_nothing() {+        let spill = ChunkSpill::create(tmp("empty")).expect("create");+        let at = spill.write_chunk(BTreeMap::new()).expect("write");+        assert_eq!(at, ChunkRef { at: 0, len: 0, entries: 0 });+        assert!(drain(&spill, &at, 1 << 16).is_empty());+        spill.check_books().expect("the books balance");+    }++    #[test]+    fn the_books_catch_a_chunk_that_was_never_read() {+        let spill = ChunkSpill::create(tmp("unread")).expect("create");+        spill.write_chunk(every_layer().into_iter().collect()).expect("write");+        assert!(spill.check_books().is_err(), "an undrained spill balanced");+    }++    #[test]+    fn the_read_window_is_a_budget_divided_by_the_stream_count() {+        // `window_for` rather than `read_window_bytes`, so a test elsewhere holding the override+        // cannot make this one assert something else.+        assert_eq!(window_for(0), MAX_WINDOW, "no streams clamps up, not to zero");+        assert_eq!(window_for(1), MAX_WINDOW);+        // A north-america z14: the budget still binds, well clear of both clamps.+        let na = window_for(5_700);+        assert_eq!(na, READ_BUDGET / 5_700);+        assert!((MIN_WINDOW..=MAX_WINDOW).contains(&na));+        // A planet z14: the floor takes over, so the total is `streams * MIN_WINDOW`.+        assert_eq!(window_for(27_000), MIN_WINDOW);+        assert_eq!(window_for(10_000_000), MIN_WINDOW);+        for streams in [1usize, 2, 100, 5_700, 27_000, 10_000_000] {+            let window = window_for(streams);+            assert!(+                (MIN_WINDOW..=MAX_WINDOW).contains(&window),+                "{streams} streams gave a {window}-byte window"+            );+        }+    }+}
scripts/maps/measure_build.ps1
diff --git a/scripts/maps/measure_build.ps1 b/scripts/maps/measure_build.ps1index 505d0f9341..f99abfaa37 100644--- a/scripts/maps/measure_build.ps1+++ b/scripts/maps/measure_build.ps1@@ -11,8 +11,9 @@ # What this adds that the binary cannot easily measure about itself on Windows: #   * Peak resident memory. `PeakWorkingSet64` is a kernel high-water mark, so sampling #     from outside cannot miss a spike between two polls.-#   * Peak scratch disk. The spill is written during stage A and drained during tiling,-#     so it is gone before the build ends and only a sampler ever sees its size.+#   * Peak scratch disk. The feature spill is written during stage A and drained during+#     tiling; the tile chunks are truncated and removed once per zoom. Both are gone before+#     the build ends and only a sampler ever sees how large they got. #   * The archive's section breakdown, from `mamaps_dump`, which already decodes the #     header — reimplementing that here would be a second copy to keep in step. #@@ -43,6 +44,9 @@ param(     # identical every time for the same input, so this is the difference between a 20-minute     # experiment and a 60-minute one. Refused if the spill was built from anything else.     [switch] $ReuseStore,+    # Skip the free-space preflight. It is a heuristic on the .pbf's size, so an unusual layer+    # selection or an already-present spill can make it wrong in either direction.+    [switch] $NoSpaceCheck,     [string] $Exe,     [string] $Dump )@@ -63,6 +67,7 @@ $Pbf   = (Resolve-Path $Pbf).Path $Out   = [System.IO.Path]::GetFullPath($Out) # Named by the writer, beside the output. This is the scratch that peaks. $spill  = [System.IO.Path]::ChangeExtension($Out, "features.tmp")+$chunks = "$Out.tilechunks" $json   = "$Out.report.json" $name   = [System.IO.Path]::GetFileNameWithoutExtension($build) @@ -76,23 +81,47 @@ if ($Threads -gt 0) { $env:MAPS_THREADS = "$Threads" } else { Remove-Item Env:MA if ($Timing)        { $env:MAPS_TIMING  = "1"       } else { Remove-Item Env:MAPS_TIMING  -ErrorAction SilentlyContinue } if ($Lanes -gt 0)   { $env:MAPS_PREFETCH_LANES = "$Lanes" } else { Remove-Item Env:MAPS_PREFETCH_LANES -ErrorAction SilentlyContinue } +# --- free space, before anything is written -------------------------------+#+# Three things are on disk at once at the deepest zoom: the feature spill, one zoom's tile+# chunks and the archive being assembled. On north-america that is about 29 + 23 + 17 GB+# against a 14 GB .pbf; a planet build projects to 134 + 100 + 78 against roughly 80. Both+# land near six times the source, so that is the rule of thumb - and running out an hour+# into z14, after stage A has already been paid for, is the failure this exists to avoid.+if (-not $NoSpaceCheck) {+    $pbfBytes = (Get-Item $Pbf).Length+    # A reused spill is already on disk and does not have to be found again.+    $wanted = if ($ReuseStore) { $pbfBytes * 4 } else { $pbfBytes * 6 }+    $root = [System.IO.Path]::GetPathRoot($Out)+    $free = (New-Object System.IO.DriveInfo $root).AvailableFreeSpace+    if ($free -lt $wanted) {+        throw ("{0} has {1:N1} GB free and this build wants about {2:N1} GB " -f `+                $root, ($free / 1GB), ($wanted / 1GB)) ++              "(feature spill + one zoom's tile chunks + the archive). Free some, or pass " ++              "-NoSpaceCheck if you know better than the estimate."+    }+}+ # Started before the build, so the first spike cannot be missed.-$sampler = Start-Job -ArgumentList $name, $spill, $Out -ScriptBlock {-    param($name, $spill, $out)-    $peakWs = 0L; $peakPriv = 0L; $peakSpill = 0L; $peakData = 0L+$sampler = Start-Job -ArgumentList $name, $spill, $Out, $chunks -ScriptBlock {+    param($name, $spill, $out, $chunks)+    $peakWs = 0L; $peakPriv = 0L; $peakSpill = 0L; $peakData = 0L; $peakChunks = 0L     while ($true) {         $p = Get-Process -Name $name -ErrorAction SilentlyContinue         if ($p) {             $peakWs   = [Math]::Max($peakWs,   ($p | Measure-Object PeakWorkingSet64    -Maximum).Maximum)             $peakPriv = [Math]::Max($peakPriv, ($p | Measure-Object PrivateMemorySize64 -Maximum).Maximum)         }-        foreach ($pair in @(@($spill, [ref]$peakSpill),

Diff truncated.