library:map: stream the .mamaps writer to a scratch file, and let callers compress
- Commit
cc11506011f4a2fde3cdb39acd2a949428a84772- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-28 04:50 UTC (3 months ago)
- Parents
677f620
Diff
library/tilecodec/src/main/rust/src/mamaps/mod.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/mod.rs b/library/tilecodec/src/main/rust/src/mamaps/mod.rsindex 779b9fe44c..80313148e6 100644--- a/library/tilecodec/src/main/rust/src/mamaps/mod.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/mod.rs@@ -63,6 +63,7 @@ mod tests { use crate::proto::Result; use crate::stream::{RangeReader, OPEN_PREFIX_BYTES}; use std::cell::RefCell;+ use std::path::PathBuf; /// A [`RangeReader`] over bytes in memory that logs every range asked for, so a test can assert /// on the **number of round trips** as well as on the bytes. The same shape `stream.rs` uses.@@ -115,6 +116,72 @@ mod tests { MamapsArchive::open(Counting { bytes, requests: RefCell::new(Vec::new()) }).expect("open") } + /// A directory of its own, removed on drop, so a test can point a writer's body scratch file at+ /// it and then assert on what is — or is not — left behind.+ struct Scratch {+ dir: PathBuf,+ }++ impl Scratch {+ fn new(name: &str) -> Scratch {+ let dir =+ std::env::temp_dir().join(format!("mamaps_write_{name}_{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).expect("temp dir");+ Scratch { dir }+ }++ fn path(&self, name: &str) -> PathBuf {+ self.dir.join(name)+ }++ fn options(&self) -> Options {+ Options { spill_dir: Some(self.dir.clone()), ..Options::default() }+ }++ /// What the directory holds, so a test can say "nothing".+ fn files(&self) -> Vec<String> {+ std::fs::read_dir(&self.dir)+ .expect("read_dir")+ .map(|e| e.expect("entry").file_name().to_string_lossy().into_owned())+ .collect()+ }+ }++ impl Drop for Scratch {+ fn drop(&mut self) {+ let _ = std::fs::remove_dir_all(&self.dir);+ }+ }++ /// A body big enough, and random enough, that a few hundred of them cannot fit in the writer's+ /// scratch-file buffer.+ ///+ /// The coordinates come from a seeded LCG rather than from a pattern on purpose: a body that+ /// deflated down to a few hundred bytes would let a whole test archive sit in the buffer, and+ /// then a test about reading bodies back off disk would pass without ever reading one.+ fn wide_body_for(seed: i16) -> Body {+ const POINTS: u32 = 2048;+ let mut roads = Layer::new(dict::LAYER_ROADS);+ roads.features.push(Feature {+ kind: 45,+ kind_detail: dict::NONE,+ geom_type: GEOM_LINE,+ flags: 0,+ parts_offset: 0,+ part_count: 1,+ });+ roads.parts.push(Part { coord_start: 0, point_count: POINTS, winding: WINDING_OUTER });+ let mut state = seed as u64 ^ 0xA5A5_A5A5_A5A5_A5A5;+ roads.coords = (0..POINTS)+ .map(|_| {+ state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);+ ((state >> 33) as i16, (state >> 17) as i16)+ })+ .collect();+ Body { extent: DEFAULT_EXTENT, layers: vec![roads] }+ }+ #[test] fn a_tile_written_reads_back_exactly() { let bytes = archive(&[(0, 0, 0, 100), (1, 0, 0, 200), (1, 1, 1, 300)], Options::default());@@ -260,6 +327,113 @@ mod tests { } } + /// **The one thing spilling the data section could have broken.** A content-dedup hit is a fact+ /// because every byte of the candidate is compared, and once the bodies are in a file that+ /// compare has to read them back. This feeds enough distinct bodies to push the earliest ones+ /// well past the writer's in-memory buffer and then repeats every one of them, so the+ /// confirmations really do come off disk rather than out of the buffer.+ #[test]+ fn content_dedup_confirms_a_candidate_that_has_already_reached_the_scratch_file() {+ let scratch = Scratch::new("dedup_off_disk");+ // 200 incompressible 8 KiB bodies is a data section of about 1.6 MB, against a buffer of 1.+ const DISTINCT: i16 = 200;+ let base = tile_id(9, 0, 0);+ let mut rows: Vec<(u64, i16)> = (0..DISTINCT).map(|i| (base + i as u64, i)).collect();+ // Then the same bodies again at later ids, in the same order. Every repeat is non-adjacent,+ // so no run can form and each one has to go through the content bucket.+ rows.extend((0..DISTINCT).map(|i| (base + DISTINCT as u64 + i as u64, i)));++ let options = Options { max_zoom: 9, ..scratch.options() };+ let mut writer = StreamWriter::new(options).expect("options");+ for (id, seed) in &rows {+ writer.append(*id, &wide_body_for(*seed)).expect("append");+ }+ let bytes = writer.finish().expect("finish");++ let header = Header::parse(&bytes).expect("header");+ assert!(+ header.data_len > 1 << 20,+ "the data section must outgrow the writer's buffer or this test proves nothing, it is \+ {} bytes",+ header.data_len,+ );+ assert_eq!(header.tiles_addressed, rows.len() as u64);+ assert_eq!(header.bodies_written, DISTINCT as u64, "the second pass stored nothing new");+ // And every tile still reads back as itself, which is what confirming against the wrong+ // bytes would silently break.+ let mut a = open(bytes);+ for (id, seed) in &rows {+ let (z, x, y) = crate::pmtiles::tile_zxy(*id);+ let tile = a.tile(z, x as u32, y as u32).expect("read").expect("present");+ assert_eq!(tile, wide_body_for(*seed), "tile {id}");+ }+ }++ /// `finish_to_path` and `finish` are two ways of emitting one archive, not two archives.+ ///+ /// Worth asserting because they are not the same code path — one copies the data section out of+ /// a file and the other into a `Vec` — and because the streaming one is what a real build uses.+ /// If it could differ by a byte then every test above would be testing something nothing ships.+ #[test]+ fn a_streamed_archive_is_byte_identical_to_one_finished_in_memory() {+ let scratch = Scratch::new("streamed");+ // Repeats and runs in the same archive, so dedup and the run-length flag are both live on+ // the way to both outputs.+ let tiles: Vec<(u8, u64, u64, i16)> = (0..8u64)+ .flat_map(|x| {+ (0..8u64).map(move |y| (3u8, x, y, if (x + y) % 3 == 0 { 4 } else { (x * 8 + y) as i16 }))+ })+ .collect();+ let options = || Options { leaf_entry_capacity: 8, ..scratch.options() };+ let in_memory = archive(&tiles, options());++ let mut rows: Vec<(u64, i16)> =+ tiles.iter().map(|(z, x, y, seed)| (tile_id(*z, *x, *y), *seed)).collect();+ rows.sort_by_key(|(id, _)| *id);+ let mut writer = StreamWriter::new(options()).expect("options");+ for (id, seed) in rows {+ writer.append(id, &body_for(seed)).expect("append");+ }+ let out = scratch.path("streamed.mamaps");+ writer.finish_to_path(&out).expect("finish_to_path");++ let streamed = std::fs::read(&out).expect("read back");+ assert_eq!(streamed.len(), in_memory.len(), "the same length");+ assert_eq!(streamed, in_memory, "the same bytes");+ // And it opens and reads, which is all a reader will ever ask of it.+ assert_eq!(open(streamed).tile(3, 7, 7).expect("read").expect("present"), body_for(63));+ }++ /// A build that dies must not strand a copy of its data section — 652 MB for California, tens of+ /// gigabytes for a planet. However the writer ends, its scratch file goes with it.+ #[test]+ fn the_body_scratch_file_is_removed_however_the_build_ends() {+ let scratch = Scratch::new("spill_cleanup");+ // A separate directory for the archives, so `scratch.files()` can assert on emptiness.+ let output = Scratch::new("spill_cleanup_out");++ // Dropped without ever being finished, which is what a failure upstream of the writer looks+ // like.+ {+ let mut writer = StreamWriter::new(scratch.options()).expect("options");+ writer.append(tile_id(0, 0, 0), &body_for(1)).expect("append");+ assert_eq!(scratch.files().len(), 1, "a writer holding bodies has a scratch file");+ }+ assert!(scratch.files().is_empty(), "dropping the writer took its scratch with it");++ let mut writer = StreamWriter::new(scratch.options()).expect("options");+ writer.append(tile_id(0, 0, 0), &body_for(2)).expect("append");+ writer.finish_to_path(&output.path("a.mamaps")).expect("finish_to_path");+ assert!(scratch.files().is_empty(), "and so did finishing");++ // And a build refused for having no tiles, which fails only after the scratch file exists.+ let writer = StreamWriter::new(scratch.options()).expect("options");+ let refused = output.path("b.mamaps");+ assert!(writer.finish_to_path(&refused).is_err(), "an archive with no tiles");+ assert!(scratch.files().is_empty());+ assert!(!refused.exists(), "and the destination was never touched");+ }+ /// **Invariant 5.** Byte-identical output for identical input, twice over. Nothing in the emit /// path iterates a hash map: the dictionary is a constant table, layers are sorted by id and /// the content bucket is only ever probed.
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 5b34c441b5..7106a92676 100644--- a/library/tilecodec/src/main/rust/src/mamaps/write.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/write.rs@@ -1,8 +1,18 @@ //! Writing a `.mamaps` archive, streaming and byte-identically. //! //! Bodies are appended in ascending tile-id order — which the generator gets for free, because its-//! spill buckets are zoom-major Hilbert ranges — and the index is built as they go. Nothing is-//! held in memory but the entries.+//! spill buckets are zoom-major Hilbert ranges — and the index is built as they go. Nothing is held+//! in memory but the index entries and the dedup buckets: bodies go to a scratch file as they+//! arrive and are copied onto the end of the archive at the finish.+//!+//! # Why the data section is not held in memory+//!+//! It was, and it cost twice the archive. A `data: Vec<u8>` grew to the whole 652 MB data section+//! of a California build, and then `finish` allocated a second 655 MB `Vec` and copied into it: a+//! 1.3 GB peak for a 655 MB file, and a projected 82 GB peak on a planet build, which is a hard+//! blocker on its own. Sending bodies straight to a scratch file makes the writer's peak the+//! *index* instead, at 16 bytes per stored body rather than the body itself, and+//! [`StreamWriter::finish_to_path`] never materialises the archive at all. //! //! # Dedup //!@@ -16,14 +26,33 @@ //! Together these are what makes empty and ocean tiles nearly free: on the planet PMTiles archive //! the same two collapse 1.57 M addressed tiles to 1.03 M stored bodies. //!+//! Both compares are against bytes that now live in a file, which is the one thing spilling the+//! data section actually complicates. Neither compare pays much for it:+//!+//! * A run-length compare is against the body the **last index entry** points at, and the writer+//! keeps exactly those bytes to hand. That is one body, not a cache, and it never reads the file.+//! * A content compare is against a body at an arbitrary earlier offset, so it may read. Only the+//! candidates in one FNV bucket are ever compared, and [`Spill`]'s write buffer answers a compare+//! against a body still in it without a syscall.+//! //! # Determinism //! //! Byte-identical output for identical input, at any thread count, because nothing in the emit //! path iterates a hash map: the dictionary comes from a constant table, layers are sorted by id, //! and the bucket map is only ever *probed*, never walked. `pyramid.rs`'s existing byte-identity //! suite is the precedent and this holds to the same standard.+//!+//! Spilling changes none of that. The scratch file holds the same bytes in the same order the+//! in-memory `Vec` did, so which candidate a compare confirms — and therefore which offset an entry+//! is given — cannot depend on whether the bytes came from the buffer or from the file. That is+//! what lets [`StreamWriter::finish`] and [`StreamWriter::finish_to_path`] be two ways of emitting+//! one archive rather than two archives. use std::collections::HashMap;+use std::fs::{File, OpenOptions};+use std::io::{Read, Seek, SeekFrom, Write};+use std::path::{Path, PathBuf};+use std::sync::atomic::{AtomicU64, Ordering}; use crate::mamaps::body::{self, Body}; use crate::mamaps::dict::Dictionary;@@ -56,6 +85,13 @@ pub struct Options { /// renderer skip its repair pass. pub rings_validated: bool, pub leaf_entry_capacity: u32,+ /// Where the body scratch file goes, or the system temporary directory when unset.+ ///+ /// Worth naming rather than always taking `std::env::temp_dir()`, because the scratch file is+ /// the size of the data section: 652 MB for California and a projected 82 GB for a planet+ /// build, and a system temporary directory is routinely on a small system volume. The generator+ /// already puts its *feature* spill beside the output for the same reason.+ pub spill_dir: Option<PathBuf>, pub min_lon_e7: i32, pub min_lat_e7: i32, pub max_lon_e7: i32,@@ -71,6 +107,7 @@ impl Default for Options { compress: true, rings_validated: false, leaf_entry_capacity: DEFAULT_LEAF_CAPACITY,+ spill_dir: None, min_lon_e7: -1_800_000_000, min_lat_e7: -850_511_287, max_lon_e7: 1_800_000_000,@@ -79,16 +116,18 @@ impl Default for Options { } } -/// Builds an archive in memory, appending bodies in ascending tile-id order.+/// Builds an archive, appending bodies in ascending tile-id order. ///-/// In memory rather than through a scratch file, unlike `pmtiles::StreamBuilder`: the data section-/// is the only thing that grows without bound, and the generator that will feed this already-/// spills its *input* to disk, so a second spill here would buy a smaller peak in exchange for a-/// second on-disk format to keep correct. A California archive is a few hundred megabytes. When a-/// planet build needs it, the scratch-file pattern is already written next door.+/// Bodies go to a scratch file as they arrive rather than into a `Vec`, so what this holds is the+/// index and the dedup buckets — 16 bytes per stored body and a hash entry per distinct one, not the+/// bodies. See the module header for why, and for what that costs the two dedup compares. pub struct StreamWriter { options: Options,- data: Vec<u8>,+ /// The data section, being written.+ ///+ /// Named `data` because that is what it is: the same bytes, in the same order, that used to be+ /// accumulated in memory here.+ data: Spill, /// One per stored body, ascending by tile id, partitioned into leaves at `finish`. /// /// The [`LeafEntry::offset_delta`] here is still **absolute** within the data section; it is@@ -98,6 +137,15 @@ pub struct StreamWriter { /// which is why it is a list. Probed, never iterated. seen: HashMap<(u64, u32), Vec<u32>>, last_id: Option<u64>,+ /// The stored bytes of the body `entries.last()` points at, which is what a run-length compare+ /// is against.+ ///+ /// Kept so that compare stays in memory. It is *not* the last body appended: content dedup+ /// means the last entry may point at a body written for a much earlier tile, and this holds+ /// whatever those bytes are. A `debug_assert` in [`Self::append_encoded`] checks it against the+ /// 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>, 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@@ -120,12 +168,16 @@ impl StreamWriter { options.leaf_entry_capacity, )); }+ // After the option checks, so a build with an impossible zoom range fails without having+ // created a file to clean up.+ let data = Spill::create(options.spill_dir.as_deref())?; Ok(StreamWriter { options,- data: Vec::new(),+ data, entries: Vec::new(), seen: HashMap::new(), last_id: None,+ last_body: Vec::new(), tiles_addressed: 0, distinct: 0, runs_used: false,@@ -143,6 +195,45 @@ impl StreamWriter { /// as bodies arrive, and the generator's zoom-major Hilbert buckets already deliver them in /// order. A caller that cannot is a caller whose bucketing broke, which is worth failing over. pub fn append_encoded(&mut self, tile_id: u64, encoded: &[u8]) -> Result<()> {+ // Parsed rather than trusted: `raw_len` is what a reader allocates from, and a body whose+ // declared length disagrees with its bytes would be caught on device instead of here.+ let raw_len = Body::raw_len(encoded)?;+ if raw_len as usize != encoded.len() {+ return err(format!(+ "a .mamaps body declares {raw_len} bytes but is {}",+ encoded.len(),+ ));+ }+ let stored = if self.options.compress { compress_body(encoded) } else { encoded.to_vec() };+ self.push(tile_id, &stored)+ }++ /// Append a body already compressed by [`compress_body`].+ ///+ /// For a generator that compresses in parallel, which is the difference between using one core+ /// and using all of them. DEFLATE at level nine runs on the order of 15 MB/s, so a California+ /// build's 1.3 GB of bodies is about ninety seconds of a single core — and inside+ /// [`Self::append_encoded`] that sits *downstream* of the caller's parallel map and encode,+ /// serialising the whole pipeline behind the one step that cannot be stolen. Compressing in the+ /// worker and appending the result leaves the append what it should be: index bookkeeping.+ ///+ /// Dedup is unaffected. Entries are deduplicated on the **stored** bytes either way, and DEFLATE+ /// is deterministic, so two equal bodies still compress to two equal frames and still collapse.+ /// That is also why this is byte-identical to compressing here.+ pub fn append_stored(&mut self, tile_id: u64, stored: &[u8]) -> Result<()> {+ if !self.options.compress {+ return err(+ "append_stored was given a compressed body but this archive stores them raw"+ .to_string(),+ );+ }+ // The 16-byte body header rides uncompressed ahead of the frame, so this still validates.+ Body::raw_len(stored)?;+ self.push(tile_id, stored)+ }++ /// The part both appends share: range and order checks, dedup, and the index entry.+ fn push(&mut self, tile_id: u64, stored: &[u8]) -> Result<()> { let (z, _, _) = crate::pmtiles::tile_zxy(tile_id); if z < self.options.min_zoom || z > self.options.max_zoom { return err(format!(@@ -157,27 +248,24 @@ impl StreamWriter { )); } }- // Parsed rather than trusted: `raw_len` is what a reader allocates from, and a body whose- // declared length disagrees with its bytes would be caught on device instead of here.- let raw_len = Body::raw_len(encoded)?;- if raw_len as usize != encoded.len() {- return err(format!(- "a .mamaps body declares {raw_len} bytes but is {}",- encoded.len(),- ));- } self.last_id = Some(tile_id); self.tiles_addressed += 1; - let stored = if self.options.compress { compress(encoded) } else { encoded.to_vec() }; let length = u32::try_from(stored.len()) .map_err(|_| crate::proto::Error("a .mamaps body is larger than 4 GiB".to_string()))?; // Run-length first: a consecutive repeat needs no dedup lookup and no new entry at all.+ // The compare is against `last_body` rather than the spill, because the bytes the last+ // entry points at are the one body always worth keeping to hand. if let Some((previous_id, previous)) = self.entries.last_mut() {+ debug_assert!(+ self.data.matches_at(previous.offset_delta, &self.last_body)?,+ "last_body must be the bytes the last entry points at, or the shortcut below is \+ answering for a body that is not there",+ ); if previous.length == length && *previous_id + previous.run_length as u64 == tile_id- && self.data[previous.offset_delta as usize..][..length as usize] == stored[..]+ && self.last_body == stored { previous.run_length += 1; self.runs_used = true;@@ -186,25 +274,28 @@ impl StreamWriter { } let key = (hash64(&stored), length);- let offset = match self- .seen- .get(&key)- .and_then(|offsets| {- offsets- .iter()- .copied()- .find(|&at| self.data[at as usize..][..length as usize] == stored[..])- }) {+ // `seen` and `data` are borrowed apart because confirming a candidate may read the spill,+ // which needs `&mut`, while the bucket being walked lives in the map.+ let StreamWriter { seen, data, distinct, .. } = &mut *self;+ let bucket = seen.entry(key).or_default();+ let mut hit = None;+ for &at in bucket.iter() {+ if data.matches_at(at, &stored)? {+ hit = Some(at);+ break;+ }+ }+ let offset = match hit { Some(at) => at, None => {- let at = u32::try_from(self.data.len()).map_err(|_| {+ let at = u32::try_from(data.len()).map_err(|_| { crate::proto::Error( "a .mamaps data section past 4 GiB needs a wider offset field".to_string(), ) })?;- self.data.extend_from_slice(&stored);- self.seen.entry(key).or_default().push(at);- self.distinct += 1;+ data.append(&stored)?;+ bucket.push(at);+ *distinct += 1; at } };@@ -212,14 +303,73 @@ impl StreamWriter { tile_id, LeafEntry { tile_id_lo: 0, run_length: 1, offset_delta: offset, length }, ));+ self.last_body.clear();+ self.last_body.extend_from_slice(stored); Ok(()) } - /// The whole file.+ /// 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,+ /// which is small next to the bodies — and the data section is copied straight from the scratch+ /// file onto the end. Nothing ever holds the archive.+ ///+ /// The header is parsed before the destination is touched, so a build that would not open does+ /// not leave a file behind that looks like it might.+ pub fn finish_to_path(mut self, path: &Path) -> Result<()> {+ let (header, prefix) = self.prefix()?;+ let mut out = File::create(path).map_err(|e| {+ crate::proto::Error(format!("cannot write {}: {e}", path.display()))+ })?;+ out.write_all(&prefix)+ .map_err(|e| crate::proto::Error(format!("cannot write {}: {e}", path.display())))?;+ let copied = self.data.copy_to(&mut out, path)?;+ if copied != header.data_len {+ return err(format!(+ "a .mamaps build declared a {} byte data section and copied {copied}",+ header.data_len,+ ));+ }+ Ok(())+ }++ /// The whole file, in memory.+ ///+ /// Kept for callers small enough not to care — the tests, and the tools that read an archive+ /// back before writing it — and for them the peak is one copy of the archive rather than the two+ /// it used to be. Anything the size of a region should use [`Self::finish_to_path`].+ pub fn finish(mut self) -> Result<Vec<u8>> {+ let (header, prefix) = self.prefix()?;+ // TEMPORARY instrumentation.+ eprintln!(+ "spill: {} confirms, {} from file ({:.2}%), {} bytes read back",+ self.data.confirms,+ self.data.confirms_from_file,+ 100.0 * self.data.confirms_from_file as f64 / self.data.confirms.max(1) as f64,+ self.data.bytes_from_file,+ );+ let mut out = Vec::with_capacity(header.file_len as usize);+ out.extend_from_slice(&prefix);+ let copied = self.data.copy_to_vec(&mut out)?;+ if copied != header.data_len {+ return err(format!(+ "a .mamaps build declared a {} byte data section and copied {copied}",+ header.data_len,+ ));+ }+ debug_assert_eq!(out.len() as u64, header.file_len);+ Ok(out)+ }++ /// Everything ahead of the data section: header, dictionary, root, leaves, in that order. /// /// Section order on disk is header, dictionary, root, leaves, data — but every one of them is /// located by a header field, so a later version may reorder them freely.- pub fn finish(self) -> Result<Vec<u8>> {+ ///+ /// Returned parsed as well as serialized, because every check `Header::parse` makes is a check a+ /// reader will make on open, and finding out then means finding out on a device. It is checked+ /// here, before either finish emits a byte.+ fn prefix(&self) -> Result<(Header, Vec<u8>)> { if self.entries.is_empty() { return err("a .mamaps archive needs at least one tile"); }@@ -269,6 +419,7 @@ impl StreamWriter { let root_offset = dict_offset + dictionary.len() as u64; let leaf_offset = root_offset + root_bytes.len() as u64; let data_offset = leaf_offset + leaf_bytes.len() as u64;+ let data_len = self.data.len(); let header = Header { flags,@@ -277,7 +428,7 @@ impl StreamWriter { min_zoom: self.options.min_zoom, max_zoom: self.options.max_zoom, build_id: self.options.build_id,- file_len: data_offset + self.data.len() as u64,+ file_len: data_offset + data_len, dict_offset, dict_len: dictionary.len() as u32, leaf_entry_capacity: capacity,@@ -287,7 +438,7 @@ impl StreamWriter { leaf_offset, leaf_len: leaf_bytes.len() as u32, data_offset,- data_len: self.data.len() as u64,+ data_len, tiles_addressed: self.tiles_addressed, bodies_written: self.distinct, min_lon_e7: self.options.min_lon_e7,@@ -296,17 +447,13 @@ impl StreamWriter { max_lat_e7: self.options.max_lat_e7, }; - let mut out = Vec::with_capacity(header.file_len as usize);- out.extend_from_slice(&header.serialize());- out.extend_from_slice(&dictionary);- out.extend_from_slice(&root_bytes);- out.extend_from_slice(&leaf_bytes);- out.extend_from_slice(&self.data);- debug_assert_eq!(out.len() as u64, header.file_len);- // Parsed back before it is handed over, because every check `Header::parse` makes is a- // check a reader will make on open, and finding out then means finding out on a device.- Header::parse(&out)?;- Ok(out)+ let mut prefix = Vec::with_capacity(data_offset as usize);+ prefix.extend_from_slice(&header.serialize());+ prefix.extend_from_slice(&dictionary);+ prefix.extend_from_slice(&root_bytes);+ prefix.extend_from_slice(&leaf_bytes);+ debug_assert_eq!(prefix.len() as u64, data_offset);+ Ok((Header::parse(&prefix)?, prefix)) } /// Chop the entries into leaves of at most `capacity`, rebasing each leaf's ids and offsets.@@ -349,11 +496,211 @@ impl StreamWriter { } } +/// How much of the data section is held in memory before it reaches the scratch file.+///+/// One mebibyte, which turns a California build's 1.9 M body appends into a few hundred writes+/// while staying noise next to the index it sits beside.+const BUFFER_BYTES: usize = 1 << 20;++/// The data section of an archive being written: a scratch file with its tail held in memory.+///+/// Two callers want different things from it. Appending wants a buffer, so that a body is not a+/// syscall. Confirming a content-dedup candidate wants random access to any *earlier* body — a seek+/// and a read for anything already on disk, but a slice compare for anything still in the buffer,+/// and the bodies most recently written are the ones a repeat is likeliest to match.+struct Spill {+ path: PathBuf,+ /// Opened for reading as well as writing, because a content-dedup compare reads back a body+ /// this same handle wrote.+ file: File,+ /// The tail of the section, not yet in `file`.+ buffer: Vec<u8>,+ /// Bytes that *are* in `file`, which is also the offset `buffer` begins at.+ flushed: u64,+ /// Reused by [`Self::matches_at`], so a compare against the file allocates nothing.+ scratch: Vec<u8>,+ // TEMPORARY instrumentation, to measure how often a content-dedup confirmation has to read.+ confirms: u64,+ confirms_from_file: u64,+ bytes_from_file: u64,+}++impl Spill {+ fn create(dir: Option<&Path>) -> Result<Spill> {+ /// Two writers in one process — which the test suite has, and a planet build may — must not+ /// share a scratch file.+ static NEXT: AtomicU64 = AtomicU64::new(0);+ let dir = dir.map(Path::to_path_buf).unwrap_or_else(std::env::temp_dir);+ let path = dir.join(format!(+ "mamaps_bodies_{}_{}.tmp",+ std::process::id(),+ NEXT.fetch_add(1, Ordering::Relaxed),+ ));+ // Truncating rather than `create_new`: a run that died left its scratch behind, and once a+ // pid is recycled, refusing to build over an abandoned file would be a worse failure than+ // overwriting it.+ let file = OpenOptions::new()+ .read(true)+ .write(true)+ .create(true)+ .truncate(true)+ .open(&path)+ .map_err(|e| scratch_error(&path, "create", e))?;+ Ok(Spill {+ path,+ file,+ buffer: Vec::with_capacity(BUFFER_BYTES),+ flushed: 0,+ scratch: Vec::new(),+ confirms: 0,+ confirms_from_file: 0,+ bytes_from_file: 0,+ })+ }++ /// Bytes appended so far, buffered or not — which is the offset the next body will land at.+ fn len(&self) -> u64 {+ self.flushed + self.buffer.len() as u64+ }++ fn append(&mut self, bytes: &[u8]) -> Result<()> {+ if self.buffer.len() + bytes.len() > BUFFER_BYTES {+ self.flush()?;+ }+ if bytes.len() >= BUFFER_BYTES {+ // A body bigger than the buffer goes straight through, because buffering it would only+ // copy it twice on the way to the same place.+ let Spill { file, path, flushed, .. } = self;+ write_all_at(file, path, *flushed, bytes)?;+ *flushed += bytes.len() as u64;+ } else {+ self.buffer.extend_from_slice(bytes);+ }+ Ok(())+ }++ /// Whether the `candidate.len()` bytes at `offset` are exactly `candidate`.+ ///+ /// The compare that makes a content-dedup hit a fact rather than a probability. Answered out of+ /// the buffer when the body is still in it, which costs nothing at all.+ fn matches_at(&mut self, offset: u32, candidate: &[u8]) -> Result<bool> {+ let start = offset as u64;+ let end = start + candidate.len() as u64;+ debug_assert!(end <= self.len(), "a dedup candidate past the end of the data section");+ self.confirms += 1;+ if start >= self.flushed {+ let at = (start - self.flushed) as usize;+ return Ok(self.buffer[at..at + candidate.len()] == *candidate);+ }+ self.confirms_from_file += 1;+ self.bytes_from_file += candidate.len() as u64;+ // A body straddling the boundary is one the buffer holds only the tail of. Flushing is+ // simpler than stitching two compares together, and can only happen once per body.+ if end > self.flushed {+ self.flush()?;+ }+ let Spill { file, path, scratch, .. } = self;+ scratch.resize(candidate.len(), 0);+ read_exact_at(file, path, start, scratch)?;+ Ok(scratch[..] == *candidate)+ }++ fn flush(&mut self) -> Result<()> {+ if self.buffer.is_empty() {+ return Ok(());+ }+ let Spill { file, path, buffer, flushed, .. } = self;+ write_all_at(file, path, *flushed, buffer)?;+ *flushed += buffer.len() as u64;+ buffer.clear();+ Ok(())+ }++ /// Copy the whole section onto the end of the archive being written, and say how much.+ ///+ /// Through a buffer of its own rather than `std::io::copy`, whose eight kilobytes would make a+ /// California data section eighty thousand round trips in each direction.+ fn copy_to(&mut self, out: &mut File, out_path: &Path) -> Result<u64> {+ self.flush()?;+ let Spill { file, path, .. } = self;+ file.rewind().map_err(|e| scratch_error(path, "seek in", e))?;+ let mut chunk = vec![0u8; BUFFER_BYTES];+ let mut copied = 0u64;+ loop {+ let n = file.read(&mut chunk).map_err(|e| scratch_error(path, "read back from", e))?;+ if n == 0 {+ return Ok(copied);+ }+ out.write_all(&chunk[..n]).map_err(|e| {+ crate::proto::Error(format!(+ "cannot copy the .mamaps data section into {}: {e}",+ out_path.display(),+ ))+ })?;+ copied += n as u64;+ }+ }++ /// The same, onto the end of an archive being assembled in memory.+ ///+ /// Into a resized tail rather than through `read_to_end`, whose growth heuristics will happily+ /// double a 655 MB buffer and hold both halves while it copies — which is most of the peak this+ /// whole arrangement exists to remove. The length is known exactly, so nothing needs guessing.+ fn copy_to_vec(&mut self, out: &mut Vec<u8>) -> Result<u64> {+ self.flush()?;+ let at = out.len();+ let len = self.flushed;+ out.resize(at + len as usize, 0);+ let Spill { file, path, .. } = self;+ file.rewind().map_err(|e| scratch_error(path, "seek in", e))?;+ file.read_exact(&mut out[at..]).map_err(|e| scratch_error(path, "read back from", e))?;+ Ok(len)+ }+}++impl Drop for Spill {+ /// So a build that dies part way through cannot strand a copy of its data section — 652 MB for+ /// California and tens of gigabytes for a planet, which is why `tile_build::spill` does the+ /// same.+ ///+ /// The error is dropped on purpose. Scratch that outlives the process is untidy; panicking in a+ /// `Drop` while a real failure is unwinding would replace its diagnostic with this one.+ fn drop(&mut self) {+ let _ = std::fs::remove_file(&self.path);+ }+}++/// Seeking before every access rather than tracking the cursor.+///+/// A dedup compare moves the file cursor, so a write that assumed it was still at the end would put+/// a body somewhere else in the data section — and the index would still say it was at the end.+/// These take the offset they want and are therefore immune to whatever ran last.+fn write_all_at(file: &mut File, path: &Path, offset: u64, bytes: &[u8]) -> Result<()> {+ file.seek(SeekFrom::Start(offset)).map_err(|e| scratch_error(path, "seek in", e))?;+ file.write_all(bytes).map_err(|e| scratch_error(path, "write to", e))+}++fn read_exact_at(file: &mut File, path: &Path, offset: u64, into: &mut [u8]) -> Result<()> {+ file.seek(SeekFrom::Start(offset)).map_err(|e| scratch_error(path, "seek in", e))?;+ file.read_exact(into).map_err(|e| scratch_error(path, "read back from", e))+}++fn scratch_error(path: &Path, doing: &str, e: std::io::Error) -> crate::proto::Error {+ crate::proto::Error(format!(+ "cannot {doing} the .mamaps body scratch file {}: {e}",+ path.display(),+ ))+}+ /// Raw DEFLATE over everything but the body header. ///+/// Public so a generator can run it on a worker thread rather than leaving it on the appending+/// thread — see [`StreamWriter::append_stored`] for why that is the difference between using one+/// core and using all of them.+/// /// The 16-byte body header is left uncompressed ahead of the frame so a reader can read `raw_len` /// out of it and allocate the output exactly once, before inflating a single byte.-fn compress(encoded: &[u8]) -> Vec<u8> {+pub fn compress_body(encoded: &[u8]) -> Vec<u8> { let header_len = body::BODY_HEADER_LEN; let mut out = Vec::with_capacity(encoded.len()); out.extend_from_slice(&encoded[..header_len]);