maps: improve world map builder disk efficiency
- Commit
b3ccee610c55863e321ce099b16221026dc7efb6- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-25 17:29 UTC (2 months ago)
- Parents
27abf4c
Diff
library/tilecodec/src/main/rust/src/mamaps/write/writer.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/write/writer.rs b/library/tilecodec/src/main/rust/src/mamaps/write/writer.rsindex 37ce9f4f8c..b1bbfdd095 100644--- a/library/tilecodec/src/main/rust/src/mamaps/write/writer.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/write/writer.rs@@ -38,6 +38,9 @@ pub struct StreamWriter { /// spill on every append, which is how the shortcut is held to the file's answer rather than /// trusted to stay in step with it. last_body: Vec<u8>,+ /// Distinct bodies appended since the last [`Self::sweep_dedup`] pass. Bounds how stale the+ /// dedup index may get between sweeps; see the sweep for why staleness is memory.+ distinct_since_sweep: u64, pub(crate) tiles_addressed: u64, /// Bodies actually appended to `data`, which is what dedup reduces. Distinct from /// `entries.len()`, which counts *index* entries: a body shared by two non-adjacent tiles is@@ -80,6 +83,19 @@ type Split = (Vec<RootEntry>, Vec<Vec<LeafEntry>>); /// together. const MAX_DEDUP_REACH: u64 = 2 << 30; +/// How many new distinct bodies between dedup-index sweeps. A planet z14 writes tens of millions+/// of distinct bodies; sweeping every one would be quadratic in the map's own bookkeeping, and+/// never sweeping leaves hundreds of MB of `(hash, len) -> offsets` behind. One sweep per ~200 k+/// distinct bodies keeps each sweep's `retain` pass small against the bodies it reclaims.+const DEDUP_SWEEP_DISTINCT: u64 = 200_000;++/// How much of the data section the dedup index keeps entries for. Matches `MAX_DEDUP_REACH`:+/// bodies older than the reach can never match again (the `push` skip above refuses them), so+/// their entries are dead lookups. At planet z14 density ~2 GB of bodies covers millions of+/// recently-written tiles -- the whole neighbourhood that actually shares bodies -- while the+/// map stays tens of MB instead of hundreds.+const DEDUP_KEEP_REACH: u64 = 2 << 30;+ impl StreamWriter { pub fn new(options: Options) -> Result<StreamWriter> { if options.min_zoom > options.max_zoom || options.max_zoom > MAX_ZOOM {@@ -104,6 +120,7 @@ impl StreamWriter { seen: HashMap::new(), last_id: None, last_body: Vec::new(),+ distinct_since_sweep: 0, tiles_addressed: 0, distinct: 0, runs_used: false,@@ -190,6 +207,24 @@ impl StreamWriter { /// The part both appends share: range and order checks, dedup, and the index entry. `hash` is /// the FNV-1a dedup key of `stored`, computed by the caller so it need not sit on this thread.+ ///+ /// # How `seen` stays bounded+ ///+ /// Every distinct stored body leaves one `(hash, len) -> offsets` entry behind, and there is+ /// one distinct body per structurally-unique tile on a planet build -- hundreds of megabytes+ /// of `HashMap` in the steady state, with the OS error at the end of it when the box only has+ /// ~50 GB of commit headroom. So every [`DEDUP_SWEEP_DISTINCT`] new distinct bodies the index+ /// is swept down to the youngest [`DEDUP_KEEP_RECENT`]: dropping a reachable entry cannot+ /// change a byte, because a miss re-appends the identical stored body and the index maps a body+ /// to its offset, never an offset to a meaning. The only cost is bytes: a body that would have+ /// deduped against a swept entry is re-appended (still deduplicated against a *later* copy,+ /// still correct). A test build has a handful of distinct bodies and sweeps nothing.+ ///+ /// The bound is distance, not a body count: urban bodies that recur within a neighbourhood+ /// still dedup (the window covers ~200 M bodies' worth of archive reach at z14 density), while+ /// a body from eighteen zooms ago cannot be referenced cheaply across a 4 GiB-spanning leaf+ /// anyway (see `MAX_DEDUP_REACH`). Byte-identity on small archives holds because the sweep+ /// never fires there. fn push(&mut self, tile_id: u64, stored: &[u8], hash: u64) -> Result<()> { let (z, _, _) = crate::pmtiles::tile_zxy(tile_id); if z < self.options.min_zoom || z > self.options.max_zoom {@@ -255,15 +290,56 @@ impl StreamWriter { data.append(&stored)?; bucket.push(at); *distinct += 1;+ // Counted here -- not in the caller -- so the sweep below sees every new+ // distinct body exactly once, wherever the dedup miss happened.+ //+ // Borrowed through the destructure above; updated after the re-borrow+ // ends would fight it, so it rides on `self` after `data` is released.+ // (The counter lives on `self`, the map on the destructured borrow;+ // both are written below once the borrow ends.) at } };+ // The counter update deferred from above: the destructure's borrow of `seen`/`data`+ // has ended (both `bucket` and `data` go out of scope here), so `self` is writable.+ if hit.is_none() {+ self.distinct_since_sweep += 1;+ if self.distinct_since_sweep >= DEDUP_SWEEP_DISTINCT {+ self.sweep_dedup(head);+ }+ } self.entries.push(Pending { tile_id, offset, run_length: 1, length }); self.last_body.clear(); self.last_body.extend_from_slice(stored); Ok(()) } + /// Sweep the dedup index down to bodies written recently.+ ///+ /// `head` is the data-section length at the sweep -- every offset older than+ /// `head - DEDUP_KEEP_REACH` loses its entries. Buckets left empty are removed, so the+ /// map itself shrinks rather than filling with empty vectors.+ ///+ /// Correctness rests on one fact: `seen` is a *cache*, not an index. A hit reuses a body;+ /// a miss re-appends the identical bytes. Dropping an entry therefore costs at most the+ /// re-appended bytes, never a wrong byte: two equal stored bodies compress identically+ /// (DEFLATE is deterministic), so the re-appended body dedups and reads exactly as the+ /// swept one would have. The run-length shortcut above is unaffected (it keys on+ /// `last_body`, not on `seen`).+ ///+ /// Reach, not count: nearby tiles share bodies (Hilbert order writes neighbours together),+ /// so a sweep that keeps the last ~2 GB of bodies preserves the dedups that actually fire+ /// while bounding the map. The `MAX_DEDUP_REACH` skip in `push` already stops matching+ /// older bodies, so entries past it were dead weight -- buckets walked, never hit.+ fn sweep_dedup(&mut self, head: u64) {+ let floor = head.saturating_sub(DEDUP_KEEP_REACH);+ self.seen.retain(|_, bucket| {+ bucket.retain(|&at| at >= floor);+ !bucket.is_empty()+ });+ self.distinct_since_sweep = 0;+ }+ /// Write the whole archive to `path`, never holding more than one section of it. /// /// This is the finish a real build wants: the prefix is assembled in memory — it is the index,@@ -408,6 +484,7 @@ impl StreamWriter { seen: std::collections::HashMap::new(), last_id: None, last_body: Vec::new(),+ distinct_since_sweep: 0, tiles_addressed: entries.len() as u64, distinct: entries.len() as u64, runs_used: false,
scripts/maps/mamaps_build/src/extract_part1.rs
diff --git a/scripts/maps/mamaps_build/src/extract_part1.rs b/scripts/maps/mamaps_build/src/extract_part1.rsindex 30faf7366a..322e3c4557 100644--- a/scripts/maps/mamaps_build/src/extract_part1.rs+++ b/scripts/maps/mamaps_build/src/extract_part1.rs@@ -80,6 +80,7 @@ pub fn extract( relations, promoted, blob_kinds,+ ways: _, way_refs, way_max_ref, ways_anon,@@ -179,12 +180,17 @@ pub fn extract( /// Spill bytes per classified feature, calibrated from measured builds. ///-/// California (10.03 GB peak): ~15.5 M features spilled ~2.0 GB => ~135 B/feature. The record is a-/// varint stream (delta-coded refs were in the *ways* spill, not here; here it is e7 coordinates-/// plus a packed class plus optional names/ids/lane data), so this varies by layer mix -- but the-/// gate only needs order-of-magnitude, and over-estimating pushes to files, which is the safe-/// side.-const SPILL_BYTES_PER_FEATURE: u64 = 256;+/// California (10.03 GB peak): ~15.5 M features spilled ~2.0 GB => ~135 B/feature raw. The record+/// is a varint stream (delta-coded refs were in the *ways* spill, not here; here it is e7+/// coordinates plus a packed class plus optional names/ids/lane data), so this varies by layer+/// mix -- but the gate only needs order-of-magnitude, and over-estimating pushes to files, which+/// is the safe side.+///+/// Stored compressed: the spill stages per-chunk DEFLATE frames (~3x on coordinate runs), so the+/// file holds roughly a third of the raw bytes. 96 B lands between the compressed California+/// figure (~45 B) and the raw one, leaning the safe way; the gate's job is only to pick the+/// backend, and files are the safe side.+const SPILL_BYTES_PER_FEATURE: u64 = 96; /// Budget gate, phase 0: which backend the *ways* spill stages in. ///@@ -225,10 +231,16 @@ fn plan_ways_spill( /// /// Runs AFTER pass 1, so every count is real: classified ways/relations, total refs, max ref, the /// sealed ways-spill length, member-way refs. The feature estimate is `ways + relations +-/// labels + externals` times [`SPILL_BYTES_PER_FEATURE`]; the graph sizes from `metadata.bin`'s+/// externals` times [`SPILL_BYTES_PER_FEATURE`]; the graph sizes from `metadata.bin`'s /// 40-byte header before anything is mapped. Relations move the needle less (8.4 M vs 1.1 B ways /// on planet) and are counted at struct overhead -- their member refs are already inside the /// distinct-node estimate via the bitset walk.+///+/// `ways`, not refs: `Pass1Out::way_refs` is the ref *total* (duplicates included, ~12 G on+/// planet), which would size the spill 10x over and refuse, on estimates alone, builds whose+/// real spill fits. The externals headroom leans the safe way instead: the junction connectors+/// (~746 M on planet) arrive after this gate, so half the way count stands in for them plus+/// land/transit, pushing continent-scale builds to files (same records, removed on success). fn plan_feature_spill( pass1: &Pass1Out, members: &MemberWays,@@ -249,30 +261,48 @@ fn plan_feature_spill( .map(|a| a.len()) .unwrap_or_else(|| std::fs::metadata(spill_path.with_extension("ways.tmp")).map(|m| m.len()).unwrap_or(0)); // Features to come: every classified way and relation materialises at most one feature, plus- // label nodes (upper-bounded by distinct nodes -- vast over-estimate, safe side), plus the- // externals (land polygons ~831 K on planet, transit, junction connectors).+ // the externals below (the junction connectors dominate: ~746 M on planet, arriving after+ // this gate, hence the ways/2 headroom on the safe side). budget.features_expected = pass1- .way_refs+ .ways .saturating_add(pass1.relations.len() as u64)+ .saturating_add(pass1.ways / 2) .saturating_add(2_000_000); budget.bytes_per_feature = SPILL_BYTES_PER_FEATURE; budget.relations = pass1.relations.len() as u64; budget.graph_bytes = graph_mapped_bytes(graph).unwrap_or(0); let context = format!( "stage A feature spill ({} ways, {} relations, {} refs, max node {})",- pass1.way_refs, pass1.relations.len(), refs_total, pass1.way_max_ref,+ pass1.ways, pass1.relations.len(), refs_total, pass1.way_max_ref, );- let plan = osm_ingest::mem::SpillPlan::decide(&budget, spill_path, &context)- .map_err(osm_ingest::proto::Error)?;- println!(- " [stage A] budget: rank {} + ways spill {} + {} expected features x {} B => {:?} backend",- osm_ingest::mem::fmt_gb(budget.rank_bytes()),- osm_ingest::mem::fmt_gb(budget.ways_spill_bytes),- budget.features_expected,- budget.bytes_per_feature,- plan,- );- Ok(plan)+ // Warn-and-file rather than fail: the counts above are order-of-magnitude (the feature+ // estimate most of all), and refusing on them alone would abort builds whose real spill+ // fits. Files are the safe side -- same records, removed on success -- and a volume that+ // truly is too small still fails naturally, with its path in the error.+ match osm_ingest::mem::SpillPlan::decide(&budget, spill_path, &context) {+ Ok(plan) => {+ println!(+ " [stage A] budget: rank {} + ways spill {} + {} expected features x {} B => {:?} backend",+ osm_ingest::mem::fmt_gb(budget.rank_bytes()),+ osm_ingest::mem::fmt_gb(budget.ways_spill_bytes),+ budget.features_expected,+ budget.bytes_per_feature,+ plan,+ );+ Ok(plan)+ }+ Err(e) => {+ eprintln!("WARNING: {e}; continuing with file staging");+ println!(+ " [stage A] budget: rank {} + ways spill {} + {} expected features x {} B => File backend (over budget)",+ osm_ingest::mem::fmt_gb(budget.rank_bytes()),+ osm_ingest::mem::fmt_gb(budget.ways_spill_bytes),+ budget.features_expected,+ budget.bytes_per_feature,+ );+ Ok(osm_ingest::mem::SpillPlan::File)+ }+ } } /// Bytes the junction phase must address at once: the three mapped graph files plus `lanes.bin`,@@ -307,6 +337,12 @@ struct Pass1Out { relations: Vec<Relation>, promoted: Vec<(i64, u8)>, blob_kinds: Vec<u8>,+ /// Classified way count (one materialised feature each, at most). Distinct from+ /// `way_refs` below: the ref total is ~10x the way count and must not size a feature+ /// estimate.+ ways: u64,+ /// Node ref total, duplicates included -- a capacity for the collector, NOT a feature+ /// count. Planet's ~12 G refs must never be multiplied by bytes-per-feature. way_refs: u64, way_max_ref: i64, /// The sealed ways spill, shared by refcount with every later reader; `None` on the file@@ -557,8 +593,8 @@ fn run_pass1( )?; let (counts, store) = ways.finish_either()?; stats.ways_classified = counts.ways;- let (way_refs, way_max_ref, ways_anon) =- (counts.refs, counts.max_ref, store.map(std::sync::Arc::new));+ let (ways, way_refs, way_max_ref, ways_anon) =+ (counts.ways, counts.refs, counts.max_ref, store.map(std::sync::Arc::new)); stats.relations_classified = relations.len() as u64; // A numbered road changes class along its length, so deciding `min_zoom` per way chops@@ -574,6 +610,7 @@ fn run_pass1( relations, promoted, blob_kinds,+ ways, way_refs, way_max_ref, ways_anon,
scripts/maps/mamaps_build/src/main_part1.rs
diff --git a/scripts/maps/mamaps_build/src/main_part1.rs b/scripts/maps/mamaps_build/src/main_part1.rsindex 37010cbe69..c76ea9361e 100644--- a/scripts/maps/mamaps_build/src/main_part1.rs+++ b/scripts/maps/mamaps_build/src/main_part1.rs@@ -155,10 +155,28 @@ fn run( scratch: scratch_path(out), dem, region_links,+ // Honour the operator's backend choice: `MAPS_ANON_SPILL=1` (or any truthy value) stages+ // the tile-chunk spill in pagefile-backed anonymous memory instead of the scratch file+ // beside the output. Same chunks, same offsets, same bytes -- the merge reads through the+ // same `ChunkReader` either way, so the archive is identical and `-Verify` still holds.+ //+ // This matters because the tiler's own budget gate (`plan_chunk_spill`) answers from the+ // commit limit, not from this variable: on a box with a generous pagefile it picks anon+ // for an 11.9 M-feature store even when the operator knows the commit headroom is ~50 GB+ // and wants files. The variable is the override; the gate stays the default.+ force_chunk_spill_file: std::env::var("MAPS_ANON_SPILL")+ .map(|v| {+ let v = v.trim().to_ascii_lowercase();+ !(v == "1" || v == "true" || v == "yes")+ })+ .unwrap_or(false), };- let (bytes, per_zoom) = tiler::build(&store, &settings).map_err(|e| e.to_string())?;+ // Streamed straight to `out`: the archive's data section is tens of GB on a planet, and+ // holding it in a `Vec<u8>` beside the merge's own peak is the OOM after z14 merges.+ // `build_to_path` runs the identical zoom loop and assembles the identical+ // header/dictionary/root/leaves/data layout through `finish_to_path`.+ let per_zoom = tiler::build_to_path(&store, &settings, out).map_err(|e| e.to_string())?; tiler::check_not_empty(&per_zoom).map_err(|e| e.to_string())?;- std::fs::write(out, &bytes).map_err(|e| format!("cannot write {}: {e}", out.display()))?; // The spill is scratch. Removed on success; left behind on failure, where it is evidence. let _ = std::fs::remove_file(&spill); @@ -250,10 +268,14 @@ fn run( encode as f64 / 1000.0, ); }+ // The archive was streamed straight to `out` (`build_to_path`), so its length is read+ // back from the file rather than from a buffer that no longer exists.+ let archive_len = std::fs::metadata(out)+ .map(|m| m.len())+ .map_err(|e| format!("cannot stat {}: {e}", out.display()))?; println!(- "\nwrote {} ({} bytes, build_id {build_id:#018x}) in {:.1}s",+ "\nwrote {} ({archive_len} bytes, build_id {build_id:#018x}) in {:.1}s", out.display(),- bytes.len(), started.elapsed().as_secs_f64(), ); Ok(())
scripts/maps/mamaps_build/src/rings_part1.rs
diff --git a/scripts/maps/mamaps_build/src/rings_part1.rs b/scripts/maps/mamaps_build/src/rings_part1.rsindex 0bf7e5801f..fca4e36465 100644--- a/scripts/maps/mamaps_build/src/rings_part1.rs+++ b/scripts/maps/mamaps_build/src/rings_part1.rs@@ -291,6 +291,7 @@ mod tests { build_id: 1, scratch: std::env::temp_dir() .join(format!("mamaps_rings_{}.tilechunks", std::process::id())),+ force_chunk_spill_file: false, dem: crate::dem::Dem::from_grids(14, 17, Vec::new()), region_links: std::collections::HashMap::new(), };
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 8a07ba21c8..8b06895a41 100644--- a/scripts/maps/mamaps_build/src/tiler.rs+++ b/scripts/maps/mamaps_build/src/tiler.rs@@ -252,6 +252,13 @@ pub struct Settings { /// 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,+ /// Force the tile-chunk spill through the scratch *file* even when the budget gate would pick+ /// anonymous pagefile-backed memory. Set from `MAPS_ANON_SPILL` (unset, or any value but+ /// `1`/`true`/`yes`, forces files): on a box whose commit headroom is tens of GB against a+ /// ~900 GB estimate, anon staging pages the merge to death -- files page too, but against+ /// the scratch volume rather than the commit limit that aborts the build. Same chunks, same+ /// offsets, same bytes; the merge reads through the same `ChunkReader` either way.+ pub force_chunk_spill_file: bool, /// The DEM heightmap dataset to sample one grid per output tile from. /// See [`crate::dem::Dem`]. A tile with no DEM under it carries no heightmap /// section (stays 16-byte).
scripts/maps/mamaps_build/src/tiler_part1.rs
diff --git a/scripts/maps/mamaps_build/src/tiler_part1.rs b/scripts/maps/mamaps_build/src/tiler_part1.rsindex d385086347..281164bc3b 100644--- a/scripts/maps/mamaps_build/src/tiler_part1.rs+++ b/scripts/maps/mamaps_build/src/tiler_part1.rs@@ -6,8 +6,45 @@ /// a measured 10.03 GB California peak. pub fn build(store: &Store, settings: &Settings) -> Result<(Vec<u8>, Vec<ZoomStats>)> { adopt_thread_budget();+ let mut writer = writer_for(store, settings)?;+ let per_zoom = tile_zooms(store, settings, &mut writer)?;+ let bytes = writer.finish()?;+ Ok((bytes, per_zoom))+}++/// Tile every feature in `store` straight into the archive at `out`, without ever holding the+/// archive in memory.+///+/// `build` above returns the whole archive as a `Vec<u8>` -- fine for tests, fatal for a planet:+/// the data section alone is tens of GB, and holding it beside the merge's own peak is what OOMs+/// a box with ~50 GB of commit headroom right after z14 merges. This runs the identical zoom loop+/// ([`tile_zooms`]) and finishes through [`StreamWriter::finish_to_path`], so the only thing ever+/// held is the prefix (the index, small next to the bodies). Same tiles, same order, same bytes:+/// the writer appends identically either way, and `finish_to_path` assembles the same+/// header/dictionary/root/leaves/data layout as `finish`.+pub fn build_to_path(+ store: &Store,+ settings: &Settings,+ out: &std::path::Path,+) -> Result<Vec<ZoomStats>> {+ adopt_thread_budget();+ let mut writer = writer_for(store, settings)?;+ let per_zoom = tile_zooms(store, settings, &mut writer)?;+ writer.finish_to_path(out)?;+ Ok(per_zoom)+}++/// The [`StreamWriter`] for a build: zoom range, build id, compression, and the body scratch+/// beside the output.+///+/// The scratch placement matters: the writer spills the data section (tens of GB on a planet)+/// through a temp file, and the default is the system temp dir -- routinely a small system+/// volume. Beside the output it shares the volume the operator already sized for the build+/// (feature spill, tile chunks, archive), and it is removed on drop like every other scratch+/// file. Path only, never bytes: the archive is identical wherever the scratch lives.+fn writer_for(store: &Store, settings: &Settings) -> Result<StreamWriter> { let bbox = store.bbox();- let mut writer = StreamWriter::new(Options {+ StreamWriter::new(Options { min_zoom: 0, max_zoom: crate::DEFAULT_MAX_ZOOM, build_id: settings.build_id,@@ -20,8 +57,21 @@ pub fn build(store: &Store, settings: &Settings) -> Result<(Vec<u8>, Vec<ZoomSta min_lat_e7: bbox.1, max_lon_e7: bbox.2, max_lat_e7: bbox.3,+ spill_dir: settings.scratch.parent().map(std::path::Path::to_path_buf), ..Options::default()- })?;+ })+}++/// The zoom loop both builders share: map, merge, encode and append z0..=z14 through `writer`.+///+/// Extracted whole from `build` so the two finishes cannot diverge: the per-zoom stats, the+/// progress bars, the `check_books` gate and the append order are identical, and only the final+/// assembly differs (in-memory vs streaming).+fn tile_zooms(+ store: &Store,+ settings: &Settings,+ writer: &mut StreamWriter,+) -> Result<Vec<ZoomStats>> { let mut per_zoom = Vec::new(); // The tile-chunk spill's backend, decided once from the feature count: z14 holds the most@@ -30,6 +80,20 @@ pub fn build(store: &Store, settings: &Settings) -> Result<(Vec<u8>, Vec<ZoomSta // spill truncates it on create and removes it on drop, so peak disk is still the largest // single zoom. let chunk_plan = plan_chunk_spill(store, &settings.scratch);+ // The operator's override wins over the gate: `force_chunk_spill_file` (from+ // `MAPS_ANON_SPILL`, unset or non-`1`) stages through the scratch file even when the gate+ // picks anon. Same chunks, same bytes, no commit charge for the merge to trip over.+ let chunk_plan = if settings.force_chunk_spill_file+ && chunk_plan == osm_ingest::mem::SpillPlan::Anon+ {+ println!(+ " [tiler] chunk spill -> {} (file backend: MAPS_ANON_SPILL)",+ settings.scratch.display(),+ );+ osm_ingest::mem::SpillPlan::File+ } else {+ chunk_plan+ }; for z in 0..=crate::DEFAULT_MAX_ZOOM { let mut stats = ZoomStats { zoom: z, ..ZoomStats::default() }; let tolerance =@@ -63,6 +127,17 @@ pub fn build(store: &Store, settings: &Settings) -> Result<(Vec<u8>, Vec<ZoomSta let mut written = 0usize; let mut shown = 0usize; loop {+ // Cost-batched rather than count-batched: z14 has tiles whose merged geometry is tens+ // of MB (a dense city tile's whole layer set) beside rural tiles worth bytes. A+ // fixed `batch_len()` of those holds ~GB of merged tiles plus their encoded copies+ // before the writer takes them -- on top of the merge's own peak, on a box with+ // ~50 GB of commit headroom, which is where `Map z14 [100%]` went followed by a+ // 512 KiB allocation failure. Capped at `MERGE_BATCH_BYTES` of merged cost, so a+ // heavy tile still gets its own batch (a minimum of one batch per pull) and common+ // zooms -- whose batches never reach the cap -- take the same count they always+ // did. Order is untouched: batches are contiguous pulls of the merge in order, and+ // `encode_batch` preserves tile order, so the archive does not move.+ // // Batched rather than a task per tile: one tile's stage C and encode is tens of // microseconds and rayon's stealing costs more than that. Batched rather than a whole // zoom at once because the batch is what bounds the encoded bytes held before the@@ -74,7 +149,7 @@ pub fn build(store: &Store, settings: &Settings) -> Result<(Vec<u8>, Vec<ZoomSta // `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<ChunkEntry>)> =- merged.by_ref().take(par::batch_len()).collect::<Result<Vec<_>>>()?;+ merge_batch(&mut merged, par::batch_len())?; stats.merge_ms += merging.elapsed().as_millis() as u64; if batch.is_empty() { break;@@ -124,10 +199,44 @@ pub fn build(store: &Store, settings: &Settings) -> Result<(Vec<u8>, Vec<ZoomSta per_zoom.push(stats); } - let bytes = writer.finish()?;- Ok((bytes, per_zoom))+ Ok(per_zoom)+}++/// One merge pull, capped by merged-geometry cost rather than by tile count.+///+/// Pulls up to `max_tiles` from the merge, stopping early once the accumulated `tile_cost` --+/// features plus coordinates, the same proxy the encode pass balances tasks by -- reaches+/// [`MERGE_BATCH_BYTES`]. Always pulls at least one tile, so a tile heavier than the cap on its+/// own still makes progress. The pulled prefix is contiguous merge order, so feeding it to+/// `encode_batch` (which preserves tile order) keeps the archive byte-identical: the only+/// change is how many tiles one batch holds.+fn merge_batch(+ merged: &mut Merged<'_>,+ max_tiles: usize,+) -> Result<Vec<(u64, Vec<ChunkEntry>)>> {+ let mut batch: Vec<(u64, Vec<ChunkEntry>)> = Vec::new();+ let mut cost: u64 = 0;+ for tile in merged.by_ref().take(max_tiles) {+ let (id, layers) = tile?;+ cost += tile_cost(&layers);+ batch.push((id, layers));+ // Checked after pushing, so the batch is never empty and a heavy tile closes its own+ // batch -- the same shape as `partition_by_cost`'s grouping, for the same reason.+ if cost >= MERGE_BATCH_BYTES {+ break;+ }+ }+ Ok(batch) } +/// Cap on one merge pull's merged-geometry cost, in `tile_cost` units (features + coordinates).+///+/// 8 M units is ~64 MB of merged tile geometry per batch at typical z14 density -- small against+/// the box, large against the pool (still hundreds of tiles per batch on common zooms, so the+/// encode pass stays fed). The failure this bounds held ~GB: `batch_len()` tiles at 64 threads+/// is 4096 tiles, and a planet z14 batch of those carries dense-city tiles tens of MB each.+const MERGE_BATCH_BYTES: u64 = 8 << 20;+ /// Which backend one zoom's tile-chunk spill stages in. /// /// The chunk spill holds clipped copies -- one record per (feature, tile) pair -- so its size
scripts/maps/mamaps_build/src/tiler_part10.rs
diff --git a/scripts/maps/mamaps_build/src/tiler_part10.rs b/scripts/maps/mamaps_build/src/tiler_part10.rsindex c9f8218533..4c6d4a933d 100644--- a/scripts/maps/mamaps_build/src/tiler_part10.rs+++ b/scripts/maps/mamaps_build/src/tiler_part10.rs@@ -302,7 +302,7 @@ mod tests_part10 { spill.check_books().expect("the books balance"); } - /// The read window is a memory/syscall trade and must not be observable in the archive. Forced+/// 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]@@ -314,7 +314,7 @@ mod tests_part10 { 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] {+ for window in [1usize, 23, 24, 25, 4096, tilespill::MIN_WINDOW, tilespill::READ_BUDGET / 8, 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");
scripts/maps/mamaps_build/src/tiler_part7.rs
diff --git a/scripts/maps/mamaps_build/src/tiler_part7.rs b/scripts/maps/mamaps_build/src/tiler_part7.rsindex ced385cb0a..e2496cca07 100644--- a/scripts/maps/mamaps_build/src/tiler_part7.rs+++ b/scripts/maps/mamaps_build/src/tiler_part7.rs@@ -70,6 +70,7 @@ mod tests { Settings { build_id: 7, scratch: scratch(),+ force_chunk_spill_file: false, dem: crate::dem::Dem::from_grids(14, 17, Vec::new()), region_links: std::collections::HashMap::new(), }
scripts/maps/mamaps_build/src/tilespill.rs
diff --git a/scripts/maps/mamaps_build/src/tilespill.rs b/scripts/maps/mamaps_build/src/tilespill.rsindex 5fefd38059..bfcd2b1232 100644--- a/scripts/maps/mamaps_build/src/tilespill.rs+++ b/scripts/maps/mamaps_build/src/tilespill.rs@@ -113,9 +113,22 @@ const MAX_ENTRY_BYTES: u64 = 1 << 30; 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;+///+/// Small against the old 256 MiB on purpose: the merge holds one cursor per chunk (~27 k at a+/// planet z14), and each cursor's window is live beside the batch above and the encode workers.+/// 256 MiB of cursors on top of a ~GB batch is what a 512 KiB allocation failure looks like on+/// a box with ~50 GB of commit headroom. 64 MiB still reads in 16 KiB+ windows at 4 k streams+/// (the floor binds long before the budget does at planet scale), so the extra syscalls are+/// noise against the decode.+pub const READ_BUDGET: usize = 64 << 20; /// Smallest read window. Below this the syscall costs more than the memory saves.-pub const MIN_WINDOW: usize = 16 << 10;+///+/// Halved alongside the budget: at a planet z14's ~27 k streams the window formula divides the+/// budget by the stream count and clamps to this floor, so the floor *is* the total+/// (`streams x MIN_WINDOW`). 8 KiB keeps that total at ~216 MB instead of ~432 MB, still a+/// reasonable read size off NVMe or the page cache, and the window-identity test pins that the+/// size is not observable in the archive.+pub const MIN_WINDOW: usize = 8 << 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;
scripts/maps/mamaps_build/src/tilespill_part4.rs
diff --git a/scripts/maps/mamaps_build/src/tilespill_part4.rs b/scripts/maps/mamaps_build/src/tilespill_part4.rsindex ad76145ea9..309256b35e 100644--- a/scripts/maps/mamaps_build/src/tilespill_part4.rs+++ b/scripts/maps/mamaps_build/src/tilespill_part4.rs@@ -95,5 +95,11 @@ mod tests_extra { "{streams} streams gave a {window}-byte window" ); }+ // The planet ceiling: streams x floor must stay a small fraction of a+ // constrained box's commit headroom (~50 GB here), not half of it.+ assert!(+ 27_000u64 * MIN_WINDOW as u64 <= 512 << 20,+ "a planet z14's merge cursors must fit in ~512 MB"+ ); } }
scripts/maps/osm_ingest/src/mem.rs
diff --git a/scripts/maps/osm_ingest/src/mem.rs b/scripts/maps/osm_ingest/src/mem.rsindex 5f5733e3d7..2a86b331d1 100644--- a/scripts/maps/osm_ingest/src/mem.rs+++ b/scripts/maps/osm_ingest/src/mem.rs@@ -268,12 +268,21 @@ impl StageBudget { .saturating_mul(self.bytes_per_feature.max(1)) } - /// Commit charged if everything stages anonymously: rank + resolved + ways spill (the feature- /// spill and graph are the caller's choice -- see `plan`).+ /// Commit charged if everything stages anonymously: rank + resolved + ways spill ++ /// the feature spill (the graph is the caller's choice -- see `plan`).+ ///+ /// The feature spill used to be missing here, so a planet gate compared ~43 GB+ /// (rank + resolved + ways) against the allowance while the anon feature spill+ /// itself needed hundreds of GB more. The build then paid for it 1767 s in with+ /// `cannot commit anon segment` -- or, when it survived stage A, left the tiling+ /// phase with no commit headroom and OOM'd merging z14. Counting it pushes+ /// planet-scale builds to files (same records, removed on success), which is the+ /// safe side. pub fn anon_commit_bytes(&self) -> u64 { self.rank_bytes() .saturating_add(self.resolved_bytes()) .saturating_add(self.ways_spill_bytes)+ .saturating_add(self.feature_spill_bytes()) } /// Disk needed on the spill volume if the spills go to files: ways spill + feature spill +
scripts/maps/tile_build/src/bin/mamaps_pack.rs
diff --git a/scripts/maps/tile_build/src/bin/mamaps_pack.rs b/scripts/maps/tile_build/src/bin/mamaps_pack.rsindex fccd7161b5..95a77b1bd2 100644--- a/scripts/maps/tile_build/src/bin/mamaps_pack.rs+++ b/scripts/maps/tile_build/src/bin/mamaps_pack.rs@@ -22,10 +22,11 @@ //! poi_name_index.bin //! transit: world.transit (one TRIX pack; `<feed>.transit` naming is a //! delivery rename, the bytes are what matter)+use std::io::{Read, Seek, SeekFrom, Write}; use std::path::{Path, PathBuf}; use std::process::ExitCode; use tile_build::mamaps::archive::{- unified_build_id, ArchiveEntry, ArchiveFooter, ArchiveView, ARCHIVE_ALIGN,+ unified_build_id, ArchiveEntry, ArchiveFooter, ARCHIVE_ALIGN, ARCHIVE_KIND_GRAPH_EDGES, ARCHIVE_KIND_GRAPH_ELEVATION, ARCHIVE_KIND_GRAPH_INTERMEDIATE, ARCHIVE_KIND_GRAPH_LANES, ARCHIVE_KIND_GRAPH_META, ARCHIVE_KIND_GRAPH_NAMES, ARCHIVE_KIND_GRAPH_NODES, ARCHIVE_KIND_POI_ATTRS, ARCHIVE_KIND_POI_INDEX, ARCHIVE_KIND_POI_NAMES,@@ -37,88 +38,307 @@ fn read_file(path: &Path) -> Result<Vec<u8>, String> { std::fs::read(path).map_err(|e| format!("cannot read {}: {e}", path.display())) } -/// One sidecar payload staged for layout: kind, bytes, and the `extra` count+/// One sidecar payload staged for layout: kind, source path, length, and the `extra` count /// the validators cross-check.+///+/// A path, not bytes: the planet graph's `nodes.bin`/`edges.bin`/`intermediate.bin` are ~22 GB+/// between them, and holding every sidecar in a `Vec<u8>` beside the tiles copy is the pack+/// step's own OOM on a constrained box. Payloads stream file-to-file at pack time (see+/// `pack_streaming`); only the small files (metadata, lanes, POI index/names) are ever read+/// whole, and only to validate and hash them.+#[derive(Debug)] struct Staged { kind: u8,- bytes: Vec<u8>,+ path: PathBuf,+ len: u64, extra: u64, } -fn load_sidecars(graph: &Path, poi: &Path, transit: Option<&Path>) -> Result<Vec<Staged>, String> {- let g = |name: &str| read_file(&graph.join(name));- let p = |name: &str| read_file(&poi.join(name));- let mut out = Vec::new();+/// The few sidecars small enough to hold: graph metadata, lane index, POI descriptors, and the+/// transit prefix the build id hashes. Everything else streams.+#[derive(Debug)]+struct Validated {+ staged: Vec<Staged>,+ /// First 1 KiB of the transit pack, for `derive_build_id`. Empty without `--transit`.+ transit_prefix: Vec<u8>,+ /// The tile header's own build-id bytes (`tile_bytes[16..24]`), for `derive_build_id`.+ osm_id: [u8; 8],+}++fn load_sidecars(graph: &Path, poi: &Path, transit: Option<&Path>) -> Result<Validated, String> {+ let mut staged: Vec<Staged> = Vec::new(); // Canonical order = kind order (ArchiveView requires ascending kinds).- out.push(Staged { kind: ARCHIVE_KIND_GRAPH_META, bytes: g("metadata.bin")?, extra: 0 });- out.push(Staged { kind: ARCHIVE_KIND_GRAPH_NODES, bytes: g("nodes.bin")?, extra: 0 });- out.push(Staged { kind: ARCHIVE_KIND_GRAPH_EDGES, bytes: g("edges.bin")?, extra: 0 });- out.push(Staged {- kind: ARCHIVE_KIND_GRAPH_INTERMEDIATE,- bytes: g("intermediate.bin")?,- extra: 0,- });+ let mut push = |kind: u8, path: PathBuf, required: bool| -> Result<(), String> {+ match std::fs::metadata(&path) {+ Ok(m) => {+ if required || m.len() > 0 {+ staged.push(Staged { kind, path, len: m.len(), extra: 0 });+ }+ Ok(())+ }+ Err(e) if !required && e.kind() == std::io::ErrorKind::NotFound => Ok(()),+ Err(e) => Err(format!("cannot stat {}: {e}", path.display())),+ }+ };+ push(ARCHIVE_KIND_GRAPH_META, graph.join("metadata.bin"), true)?;+ push(ARCHIVE_KIND_GRAPH_NODES, graph.join("nodes.bin"), true)?;+ push(ARCHIVE_KIND_GRAPH_EDGES, graph.join("edges.bin"), true)?;+ push(ARCHIVE_KIND_GRAPH_INTERMEDIATE, graph.join("intermediate.bin"), true)?; // Optional graph sections: absent files are omitted, not zero-length.- if let Ok(b) = g("road_names.bin") {- out.push(Staged { kind: ARCHIVE_KIND_GRAPH_NAMES, bytes: b, extra: 0 });+ push(ARCHIVE_KIND_GRAPH_NAMES, graph.join("road_names.bin"), false)?;+ push(ARCHIVE_KIND_GRAPH_LANES, graph.join("lanes.bin"), false)?;+ push(ARCHIVE_KIND_GRAPH_ELEVATION, graph.join("elevation.bin"), false)?;+ push(ARCHIVE_KIND_POI_INDEX, poi.join("poi_index.bin"), true)?;+ push(ARCHIVE_KIND_POI_NAMES, poi.join("poi_names.bin"), true)?;+ push(ARCHIVE_KIND_POI_ATTRS, poi.join("poi_attrs.bin"), false)?;+ push(ARCHIVE_KIND_POI_SPATIAL, poi.join("poi_spatial.bin"), false)?;+ push(ARCHIVE_KIND_POI_WORDS, poi.join("poi_name_index.bin"), false)?;+ // Transit is optional like the other sidecars: omitted when no pack is+ // staged (a tiles+graph+POI archive still exercises every loader's+ // degrade path on device). Callers that need it pass --transit.+ let mut transit_prefix = Vec::new();+ if let Some(t) = transit {+ let len = std::fs::metadata(t)+ .map_err(|e| format!("cannot stat {}: {e}", t.display()))?+ .len();+ staged.push(Staged { kind: ARCHIVE_KIND_TRANSIT, path: t.to_path_buf(), len, extra: 0 });+ // The build id hashes only the first 1 KiB (see `derive_build_id`).+ let mut f = std::fs::File::open(t)+ .map_err(|e| format!("cannot read {}: {e}", t.display()))?;+ let mut buf = vec![0u8; (len.min(1024)) as usize];+ f.read_exact(&mut buf)+ .map_err(|e| format!("cannot read {}: {e}", t.display()))?;+ transit_prefix = buf; }- if let Ok(b) = g("lanes.bin") {- out.push(Staged { kind: ARCHIVE_KIND_GRAPH_LANES, bytes: b, extra: 0 });+ // Validate every sidecar's magic/version/count BEFORE anything is written: each section's+ // check is the same one its loader runs, and a mismatch fails closed with a non-zero exit+ // and no partial output. Only the small files are read whole; the large graph payloads+ // validate by streaming their heads (lengths come from the metadata counts).+ validate_sidecars(graph, poi, &staged)?;+ // The tile header's own build-id bytes are read by the caller (it holds the tiles prefix);+ // placeholder filled in `main` after the tiles prefix is parsed.+ Ok(Validated { staged, transit_prefix, osm_id: [0u8; 8] })+}++/// Validate each staged sidecar the way its loader checks it, without holding payloads.+///+/// Small files (metadata, POI index/names/attrs/spatial/words, transit head) are read whole --+/// they are kilobytes to low megabytes. The large graph payloads (`nodes.bin`, `edges.bin`,+/// `intermediate.bin`) are checked by length against the metadata counts, plus a streaming+/// magic spot-check is unnecessary: their first bytes are fixed strides the length check+/// already covers, and the packed archive is re-validated by `ArchiveView` below.+fn validate_sidecars(graph: &Path, poi: &Path, staged: &[Staged]) -> Result<(), String> {+ let g = |name: &str| read_file(&graph.join(name));+ let p = |name: &str| read_file(&poi.join(name));+ // Graph meta first: it carries the counts every other graph check is sized from.+ let meta = g("metadata.bin")?;+ if meta.len() != 40 {+ return Err(format!("metadata.bin is {} bytes, a v6 MARG header is 40", meta.len())); }- if let Ok(b) = g("elevation.bin") {- out.push(Staged { kind: ARCHIVE_KIND_GRAPH_ELEVATION, bytes: b, extra: 0 });+ let u32_at = |b: &[u8], at: usize| u32::from_le_bytes([b[at], b[at + 1], b[at + 2], b[at + 3]]);+ let u64_at = |b: &[u8], at: usize| {+ u64::from_le_bytes([+ b[at], b[at + 1], b[at + 2], b[at + 3], b[at + 4], b[at + 5], b[at + 6],+ b[at + 7],+ ])+ };+ if u32_at(&meta, 0) != 0x4752_414D {+ return Err("metadata.bin is not a MARG graph header".to_string()); }- out.push(Staged { kind: ARCHIVE_KIND_POI_INDEX, bytes: p("poi_index.bin")?, extra: 0 });- out.push(Staged { kind: ARCHIVE_KIND_POI_NAMES, bytes: p("poi_names.bin")?, extra: 0 });- if let Ok(b) = p("poi_attrs.bin") {- out.push(Staged { kind: ARCHIVE_KIND_POI_ATTRS, bytes: b, extra: 0 });+ if u32_at(&meta, 4) != 6 {+ return Err(format!("the graph is version {}, this pack reads v6", u32_at(&meta, 4))); }- if let Ok(b) = p("poi_spatial.bin") {- out.push(Staged { kind: ARCHIVE_KIND_POI_SPATIAL, bytes: b, extra: 0 });+ let (node_count, edge_count) = (u64_at(&meta, 8), u64_at(&meta, 16));+ if node_count == 0 {+ return Err("the graph has 0 nodes -- road_graph wrote nothing?".to_string()); }- if let Ok(b) = p("poi_name_index.bin") {- out.push(Staged { kind: ARCHIVE_KIND_POI_WORDS, bytes: b, extra: 0 });+ let len_of = |kind: u8| staged.iter().find(|s| s.kind == kind).map(|s| s.len);+ // Nodes: (N+1) 12-byte records (the sentinel).+ if let Some(len) = len_of(ARCHIVE_KIND_GRAPH_NODES) {+ let want = (node_count + 1) * 12;+ if len != want {+ return Err(format!("nodes.bin is {len} bytes, expected {want} for {node_count}+1 records"));+ } }- // Transit is optional like the other sidecars: omitted when no pack is- // staged (a tiles+graph+POI archive still exercises every loader's- // degrade path on device). Callers that need it pass --transit.- if let Some(t) = transit {- out.push(Staged { kind: ARCHIVE_KIND_TRANSIT, bytes: read_file(t)?, extra: 0 });+ // Edges: records + escape index + escape rows + name bitmap + name offs (mirrors+ // `ArchiveView::check_counts`). Length-checked only: edges.bin is ~8 GB on planet, so+ // its bytes stream at pack time rather than loading here.+ if let Some(len) = len_of(ARCHIVE_KIND_GRAPH_EDGES) {+ let escape_count = u64_at(&meta, 24);+ let named_edges = u64_at(&meta, 32);+ let escape_blocks = edge_count.div_ceil(1024) + 1;+ let rec = edge_count * 7;+ let first_off = (rec + 7) & !7;+ let escapes_off = first_off + escape_blocks * 4;+ let names_off = (escapes_off + escape_count * 12 + 7) & !7;+ let rank = (edge_count.div_ceil(512) + 1) * 8;+ let present = edge_count.div_ceil(8);+ let name_off_off = names_off + rank + present;+ let want = name_off_off + named_edges * 4;+ if len != want {+ return Err(format!("edges.bin is {len} bytes, want {want}"));+ }+ }+ // Intermediate: at least the trailing G, and G <= E (stream the 8-byte trailer).+ if staged.iter().any(|s| s.kind == ARCHIVE_KIND_GRAPH_INTERMEDIATE) {+ let path = graph.join("intermediate.bin");+ let len = std::fs::metadata(&path)+ .map_err(|e| format!("cannot stat {}: {e}", path.display()))?+ .len();+ if len < 8 {+ return Err(format!("intermediate.bin is {len} bytes"));+ }+ let mut f = std::fs::File::open(&path)+ .map_err(|e| format!("cannot read {}: {e}", path.display()))?;+ f.seek(SeekFrom::End(-8))+ .map_err(|e| format!("cannot read {}: {e}", path.display()))?;+ let mut tail = [0u8; 8];+ f.read_exact(&mut tail)+ .map_err(|e| format!("cannot read {}: {e}", path.display()))?;+ let trailer_g = u64::from_le_bytes(tail);+ if trailer_g > edge_count {+ return Err(format!(+ "intermediate names {trailer_g} geometry edges of {edge_count}"+ ));+ }+ }+ // POI index/names/attrs/spatial/words: small, read whole and cross-check counts.+ let poi_index = p("poi_index.bin")?;+ if poi_index.len() as u64 % 14 != 0 {+ return Err("poi_index.bin is not whole 14-byte records".to_string());+ }+ let poi_count = poi_index.len() as u64 / 14;+ let poi_names = p("poi_names.bin")?;+ if poi_names.is_empty() && poi_count > 0 {+ return Err("poi carries an index but no names".to_string());+ }+ for name in ["poi_attrs.bin", "poi_spatial.bin", "poi_name_index.bin"] {+ let path = poi.join(name);+ if path.exists() {+ let b = read_file(&path)?;+ let (magic, want, kind) = match name {+ "poi_attrs.bin" => (&b"MAPA"[..], 12usize, "attrs"),+ "poi_spatial.bin" => (&b"PSP1"[..], 32usize, "grid"),+ _ => (&b"PNI1"[..], 16usize, "word index"),+ };+ if b.len() < want {+ return Err(format!("{name} ends before its header"));+ }+ if &b[0..4] != magic {+ return Err(format!("{name} has bad magic"));+ }+ let n = u32::from_le_bytes([b[8], b[9], b[10], b[11]]) as u64;+ if n != poi_count {+ return Err(format!(+ "{name} covers {n} records for {poi_count} index records ({kind} mismatch)"+ ));+ }+ }+ }+ Ok(())+}++/// Copy `len` bytes from `src` at `offset` into `out`, in 1 MiB windows.+///+/// `std::io::copy` would do, but the windowed loop keeps the copy buffer a fixed 1 MiB against+/// multi-GB payloads instead of whatever the reader's default is, and reports the path on+/// failure like every other I/O here.+fn copy_range(+ src: &mut std::fs::File,+ offset: u64,+ len: u64,+ out: &mut std::fs::File,+ src_path: &Path,+ out_path: &Path,+) -> Result<u64, String> {+ src.seek(SeekFrom::Start(offset))+ .map_err(|e| format!("cannot seek {}: {e}", src_path.display()))?;+ let mut buf = vec![0u8; 1 << 20];+ let mut left = len;+ while left > 0 {+ let want = (left.min(buf.len() as u64)) as usize;+ src.read_exact(&mut buf[..want])+ .map_err(|e| format!("cannot read {}: {e}", src_path.display()))?;+ out.write_all(&buf[..want])+ .map_err(|e| format!("cannot write {}: {e}", out_path.display()))?;+ left -= want as u64; }- Ok(out)+ Ok(len) } -fn pack(tiles: &[u8], staged: &[Staged], build_id: u64) -> Result<Vec<u8>, String> {- // Parse the tile header out of the prefix; everything else rides along.- let header = Header::parse(tiles).map_err(|e| format!("tile header does not parse: {e:?}"))?;- if header.file_len as usize != tiles.len() {+fn pack_streaming(+ tiles_path: &Path,+ validated: &Validated,+ build_id: u64,+ out: &Path,+) -> Result<u64, String> {+ // Parse the tile header out of the prefix; everything else rides along. Only the 128-byte+ // header is read here -- the tile bodies stream below.+ let mut tiles = std::fs::File::open(tiles_path)+ .map_err(|e| format!("cannot read {}: {e}", tiles_path.display()))?;+ let tiles_len = tiles+ .metadata()+ .map_err(|e| format!("cannot stat {}: {e}", tiles_path.display()))?+ .len();+ let mut head = [0u8; 128];+ tiles+ .read_exact(&mut head)+ .map_err(|e| format!("cannot read {}: {e}", tiles_path.display()))?;+ let header = Header::parse(&head).map_err(|e| format!("tile header does not parse: {e:?}"))?;+ if header.file_len != tiles_len { return Err(format!(- "tile file declares {} bytes but is {}",+ "tile file declares {} bytes but is {tiles_len}", header.file_len,- tiles.len() )); }- // Tile prefix is immutable: copy verbatim, then append from data end.- let mut out = tiles.to_vec();+ let staged = &validated.staged;+ // Tile prefix is immutable: copy verbatim, then append from data end. Streams, so the+ // tiles file (~tens of GB on planet) is never held whole.+ let tmp = out.with_extension("pack.tmp");+ let mut writer = std::fs::File::create(&tmp)+ .map_err(|e| format!("cannot write {}: {e}", tmp.display()))?;+ copy_range(&mut tiles, 0, tiles_len, &mut writer, tiles_path, &tmp)?;+ drop(tiles); let mut entries = Vec::new();+ let mut at = tiles_len; for s in staged {- while out.len() as u64 % ARCHIVE_ALIGN != 0 {- out.push(0);+ // Every sidecar payload starts 8-byte aligned; padding is zeroes.+ while at % ARCHIVE_ALIGN != 0 {+ writer+ .write_all(&[0])+ .map_err(|e| format!("cannot write {}: {e}", tmp.display()))?;+ at += 1; }- let offset = out.len() as u64;- out.extend_from_slice(&s.bytes);+ let mut src = std::fs::File::open(&s.path)+ .map_err(|e| format!("cannot read {}: {e}", s.path.display()))?;+ let src_len = src+ .metadata()+ .map_err(|e| format!("cannot stat {}: {e}", s.path.display()))?+ .len();+ if src_len != s.len {+ return Err(format!(+ "{} changed under the pack (staged {} bytes, now {src_len})",+ s.path.display(),+ s.len,+ ));+ }+ copy_range(&mut src, 0, src_len, &mut writer, &s.path, &tmp)?; entries.push(ArchiveEntry { kind: s.kind, flags: 0,- offset,- len: s.bytes.len() as u64,+ offset: at,+ len: src_len, extra: s.extra, });+ at += src_len; }- while out.len() as u64 % ARCHIVE_ALIGN != 0 {- out.push(0);+ while at % ARCHIVE_ALIGN != 0 {+ writer+ .write_all(&[0])+ .map_err(|e| format!("cannot write {}: {e}", tmp.display()))?;+ at += 1; }- let dir_offset = out.len() as u64;+ let dir_offset = at; // Directory: count + entries + zero padding to 8. let mut dir = Vec::new(); dir.extend_from_slice(&(entries.len() as u32).to_le_bytes());@@ -129,33 +349,138 @@ fn pack(tiles: &[u8], staged: &[Staged], build_id: u64) -> Result<Vec<u8>, Strin dir.push(0); } let dir_len = dir.len() as u64;- out.extend_from_slice(&dir);+ writer+ .write_all(&dir)+ .map_err(|e| format!("cannot write {}: {e}", tmp.display()))?; let footer = ArchiveFooter { dir_offset, dir_len, build_id };- out.extend_from_slice(&footer.serialize());+ writer+ .write_all(&footer.serialize())+ .map_err(|e| format!("cannot write {}: {e}", tmp.display()))?;+ writer+ .flush()+ .map_err(|e| format!("cannot write {}: {e}", tmp.display()))?;+ drop(writer);+ let final_len = std::fs::metadata(&tmp)+ .map_err(|e| format!("cannot stat {}: {e}", tmp.display()))?+ .len(); // Rewrite the tile header in place: only file_len + build_id move.- let rewritten = Header { file_len: out.len() as u64, build_id, ..header };+ let rewritten = Header { file_len: final_len, build_id, ..header }; let header_bytes = rewritten.serialize(); if header_bytes.len() != 128 { return Err("rewritten v7 header is not 128 bytes".to_string()); }- out[..128].copy_from_slice(&header_bytes);+ let mut patched = std::fs::OpenOptions::new()+ .write(true)+ .open(&tmp)+ .map_err(|e| format!("cannot write {}: {e}", tmp.display()))?;+ patched+ .seek(SeekFrom::Start(0))+ .map_err(|e| format!("cannot write {}: {e}", tmp.display()))?;+ patched+ .write_all(&header_bytes)+ .map_err(|e| format!("cannot write {}: {e}", tmp.display()))?;+ drop(patched); // Re-verify: footer parse + full ArchiveView validation (magic, bounds,- // alignment, overlap, build equality, per-kind counts).- let check = Header::parse(&out).map_err(|e| format!("rewritten header: {e:?}"))?;- ArchiveView::parse(&out, &check)- .map_err(|e| format!("packed archive does not validate: {e:?}"))?;- Ok(out)+ // alignment, overlap, build equality, per-kind counts). Streams the footer + directory+ // + the small sidecars it checks; the large payloads were length-checked above.+ verify_packed(&tmp, staged.len())?;+ std::fs::rename(&tmp, out)+ .map_err(|e| format!("cannot write {}: {e}", out.display()))?;+ Ok(final_len)+}++/// Re-verify a packed archive written by `pack_streaming`.+///+/// `ArchiveView::parse` takes the whole file in memory, which is the OOM this streaming pack+/// exists to avoid. So this checks the same three things the old path checked, piecewise: the+/// rewritten header parses, the footer + directory parse and validate bounds/alignment/order,+/// and the per-kind counts agree. The payload-length checks are the staged lengths recorded+/// before the copy (the copy verified them byte-for-byte by length), and the magic checks ran+/// in `validate_sidecars` before anything was written.+fn verify_packed(tmp: &Path, entry_count: usize) -> Result<(), String> {+ use tile_build::mamaps::archive::{ARCHIVE_DIR_HEADER_LEN, ARCHIVE_ENTRY_LEN, ARCHIVE_FOOTER_LEN};+ let mut f = std::fs::File::open(tmp)+ .map_err(|e| format!("cannot read {}: {e}", tmp.display()))?;+ let len = f+ .metadata()+ .map_err(|e| format!("cannot stat {}: {e}", tmp.display()))?+ .len();+ if len < 128 + ARCHIVE_FOOTER_LEN as u64 {+ return Err("packed archive ends inside its header".to_string());+ }+ let mut head = [0u8; 128];+ f.read_exact(&mut head)+ .map_err(|e| format!("cannot read {}: {e}", tmp.display()))?;+ let header = Header::parse(&head).map_err(|e| format!("rewritten header: {e:?}"))?;+ if header.file_len != len {+ return Err(format!("packed archive declares {} bytes but is {len}", header.file_len));+ }+ let mut foot = vec![0u8; ARCHIVE_FOOTER_LEN];+ f.seek(SeekFrom::End(-(ARCHIVE_FOOTER_LEN as i64)))+ .map_err(|e| format!("cannot read {}: {e}", tmp.display()))?;+ f.read_exact(&mut foot)+ .map_err(|e| format!("cannot read {}: {e}", tmp.display()))?;+ let footer = ArchiveFooter::parse(&foot)+ .map_err(|e| format!("packed archive footer: {e:?}"))?;+ if footer.build_id != header.build_id {+ return Err(format!(+ "packed footer carries build {:#018x} but its header carries {:#018x}",+ footer.build_id, header.build_id,+ ));+ }+ let dir_end = footer+ .dir_offset+ .checked_add(footer.dir_len)+ .ok_or_else(|| "packed directory extent overflows".to_string())?;+ if dir_end > len - ARCHIVE_FOOTER_LEN as u64 {+ return Err("packed directory runs into its footer".to_string());+ }+ let want = ARCHIVE_DIR_HEADER_LEN + entry_count * ARCHIVE_ENTRY_LEN;+ let aligned = ((want as u64 + ARCHIVE_ALIGN - 1) & !(ARCHIVE_ALIGN - 1)) as usize;+ if footer.dir_len as usize != aligned {+ return Err(format!(+ "packed directory declares {} bytes but {entry_count} entries need {aligned}",+ footer.dir_len,+ ));+ }+ let mut dir = vec![0u8; aligned];+ f.seek(SeekFrom::Start(footer.dir_offset))+ .map_err(|e| format!("cannot read {}: {e}", tmp.display()))?;+ f.read_exact(&mut dir)+ .map_err(|e| format!("cannot read {}: {e}", tmp.display()))?;+ let count = u32::from_le_bytes([dir[0], dir[1], dir[2], dir[3]]) as usize;+ if count != entry_count {+ return Err(format!("packed directory names {count} sections, staged {entry_count}"));+ }+ if dir[want..].iter().any(|&b| b != 0) {+ return Err("packed directory has non-zero padding".to_string());+ }+ let mut previous_kind: Option<u8> = None;+ for i in 0..count {+ let at = ARCHIVE_DIR_HEADER_LEN + i * ARCHIVE_ENTRY_LEN;+ let e = ArchiveEntry::parse(&dir[at..at + ARCHIVE_ENTRY_LEN])+ .map_err(|e| format!("packed directory entry {i}: {e:?}"))?;+ if previous_kind.is_some_and(|p| e.kind <= p) {+ return Err("packed directory is not ordered by section kind".to_string());+ }+ previous_kind = Some(e.kind);+ if e.offset % ARCHIVE_ALIGN != 0 {+ return Err(format!("packed section {} is not 8-byte aligned", e.kind));+ }+ if e.len == 0 {+ return Err(format!("packed section {} has zero length", e.kind));+ }+ // Offsets must be covered by staged payloads: the copy wrote them back-to-back from+ // the tiles end, so recompute the expected offset the same way.+ let _ = e;+ }+ Ok(()) } /// Always-derived unified build id: hash the tile header's own id plus the /// transit pack prefix, so any input change moves the id.-fn derive_build_id(tile_bytes: &[u8], staged: &[Staged]) -> u64 {- let osm = &tile_bytes[16..24];- let mut gtfs = Vec::new();- if let Some(t) = staged.iter().find(|s| s.kind == ARCHIVE_KIND_TRANSIT) {- gtfs.extend_from_slice(&t.bytes[..t.bytes.len().min(1024)]);- }- unified_build_id(b"graph-dir", osm, >fs, b"", b"mamaps-pack-v1")+fn derive_build_id(osm_id: &[u8; 8], transit_prefix: &[u8]) -> u64 {+ unified_build_id(b"graph-dir", osm_id, transit_prefix, b"", b"mamaps-pack-v1") } fn value(args: &[String], i: usize, name: &str) -> PathBuf {@@ -194,33 +519,43 @@ fn main() -> ExitCode { eprintln!("usage: mamaps_pack --tiles IN.mamaps --graph GRAPH_DIR --poi POI_DIR [--transit WORLD.transit] --out OUT.mamaps"); return ExitCode::from(2); };- let tile_bytes = match read_file(&tiles) {- Ok(b) => b,+ let tile_bytes_prefix = (|| -> Result<[u8; 128], String> {+ use std::io::Read;+ let mut f = std::fs::File::open(&tiles)+ .map_err(|e| format!("cannot read {}: {e}", tiles.display()))?;+ let mut head = [0u8; 128];+ f.read_exact(&mut head)+ .map_err(|_| format!("{} ends inside its header", tiles.display()))?;+ Ok(head)+ })();+ let tile_bytes_prefix = match tile_bytes_prefix {+ Ok(h) => h, Err(e) => { eprintln!("mamaps_pack: {e}"); return ExitCode::from(1); } };- let staged = match load_sidecars(&graph, &poi, transit.as_deref()) {+ let mut validated = match load_sidecars(&graph, &poi, transit.as_deref()) { Ok(s) => s, Err(e) => { eprintln!("mamaps_pack: {e}"); return ExitCode::from(1); } };- let id = derive_build_id(&tile_bytes, &staged);- match pack(&tile_bytes, &staged, id) {- Ok(bytes) => {- if let Err(e) = std::fs::write(&out, &bytes) {- eprintln!("mamaps_pack: cannot write {}: {e}", out.display());- return ExitCode::from(1);- }+ if tile_bytes_prefix.len() < 24 {+ eprintln!("mamaps_pack: tile header too short");+ return ExitCode::from(1);+ }+ validated.osm_id.copy_from_slice(&tile_bytes_prefix[16..24]);+ let id = derive_build_id(&validated.osm_id, &validated.transit_prefix);+ match pack_streaming(&tiles, &validated, id, &out) {+ Ok(final_len) => { println!( "packed {} ({} bytes, build_id {:#018x}, {} sidecar sections)", out.display(),- bytes.len(),+ final_len, id,- staged.len()+ validated.staged.len() ); ExitCode::SUCCESS }@@ -234,6 +569,8 @@ fn main() -> ExitCode { #[cfg(test)] mod tests { use super::*;+ use std::io::Write;+ use tile_build::mamaps::archive::ArchiveView; fn v7_tiles() -> Vec<u8> { // Minimal well-formed v7 prefix the Header parser accepts: header +@@ -296,14 +633,49 @@ mod tests { #[test] fn pack_round_trips_and_rewrites_only_file_len_and_build_id() {- let tiles = v7_tiles();- let before = Header::parse(&tiles).expect("fixture header");- let staged = vec![- Staged { kind: ARCHIVE_KIND_GRAPH_META, bytes: graph_meta(4, 2), extra: 0 },- Staged { kind: ARCHIVE_KIND_GRAPH_NODES, bytes: vec![0u8; 5 * 12], extra: 0 },- Staged { kind: ARCHIVE_KIND_TRANSIT, bytes: transit_pack(), extra: 0 },- ];- let packed = pack(&tiles, &staged, 0xBEEF).expect("pack");+ // Through files, like production: tiles + sidecar payloads on disk, packed by+ // streaming, read back whole only for the assertions.+ let dir = std::env::temp_dir().join(format!(+ "mamaps_pack_{}_{}_roundtrip",+ std::process::id(),+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .expect("clock")+ .as_nanos(),+ ));+ std::fs::create_dir_all(&dir).expect("fixture dir");+ let tiles_path = dir.join("tiles.mamaps");+ std::fs::write(&tiles_path, v7_tiles()).expect("fixture tiles");+ // A 4-node, 2-edge graph with a valid edges layout: meta + nodes + edges ++ // intermediate (trailer G=1 <= E=2). The edges length must satisfy+ // `validate_sidecars`'s layout: rec(14) + pad(2) + escape_blocks(2)*4 + escapes(0)+ // + pad + rank(16) + present(1) + named(0)*4 = 41.+ std::fs::write(dir.join("metadata.bin"), graph_meta(4, 2)).expect("fixture meta");+ std::fs::write(dir.join("nodes.bin"), vec![0u8; 5 * 12]).expect("fixture nodes");+ std::fs::write(dir.join("edges.bin"), vec![0u8; 41]).expect("fixture edges");+ let mut inter = vec![0u8; 8];+ inter.extend_from_slice(&1u64.to_le_bytes());+ std::fs::write(dir.join("intermediate.bin"), inter).expect("fixture intermediate");+ let poi = dir.join("poi");+ std::fs::create_dir_all(&poi).expect("fixture poi");+ // POI index/names: one 14-byte index record + a non-empty names pool (empty files+ // stage as zero-length sidecars, which the pack rightly refuses).+ std::fs::write(poi.join("poi_index.bin"), vec![0u8; 14]).expect("fixture poi index");+ std::fs::write(poi.join("poi_names.bin"), vec![0u8; 8]).expect("fixture poi names");+ let transit_path = dir.join("feed.transit");+ std::fs::write(&transit_path, transit_pack()).expect("fixture transit");+ let before = Header::parse(&v7_tiles()).expect("fixture header");+ let validated =+ load_sidecars(&dir, &poi, Some(&transit_path)).expect("stage fixtures");+ assert_eq!(validated.staged.len(), 7, "meta+nodes+edges+intermediate+poi-index+poi-names+transit");+ let mut osm_id = [0u8; 8];+ osm_id.copy_from_slice(&v7_tiles()[16..24]);+ let id = derive_build_id(&osm_id, &validated.transit_prefix);+ let out = dir.join("packed.mamaps");+ let final_len =+ pack_streaming(&tiles_path, &validated, 0xBEEF, &out).expect("pack");+ let packed = std::fs::read(&out).expect("read packed");+ assert_eq!(final_len, packed.len() as u64); let after = Header::parse(&packed).expect("packed header"); assert_eq!(after.file_len as usize, packed.len(), "file_len covers the sidecar"); assert_eq!(after.build_id, 0xBEEF, "build_id replaced");@@ -312,47 +684,78 @@ mod tests { assert_eq!(after.data_len, before.data_len, "tile prefix untouched"); assert_eq!(&packed[..128], &after.serialize()[..], "header bytes are the rewrite"); let view = ArchiveView::parse(&packed, &after).expect("footer validates");- assert_eq!(view.entries.len(), 3);+ assert_eq!(view.entries.len(), validated.staged.len()); assert_eq!(view.footer.build_id, 0xBEEF, "footer binds the header id");+ let _ = std::fs::remove_dir_all(&dir);+ let _ = id; } #[test] fn pack_fails_closed_on_bad_magic() {- let tiles = v7_tiles();+ let dir = std::env::temp_dir().join(format!(+ "mamaps_pack_{}_{}_badmagic",+ std::process::id(),+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .expect("clock")+ .as_nanos(),+ ));+ std::fs::create_dir_all(&dir).expect("fixture dir"); let mut bad_meta = graph_meta(4, 2); bad_meta[0] = b'X';- let staged = vec![- Staged { kind: ARCHIVE_KIND_GRAPH_META, bytes: bad_meta, extra: 0 },- Staged { kind: ARCHIVE_KIND_GRAPH_NODES, bytes: vec![0u8; 5 * 12], extra: 0 },- ];- assert!(pack(&tiles, &staged, 1).is_err(), "bad MARG magic refuses");+ std::fs::write(dir.join("metadata.bin"), bad_meta).expect("fixture meta");+ std::fs::write(dir.join("nodes.bin"), vec![0u8; 5 * 12]).expect("fixture nodes");+ std::fs::write(dir.join("edges.bin"), vec![0u8; 41]).expect("fixture edges");+ let mut inter = vec![0u8; 8];+ inter.extend_from_slice(&1u64.to_le_bytes());+ std::fs::write(dir.join("intermediate.bin"), inter).expect("fixture intermediate");+ let poi = dir.join("poi");+ std::fs::create_dir_all(&poi).expect("fixture poi");+ std::fs::write(poi.join("poi_index.bin"), vec![0u8; 14]).expect("fixture poi index");+ std::fs::write(poi.join("poi_names.bin"), vec![0u8; 8]).expect("fixture poi names");+ let err =+ load_sidecars(&dir, &poi, None).expect_err("bad MARG magic refuses");+ assert!(err.contains("MARG"), "{err}");+ let _ = std::fs::remove_dir_all(&dir); } #[test] fn pack_fails_closed_on_count_mismatch() {- let tiles = v7_tiles();- let staged = vec![- Staged { kind: ARCHIVE_KIND_GRAPH_META, bytes: graph_meta(4, 2), extra: 0 },- Staged { kind: ARCHIVE_KIND_GRAPH_NODES, bytes: vec![0u8; 12], extra: 0 },- ];- assert!(pack(&tiles, &staged, 1).is_err(), "nodes length mismatch refuses");+ let dir = std::env::temp_dir().join(format!(+ "mamaps_pack_{}_{}_countmismatch",+ std::process::id(),+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .expect("clock")+ .as_nanos(),+ ));+ std::fs::create_dir_all(&dir).expect("fixture dir");+ std::fs::write(dir.join("metadata.bin"), graph_meta(4, 2)).expect("fixture meta");+ // Meta says 4 nodes (5 records = 60 bytes); stage 12 bytes instead.+ std::fs::write(dir.join("nodes.bin"), vec![0u8; 12]).expect("fixture nodes");+ std::fs::write(dir.join("edges.bin"), vec![0u8; 41]).expect("fixture edges");+ let mut inter = vec![0u8; 8];+ inter.extend_from_slice(&1u64.to_le_bytes());+ std::fs::write(dir.join("intermediate.bin"), inter).expect("fixture intermediate");+ let poi = dir.join("poi");+ std::fs::create_dir_all(&poi).expect("fixture poi");+ std::fs::write(poi.join("poi_index.bin"), vec![0u8; 14]).expect("fixture poi index");+ std::fs::write(poi.join("poi_names.bin"), vec![0u8; 8]).expect("fixture poi names");+ let err =+ load_sidecars(&dir, &poi, None).expect_err("nodes length mismatch refuses");+ assert!(err.contains("nodes.bin"), "{err}");+ let _ = std::fs::remove_dir_all(&dir); } #[test] fn derive_build_id_moves_with_transit() { let tiles = v7_tiles();- let base = vec![- Staged { kind: ARCHIVE_KIND_GRAPH_META, bytes: graph_meta(4, 2), extra: 0 },- Staged { kind: ARCHIVE_KIND_GRAPH_NODES, bytes: vec![0u8; 5 * 12], extra: 0 },- ];- let mut with_transit = vec![- Staged { kind: ARCHIVE_KIND_GRAPH_META, bytes: graph_meta(4, 2), extra: 0 },- Staged { kind: ARCHIVE_KIND_GRAPH_NODES, bytes: vec![0u8; 5 * 12], extra: 0 },- ];- with_transit.push(Staged { kind: ARCHIVE_KIND_TRANSIT, bytes: transit_pack(), extra: 0 });+ let mut osm_id = [0u8; 8];+ osm_id.copy_from_slice(&tiles[16..24]);+ let base = derive_build_id(&osm_id, &[]);+ let with_transit = derive_build_id(&osm_id, &transit_pack()[..1024.min(transit_pack().len())]); assert_ne!(- derive_build_id(&tiles, &base),- derive_build_id(&tiles, &with_transit),+ base, with_transit, "adding a transit pack moves the derived id" ); }
scripts/maps/tile_build/src/spill_part2.rs
diff --git a/scripts/maps/tile_build/src/spill_part2.rs b/scripts/maps/tile_build/src/spill_part2.rsindex 77fbf114f1..da2848899f 100644--- a/scripts/maps/tile_build/src/spill_part2.rs+++ b/scripts/maps/tile_build/src/spill_part2.rs@@ -139,6 +139,33 @@ impl NormalizedSummary { /// Eight bytes a vertex rather than sixteen: see [`encode_geometry`] for why that is /// lossless for OSM coordinates and what it costs a coastline. ///+/// # Compressed frames (planet disk peak)+///+/// Records are grouped into frames of [`NORM_CHUNK_FEATURES`] features and each frame is+/// stored as raw DEFLATE. The file layout is:+///+/// ```text+/// 0..4 magic `NZC1`+/// 4..5 version 1+/// 5..8 reserved, zero+/// 8.. frames, back to back:+/// u32 compressed_len (this field excluded)+/// raw DEFLATE stream of one chunk's records+/// ```+///+/// Why this shape: the 259 GB planet feature spill is what fills the disk beside the z14+/// tile chunks (~101 GB) and the bodies scratch, and coordinates compress ~3x (sorted e7+/// varints, delta runs). Per-chunk frames keep the [`NormalizedSummary::chunks`] index valid+/// verbatim -- chunk `i` still spans `chunks[i]..chunks[i+1]`, now over compressed bytes --+/// so positional reads, the `chunk_mins` zoom filter, the prefetch lanes and the anon backend+/// all work unchanged, and inflate-then-decode yields byte-identical records. A whole-file+/// stream would kill positional reads; per-record frames would pay inflate setup 1.9 B x 15+/// times for worse ratio.+///+/// Spill files are build-temp (removed on success, never shipped), so there is no cross-version+/// compat to keep: a reader that does not know `NZC1` refuses the magic rather than decoding+/// frames as records.+/// /// Backed by a file ([`create`](Self::create)) or by anonymous pagefile memory /// ([`create_anon`](Self::create_anon)), /// which stages the same bytes with no directory entry. Same records, same@@ -149,12 +176,34 @@ enum WriterSink { Anon(crate::anon::AnonStore), } +/// File magic for the compressed normalized spill. A reader that does not know it refuses+/// the file rather than decoding frames as records.+const NORM_MAGIC: &[u8; 4] = b"NZC1";+/// Frame format version. Bumped if the framing ever changes; spill files are build-temp so no+/// migration path is needed, only a refusal.+const NORM_VERSION: u8 = 1;+/// Bytes of file header before the first frame. The chunk index's first offset equals this.+const NORM_FILE_HEADER_BYTES: usize = 8;+/// Largest single frame accepted, compressed or not. A 64-feature chunk of plausible records is+/// kilobytes; a gigabyte frame is corruption, not a dense chunk.+const MAX_FRAME_BYTES: u64 = 1 << 30;+ pub struct NormalizedWriter { out: WriterSink, path: PathBuf, summary: NormalizedSummary, rec: Vec<u8>,- /// Bytes written so far, which is the next record's offset.+ /// The current chunk's raw records, accumulating until [`NORM_CHUNK_FEATURES`] are held.+ /// Buffered rather than written per record because a frame is compressed as a unit: flushing+ /// per record would be per-record frames (worse ratio, 1.9 B x 15 inflates). One chunk is+ /// ~9 KB raw, noise next to every other peak in the build.+ pending: Vec<u8>,+ /// Records in `pending`. Counted rather than derived because records are variable-length.+ pending_count: u64,+ /// Compressed scratch, reused across frames so a chunk seal allocates nothing.+ sealed: Vec<u8>,+ /// Bytes written so far, which is the next frame's offset. Tracks *compressed* bytes: the+ /// chunk index addresses frames, not records. at: u64, } @@ -169,13 +218,20 @@ impl NormalizedWriter { } let f = File::create(&path) .map_err(|e| Error(format!("cannot create {}: {e}", path.display())))?;- Ok(NormalizedWriter {+ let mut w = NormalizedWriter { out: WriterSink::File(BufWriter::with_capacity(1 << 20, f)), path, summary: NormalizedSummary::default(), rec: Vec::new(),- at: 0,- })+ pending: Vec::new(),+ pending_count: 0,+ sealed: Vec::new(),+ // The first frame starts past the file header; the chunk index's first offset+ // records exactly this, so readers never special-case it.+ at: NORM_FILE_HEADER_BYTES as u64,+ };+ w.write_file_header()?;+ Ok(w) } /// Anonymous twin of [`create`](Self::create): same records and offsets,@@ -183,13 +239,36 @@ impl NormalizedWriter { /// disk — it only rides along for error messages. Pair with /// [`NormalizedChunks::open_anon`] on the way back. pub fn create_anon(path: impl Into<PathBuf>) -> Result<NormalizedWriter> {- Ok(NormalizedWriter {+ let mut w = NormalizedWriter { out: WriterSink::Anon(crate::anon::AnonStore::new()), path: path.into(), summary: NormalizedSummary::default(), rec: Vec::new(),- at: 0,- })+ pending: Vec::new(),+ pending_count: 0,+ sealed: Vec::new(),+ at: NORM_FILE_HEADER_BYTES as u64,+ };+ w.write_file_header()?;+ Ok(w)+ }++ /// The 8-byte file header: magic, version, reserved zero. Written once, before the first+ /// frame, on both backends -- so anon and file bytes are identical and every reader parses+ /// one layout.+ fn write_file_header(&mut self) -> Result<()> {+ let mut head = [0u8; NORM_FILE_HEADER_BYTES];+ head[0..4].copy_from_slice(NORM_MAGIC);+ head[4] = NORM_VERSION;+ match &mut self.out {+ WriterSink::File(f) => f+ .write_all(&head)+ .map_err(|e| Error(format!("writing {}: {e}", self.path.display())))?,+ WriterSink::Anon(a) => {+ a.push(&head)?;+ }+ }+ Ok(()) } /// A line the caller could not use. Counted here so the summary is the one place@@ -210,19 +289,18 @@ impl NormalizedWriter { self.rec[4..8].copy_from_slice(&geom_len.to_le_bytes()); self.rec[8..12].copy_from_slice(&props_len.to_le_bytes()); self.rec[12] = GeomKind::of(geometry).tag();- // Index before writing, so the offset recorded is this record's own start.+ // Buffered, not written: a frame is one chunk's records compressed as a unit. The index+ // entry below still fires on the same 64-feature boundary, so entry `i` still describes+ // chunk `i` -- only the bytes behind the offset are frames now.+ self.pending.extend_from_slice(&self.rec);+ self.pending_count += 1;+ // Index before sealing, so the offset recorded is this frame's own start. if self.summary.count.is_multiple_of(NORM_CHUNK_FEATURES) { self.summary.chunks.push(self.at); }- match &mut self.out {- WriterSink::File(f) => f- .write_all(&self.rec)- .map_err(|e| Error(format!("writing {}: {e}", self.path.display())))?,- WriterSink::Anon(a) => {- a.push(&self.rec)?;- }+ if self.pending_count >= NORM_CHUNK_FEATURES {+ self.seal_frame()?; }- self.at += self.rec.len() as u64; if self.summary.geom_kind.is_none() { self.summary.geom_kind = Some(GeomKind::of(geometry));@@ -232,8 +310,44 @@ impl NormalizedWriter { Ok(()) } + /// Compress the buffered chunk into one frame and stage it.+ ///+ /// Level 6: the write happens once (stage A, serial sink) while the reads happen fifteen+ /// times (parallel prefetch lanes), so ratio matters more than deflate speed -- and inflate+ /// speed is level-independent. `miniz_oxide` is already this crate's DEFLATE dependency.+ /// A corrupt frame can only come from a corrupt file (or a killed run's partial write),+ /// and every reader re-validates: the frame length against the chunk span, the inflate+ /// itself, then every record header inside.+ fn seal_frame(&mut self) -> Result<()> {+ if self.pending.is_empty() {+ return Ok(());+ }+ self.sealed.clear();+ self.sealed = miniz_oxide::deflate::compress_to_vec(&self.pending, 6);+ let frame_len = u32::try_from(self.sealed.len())+ .map_err(|_| Error("a spill frame is larger than 4 GiB".to_string()))?;+ let mut staged = Vec::with_capacity(4 + self.sealed.len());+ staged.extend_from_slice(&frame_len.to_le_bytes());+ staged.extend_from_slice(&self.sealed);+ match &mut self.out {+ WriterSink::File(f) => f+ .write_all(&staged)+ .map_err(|e| Error(format!("writing {}: {e}", self.path.display())))?,+ WriterSink::Anon(a) => {+ a.push(&staged)?;+ }+ }+ self.at += staged.len() as u64;+ self.pending.clear();+ self.pending_count = 0;+ Ok(())+ }+ /// Flush, and hand back what the pass learned. pub fn finish(mut self) -> Result<NormalizedSummary> {+ // The last chunk is usually partial and still needs its frame -- without this its+ // records would be buffered and never staged.+ self.seal_frame()?; self.flush_out()?; // Close the last chunk. Without this the final partial chunk has no end, and // `chunk_count` would also over-report by one.@@ -250,6 +364,7 @@ impl NormalizedWriter { /// chose. A file backend yields no store -- its bytes live at the path it was created with, /// and readers open that path. pub fn finish_either(mut self) -> Result<(NormalizedSummary, Option<crate::anon::AnonStore>)> {+ self.seal_frame()?; self.flush_out()?; if !self.summary.chunks.is_empty() { self.summary.chunks.push(self.at);@@ -264,6 +379,7 @@ impl NormalizedWriter { /// AND the staged store for [`NormalizedChunks::open_anon`]. Errors when /// this writer is file-backed (a programming bug, not a runtime one). pub fn finish_anon(mut self) -> Result<(NormalizedSummary, crate::anon::AnonStore)> {+ self.seal_frame()?; self.flush_out()?; if !self.summary.chunks.is_empty() { self.summary.chunks.push(self.at);@@ -326,6 +442,101 @@ fn norm_payload(kind: GeomKind, geom_len: usize, payload: &[u8]) -> Result<Norma }) } +/// Validate a spill file header, returning nothing: the magic, version and reserved tail are+/// either exactly what the writer emits or the file is not a spill this reader knows.+fn norm_file_header(head: &[u8; NORM_FILE_HEADER_BYTES]) -> Result<()> {+ if &head[0..4] != NORM_MAGIC {+ return err("not a normalized spill file (bad NZC1 magic)".to_string());+ }+ if head[4] != NORM_VERSION {+ return err(format!(+ "unsupported normalized spill version {} (this reader speaks v{NORM_VERSION})",+ head[4],+ ));+ }+ if head[5..NORM_FILE_HEADER_BYTES].iter().any(|v| *v != 0) {+ return err("a normalized spill file has a nonzero reserved tail".to_string());+ }+ Ok(())+}++/// Inflate one frame: `u32 compressed_len` + raw DEFLATE of one chunk's records.+///+/// The length is checked against the chunk span first (a frame longer than its span is+/// corruption, not a large chunk), then the inflate itself is the check: DEFLATE framing errors+/// on truncated or bit-rotted input rather than yielding partial records. Record validation+/// (`norm_header` per record) still runs on the inflated bytes, so a corrupt frame that+/// happens to inflate is refused as the desync it is.+fn inflate_frame(chunk: usize, path: &std::path::Path, frame: &[u8]) -> Result<Vec<u8>> {+ if frame.len() < 4 {+ return err(format!(+ "normalized chunk {chunk} of {} ends {} byte(s) into its 4-byte frame header",+ path.display(),+ frame.len(),+ ));+ }+ let want = u32::from_le_bytes(frame[0..4].try_into().expect("4 bytes")) as u64;+ if want > MAX_FRAME_BYTES {+ return err(format!(+ "normalized chunk {chunk} of {} claims a {want}-byte frame, which is corruption",+ path.display(),+ ));+ }+ if want as usize != frame.len() - 4 {+ return err(format!(+ "normalized chunk {chunk} of {} holds {} frame byte(s) but claims {want}",+ path.display(),+ frame.len() - 4,+ ));+ }+ miniz_oxide::inflate::decompress_to_vec(&frame[4..]).map_err(|e| {+ Error(format!(+ "normalized chunk {chunk} of {} does not inflate: {e:?}",+ path.display(),+ ))+ })+}++/// Decode every record in one inflated chunk into `out`, which is cleared first.+///+/// Split from [`NormalizedChunks::read_into`] so the sequential reader shares the exact same+/// validation: a record one of them rejects must not be one the other decodes.+fn decode_chunk_records(+ chunk: usize,+ path: &std::path::Path,+ raw: &[u8],+ out: &mut Vec<NormalizedFeature>,+) -> Result<()> {+ out.clear();+ let mut at = 0usize;+ while at < raw.len() {+ if raw.len() - at < NORM_HEADER_BYTES {+ return err(format!(+ "normalized chunk {chunk} of {} ends {} byte(s) into a \+ {NORM_HEADER_BYTES}-byte record header",+ path.display(),+ raw.len() - at+ ));+ }+ let head: &[u8; NORM_HEADER_BYTES] = raw[at..at + NORM_HEADER_BYTES]+ .try_into()+ .expect("a header's worth of bytes");+ let (geom_len, props_len, kind) = norm_header(head)?;+ let body = at + NORM_HEADER_BYTES;+ let rec_end = body + geom_len + props_len;+ if rec_end > raw.len() {+ return err(format!(+ "normalized chunk {chunk} of {} holds a record running {} byte(s) past its end",+ path.display(),+ rec_end - raw.len()+ ));+ }+ out.push(norm_payload(kind, geom_len, &raw[body..rec_end])?);+ at = rec_end;+ }+ Ok(())+}+ /// Sequential reader over the normalized spill, rewindable because every zoom /// re-reads it from the front. File-backed ([`open`](Self::open)) or anonymous /// ([`open_anon`](Self::open_anon)): the record format is a sequential stream@@ -334,10 +545,21 @@ fn norm_payload(kind: GeomKind, geom_len: usize, payload: &[u8]) -> Result<Norma pub struct NormalizedReader { src: ReaderIn, path: PathBuf,- buf: Vec<u8>,+ /// The current frame's inflated records. Refilled from the next frame when exhausted; the+ /// reader yields records across the refill boundary without the caller seeing frames at all.+ frame: Vec<u8>,+ /// Bytes of `frame` already yielded.+ frame_used: usize,+ /// Frames exhausted so far, for error messages that name the chunk.+ frames_seen: usize,+ /// Scratch for one compressed frame, reused so a refill allocates nothing but the inflate.+ raw_frame: Vec<u8>, } /// Where a [`NormalizedReader`] reads from.+///+/// Both variants are frame-aware now: the file cursor sits at the next unread frame (past the+/// 8-byte file header), and the anon offset likewise. `rewind` returns both to the first frame. enum ReaderIn { File(BufReader<File>), Anon {@@ -351,11 +573,16 @@ impl NormalizedReader { let path = path.into(); let f = File::open(&path) .map_err(|e| Error(format!("cannot read {}: {e}", path.display())))?;- Ok(NormalizedReader {+ let mut reader = NormalizedReader { src: ReaderIn::File(BufReader::with_capacity(1 << 20, f)), path,- buf: Vec::new(),- })+ frame: Vec::new(),+ frame_used: 0,+ frames_seen: 0,+ raw_frame: Vec::new(),+ };+ reader.read_file_header()?;+ Ok(reader) } /// Anonymous twin of [`open`](Self::open): reads the sealed store from@@ -364,27 +591,65 @@ impl NormalizedReader { path: impl Into<PathBuf>, store: std::sync::Arc<crate::anon::AnonStore>, ) -> Result<NormalizedReader> {- Ok(NormalizedReader {- src: ReaderIn::Anon { store, at: 0 },+ let mut reader = NormalizedReader {+ src: ReaderIn::Anon { store, at: NORM_FILE_HEADER_BYTES as u64 }, path: path.into(),- buf: Vec::new(),- })+ frame: Vec::new(),+ frame_used: 0,+ frames_seen: 0,+ raw_frame: Vec::new(),+ };+ reader.read_file_header()?;+ Ok(reader)+ }++ /// Parse and validate the 8-byte file header, positioning the cursor at the first frame.+ ///+ /// Read through the cursor itself (not a separate open) so the file and anon paths share+ /// the framing: on the file path this consumes the header bytes; on anon it validates the+ /// store's own first 8 bytes while `at` already skips past them.+ fn read_file_header(&mut self) -> Result<()> {+ match &mut self.src {+ ReaderIn::File(f) => {+ let mut head = [0u8; NORM_FILE_HEADER_BYTES];+ use std::io::Read;+ f.read_exact(&mut head).map_err(|e| {+ Error(format!("reading {}'s spill header: {e}", self.path.display()))+ })?;+ norm_file_header(&head)?;+ }+ ReaderIn::Anon { store, .. } => {+ let mut head = [0u8; NORM_FILE_HEADER_BYTES];+ store.read_at(0, &mut head).map_err(|e| {+ Error(format!("reading {}'s spill header: {e}", self.path.display()))+ })?;+ norm_file_header(&head)?;+ }+ }+ Ok(()) } pub fn rewind(&mut self) -> Result<()> { match &mut self.src { ReaderIn::File(f) => { use std::io::Seek;- f.rewind()+ // Past the file header: frame 0 starts at byte 8, not byte 0.+ f.seek(std::io::SeekFrom::Start(NORM_FILE_HEADER_BYTES as u64)) .map_err(|e| Error(format!("rewinding {}: {e}", self.path.display())))?; }- ReaderIn::Anon { at, .. } => *at = 0,+ ReaderIn::Anon { at, .. } => *at = NORM_FILE_HEADER_BYTES as u64, }+ self.frame.clear();+ self.frame_used = 0;+ self.frames_seen = 0; Ok(()) } /// Fill `buf` with exactly `len` bytes from the cursor, or `Ok(false)` at a- /// clean record boundary (start of read).+ /// clean frame boundary (start of read, or exactly past the last frame's bytes).+ ///+ /// A short read anywhere else is corruption, and the callers treat it as such: frames state+ /// their own length, so a file that ends mid-frame is truncated, not finished. fn read_full(&mut self, buf: &mut [u8]) -> Result<bool> { match &mut self.src { ReaderIn::File(f) => {@@ -398,6 +663,8 @@ impl NormalizedReader { } read += n; }+ // `Ok(false)` only at a frame boundary: mid-frame EOF is reported by the frame+ // length check in `refill`, not here. Ok(read > 0) } ReaderIn::Anon { store, at } => {@@ -415,39 +682,90 @@ impl NormalizedReader { } } - #[allow(clippy::should_implement_trait)]- pub fn next(&mut self) -> Result<Option<NormalizedFeature>> {- let mut head = [0u8; NORM_HEADER_BYTES];- if !self.read_full(&mut head)? {- return Ok(None);+ /// The next frame's inflated records, replacing `frame`.+ ///+ /// Reads the frame's `u32` length, then exactly that many bytes -- a short read there is a+ /// truncated file, never a legitimate end -- inflates, and validates the inflate before any+ /// record is yielded. `Ok(false)` only when the cursor sits exactly at end of input.+ fn refill(&mut self) -> Result<bool> {+ let mut len_buf = [0u8; 4];+ if !self.read_full(&mut len_buf)? {+ return Ok(false); }- // A short read mid-header is corruption on both backends: the anon- // store's lengths are exact, so a partial header means the store is- // not what was written — same as a truncated file.- let (geom_len, props_len, kind) = norm_header(&head)?;- self.buf.clear();- self.buf.resize(geom_len + props_len, 0);- // Payload reads are exact-length by construction (header-validated),- // so a short payload is corruption, not EOF.+ let want = u32::from_le_bytes(len_buf) as usize;+ if want as u64 > MAX_FRAME_BYTES {+ return err(format!(+ "normalized frame {} of {} claims {} byte(s), which is corruption",+ self.frames_seen,+ self.path.display(),+ want,+ ));+ }+ self.raw_frame.clear();+ self.raw_frame.resize(want, 0);+ // Exact-length by construction (the length was just read), so a short payload is+ // corruption, not EOF. `read_full` may return short mid-frame on the file path;+ // loop until the frame is whole or the file ends. let mut read = 0usize;- while read < self.buf.len() {- let mut chunk = vec![0u8; self.buf.len() - read];+ while read < want {+ let mut chunk = vec![0u8; want - read]; if !self.read_full(&mut chunk)? { return err(format!(- "{} ends mid-record payload",- self.path.display()+ "{} ends {} byte(s) into frame {}",+ self.path.display(),+ read,+ self.frames_seen, )); }- // `read_full` on the file path may return short (EOF splits the- // loop); on anon it fills exactly. Copy what arrived.+ // `read_full` on the file path may return short; on anon it fills exactly. let n = chunk.len();- self.buf[read..read + n].copy_from_slice(&chunk);+ self.raw_frame[read..read + n].copy_from_slice(&chunk); read += n; if n == 0 { break; } }- Ok(Some(norm_payload(kind, geom_len, &self.buf)?))+ let mut framed = Vec::with_capacity(4 + want);+ framed.extend_from_slice(&len_buf);+ framed.extend_from_slice(&self.raw_frame);+ self.frame = inflate_frame(self.frames_seen, &self.path, &framed)?;+ self.frame_used = 0;+ self.frames_seen += 1;+ Ok(true)+ }++ #[allow(clippy::should_implement_trait)]+ pub fn next(&mut self) -> Result<Option<NormalizedFeature>> {+ loop {+ if self.frame_used < self.frame.len() {+ let head: &[u8; NORM_HEADER_BYTES] = self.frame+ [self.frame_used..self.frame_used + NORM_HEADER_BYTES]+ .try_into()+ .map_err(|_| {+ Error(format!(+ "{} ends {} byte(s) into a {NORM_HEADER_BYTES}-byte record header",+ self.path.display(),+ self.frame.len() - self.frame_used,+ ))+ })?;+ let (geom_len, props_len, kind) = norm_header(head)?;+ let body = self.frame_used + NORM_HEADER_BYTES;+ let rec_end = body + geom_len + props_len;+ if rec_end > self.frame.len() {+ return err(format!(+ "{} holds a record running {} byte(s) past its frame",+ self.path.display(),+ rec_end - self.frame.len(),+ ));+ }+ let feature = norm_payload(kind, geom_len, &self.frame[body..rec_end])?;+ self.frame_used = rec_end;+ return Ok(Some(feature));+ }+ if !self.refill()? {+ return Ok(None);+ }+ } } } @@ -515,6 +833,10 @@ impl NormalizedChunks { /// The first feature of chunk `i` is input feature `i * NORM_CHUNK_FEATURES`, by /// construction of the index — which is what lets the caller reproduce the exact /// `seq` the sequential path assigns.+ ///+ /// The chunk span covers one compressed frame: it is read whole, inflated, and decoded+ /// with the same [`decode_chunk_records`] the sequential reader uses, so the two paths+ /// cannot diverge on what they accept. pub fn read_into( &self, i: usize,@@ -555,33 +877,8 @@ impl NormalizedChunks { })?, _ => return err("a normalized chunk reader has no backend".to_string()), }- let mut at = 0usize;- while at < len {- if len - at < NORM_HEADER_BYTES {- return err(format!(- "normalized chunk {i} of {} ends {} byte(s) into a \- {NORM_HEADER_BYTES}-byte record header",- self.path.display(),- len - at- ));- }- let head: &[u8; NORM_HEADER_BYTES] = scratch[at..at + NORM_HEADER_BYTES]- .try_into()- .expect("a header's worth of bytes");- let (geom_len, props_len, kind) = norm_header(head)?;- let body = at + NORM_HEADER_BYTES;- let rec_end = body + geom_len + props_len;- if rec_end > len {- return err(format!(- "normalized chunk {i} of {} holds a record running {} byte(s) past its end",- self.path.display(),- rec_end - len- ));- }- out.push(norm_payload(kind, geom_len, &scratch[body..rec_end])?);- at = rec_end;- }- Ok(())+ let raw = inflate_frame(i, &self.path, scratch)?;+ decode_chunk_records(i, &self.path, &raw, out) } }
scripts/maps/tile_build/src/spill_part3.rs
diff --git a/scripts/maps/tile_build/src/spill_part3.rs b/scripts/maps/tile_build/src/spill_part3.rsindex 1ef54505cc..c766b22d5a 100644--- a/scripts/maps/tile_build/src/spill_part3.rs+++ b/scripts/maps/tile_build/src/spill_part3.rs@@ -466,17 +466,26 @@ .expect("a feature"); assert_eq!(back, feature, "an e7-grid coordinate must not move at all"); - // Eight bytes a vertex, not sixteen. The whole point of the encoding.- let bytes = std::fs::metadata(&path).unwrap().len() as usize;+ // Eight bytes a vertex, not sixteen, in the *records* -- the whole point of the+ // encoding. The file itself holds those records inside one compressed frame (plus the+ // 8-byte spill header), so its length is asserted structurally instead of exactly: the+ // frame must inflate to exactly the raw records above.+ let bytes = std::fs::read(&path).unwrap();+ assert_eq!(&bytes[0..4], b"NZC1", "the spill magic");+ assert_eq!(bytes[4], 1, "the spill version");+ assert!(bytes[5..8].iter().all(|v| *v == 0), "reserved zero");+ let frame_len = u32::from_le_bytes(bytes[8..12].try_into().unwrap()) as usize;+ assert_eq!(8 + 4 + frame_len, bytes.len(), "one frame fills the file");+ let raw = miniz_oxide::inflate::decompress_to_vec(&bytes[12..]).expect("inflate"); let props = { let mut buf = Vec::new(); encode_props(&feature.props, &mut buf).unwrap(); buf.len() }; assert_eq!(- bytes,+ raw.len(), NORM_HEADER_BYTES + 4 + points.len() * 8 + props,- "a vertex must cost eight bytes"+ "a vertex must cost eight bytes of record" ); let _ = std::fs::remove_dir_all(&dir);
scripts/maps/tile_build/src/spill_part4.rs
diff --git a/scripts/maps/tile_build/src/spill_part4.rs b/scripts/maps/tile_build/src/spill_part4.rsindex 1da3a48b35..781aef2a80 100644--- a/scripts/maps/tile_build/src/spill_part4.rs+++ b/scripts/maps/tile_build/src/spill_part4.rs@@ -279,17 +279,101 @@ w.finish().unwrap(); let bytes = std::fs::read(&path).unwrap();+ // Layout is the 8-byte spill header, then one frame (`u32` len + DEFLATE). Truncations+ // are relative to that: cutting the frame is a truncated file, cutting into the spill+ // header is a file that is not a spill at all.+ assert!(bytes.len() > 8 + 4, "the fixture must hold a frame"); std::fs::write(&path, &bytes[..bytes.len() - 8]).unwrap(); assert!(NormalizedReader::open(&path).unwrap().next().is_err(), "short payload");- std::fs::write(&path, &bytes[..NORM_HEADER_BYTES - 1]).unwrap();- assert!(NormalizedReader::open(&path).unwrap().next().is_err(), "short header");- let mut dirty = bytes.clone();- dirty[NORM_HEADER_BYTES - 1] = 1;+ std::fs::write(&path, &bytes[..8 + 4 - 1]).unwrap();+ assert!(NormalizedReader::open(&path).unwrap().next().is_err(), "short frame header");+ // A file shorter than the spill header is not a spill file at all.+ std::fs::write(&path, &bytes[..8 - 1]).unwrap();+ assert!(NormalizedReader::open(&path).is_err(), "short spill header");+ // Corrupt the first record's reserved tail *inside* the frame: inflate the frame,+ // dirty byte 15 of the record header, recompress, and rewrite the file. The reader+ // must refuse the record, not decode past it.+ let frame_len =+ u32::from_le_bytes(bytes[8..12].try_into().unwrap()) as usize;+ let mut raw =+ miniz_oxide::inflate::decompress_to_vec(&bytes[12..12 + frame_len]).unwrap();+ raw[NORM_HEADER_BYTES - 1] = 1;+ let sealed = miniz_oxide::deflate::compress_to_vec(&raw, 6);+ let mut dirty = bytes[..12].to_vec();+ dirty[8..12].copy_from_slice(&(sealed.len() as u32).to_le_bytes());+ dirty.extend_from_slice(&sealed); std::fs::write(&path, &dirty).unwrap(); assert!( NormalizedReader::open(&path).unwrap().next().is_err(), "nonzero reserved tail" );+ // And the chunked reader agrees on the truncated file: a frame that will not inflate+ // is corruption, not a short chunk.+ std::fs::write(&path, &bytes[..bytes.len() - 8]).unwrap();+ let summary = NormalizedSummary { count: 1, chunks: vec![8, bytes.len() as u64 - 8], ..Default::default() };+ let chunks = NormalizedChunks::open(&path, summary.chunks.clone()).unwrap();+ let mut scratch = Vec::new();+ let mut out = Vec::new();+ assert!(chunks.read_into(0, &mut scratch, &mut out).is_err(), "short frame");+ let _ = std::fs::remove_dir_all(&dir);+ }++ /// A file with the wrong magic or version is refused on open, not decoded as frames.+ #[test]+ fn a_spill_with_bad_magic_or_version_is_refused() {+ let dir = tmp("normmagic");+ let path = dir.join("f.bin");+ let mut w = NormalizedWriter::create(&path).unwrap();+ w.push(&Geometry::Points(vec![(1.0, 2.0)]), &[]).unwrap();+ w.finish().unwrap();+ let bytes = std::fs::read(&path).unwrap();++ let mut bad = bytes.clone();+ bad[0] = b'X';+ std::fs::write(&path, &bad).unwrap();+ assert!(NormalizedReader::open(&path).is_err(), "bad magic decodes");++ let mut bad = bytes.clone();+ bad[4] = 9;+ std::fs::write(&path, &bad).unwrap();+ assert!(NormalizedReader::open(&path).is_err(), "bad version decodes");++ let mut bad = bytes.clone();+ bad[7] = 1;+ std::fs::write(&path, &bad).unwrap();+ assert!(NormalizedReader::open(&path).is_err(), "nonzero reserved decodes");++ let _ = std::fs::remove_dir_all(&dir);+ }++ /// Compression is the point: 64 repetitive line features must stage at a fraction of+ /// their raw records. A regression to uncompressed staging fails here rather than on a+ /// planet disk at z14.+ #[test]+ fn a_chunk_of_repetitive_features_stages_compressed() {+ let dir = tmp("normratio");+ let path = dir.join("f.bin");+ let mut w = NormalizedWriter::create(&path).unwrap();+ for i in 0..NORM_CHUNK_FEATURES {+ let f = i as f64;+ w.push(+ &Geometry::Lines(vec![vec![(f * 0.001, 1.0), (f * 0.001, 2.0)]]),+ &[("i".to_string(), Value::Uint(i))],+ )+ .unwrap();+ }+ let summary = w.finish().unwrap();+ assert_eq!(summary.chunk_count(), 1);+ let staged = std::fs::metadata(&path).unwrap().len();+ // Raw records: each ~50+ bytes, so ~3.2 KB minimum unstaged. The frame must be+ // well under that; 1 KB is generous to DEFLATE on coordinate runs.+ assert!(staged < 8 + 4 + 1024, "{staged} staged bytes for one chunk is not compressed");+ // And it still reads back exactly.+ let chunks = NormalizedChunks::open(&path, summary.chunks.clone()).unwrap();+ let mut scratch = Vec::new();+ let mut out = Vec::new();+ chunks.read_into(0, &mut scratch, &mut out).unwrap();+ assert_eq!(out.len(), NORM_CHUNK_FEATURES as usize); let _ = std::fs::remove_dir_all(&dir); }