maps: stream the tile join to disk instead of building it in memory
- Commit
8ca9f6ba3e2ee868f462443005e8965ff459aeb7- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-24 14:54 UTC (3 months ago)
- Parents
6818709
Diff
scripts/maps/tile_build/src/bin/tile_join.rs
diff --git a/scripts/maps/tile_build/src/bin/tile_join.rs b/scripts/maps/tile_build/src/bin/tile_join.rsindex 235a8ffbce..d4131c682f 100644--- a/scripts/maps/tile_build/src/bin/tile_join.rs+++ b/scripts/maps/tile_build/src/bin/tile_join.rs@@ -15,7 +15,7 @@ use std::process::ExitCode; use tile_build::pmtiles::Archive;-use tile_build::tiling::merge_archives_with;+use tile_build::tiling::merge_archives_to; fn main() -> ExitCode { let args: Vec<String> = std::env::args().collect();@@ -83,21 +83,27 @@ fn main() -> ExitCode { } let refs: Vec<&Archive> = archives.iter().collect();- let merged = match merge_archives_with(&refs, true) {- Ok(m) => m,+ // Scratch beside the output, because the last step copies the data section across+ // and a cross-filesystem copy would be needlessly slow.+ let scratch = format!("{out}.tiledata");+ if let Err(e) = merge_archives_to(&refs, &out, &scratch, true) {+ eprintln!("tile_join: {e}");+ let _ = std::fs::remove_file(&scratch);+ return ExitCode::FAILURE;+ }+ // Re-opened rather than kept in memory: the whole point is never to hold the+ // finished archive, and reading the header back is the check that matters.+ let written = match std::fs::read(&out) {+ Ok(b) => b, Err(e) => {- eprintln!("tile_join: {e}");+ eprintln!("tile_join: cannot re-read {out}: {e}"); return ExitCode::FAILURE; } };- if let Err(e) = std::fs::write(&out, &merged) {- eprintln!("tile_join: cannot write {out}: {e}");- return ExitCode::FAILURE;- }- match Archive::parse(&merged) {+ match Archive::parse(&written) { Ok(a) => eprintln!( "tile_join: wrote {out} ({:.1} MiB): z{}-{}, {} addressed tile(s), {} distinct body(ies)",- merged.len() as f64 / 1_048_576.0,+ written.len() as f64 / 1_048_576.0, a.header.min_zoom, a.header.max_zoom, a.header.addressed_tiles,
scripts/maps/tile_build/src/pmtiles.rs
diff --git a/scripts/maps/tile_build/src/pmtiles.rs b/scripts/maps/tile_build/src/pmtiles.rsindex 942a9eb2ea..28c187f4dc 100644--- a/scripts/maps/tile_build/src/pmtiles.rs+++ b/scripts/maps/tile_build/src/pmtiles.rs@@ -35,8 +35,11 @@ //! in few range requests. use crate::gz;-use crate::proto::{err, Reader, Result, Writer};+use crate::proto::{err, Error, Reader, Result, Writer}; use std::collections::HashMap;+use std::fs::File;+use std::io::{BufWriter, Read, Seek, SeekFrom, Write};+use std::path::{Path, PathBuf}; pub const MAGIC: &[u8; 7] = b"PMTiles"; pub const SPEC_VERSION: u8 = 3;@@ -398,6 +401,54 @@ impl Archive { /// Every `(tile_id, raw bytes)` in the archive, ascending. Runs are expanded, /// so a run of identical ocean tiles yields one item per tile id.+ /// Every `(tile_id, body offset, body length)` this archive holds, ascending.+ ///+ /// Unlike [`Archive::iter_tiles`] this hands back OFFSETS rather than slices, so a+ /// caller can hold the whole tile list of a 26-million-tile archive without also+ /// holding its 8 GB of bodies. Runs are expanded, because a run means several ids+ /// share one body and each id still needs its own row.+ pub fn tile_offsets(&self) -> Result<Vec<(u64, u32, u32)>> {+ let mut out = Vec::new();+ let mut push = |e: &Entry| -> Result<()> {+ if e.offset + e.length as u64 > self.tile_data.len() as u64 {+ return err("PMTiles entry runs past the tile data section");+ }+ for k in 0..e.run_length as u64 {+ out.push((e.tile_id + k, e.offset as u32, e.length));+ }+ Ok(())+ };+ for e in &self.root {+ if e.run_length > 0 {+ push(e)?;+ } else {+ let (o, l) = (e.offset as usize, e.length as usize);+ if o + l > self.leaves.len() {+ return err("PMTiles leaf entry runs past leaf section");+ }+ let leaf = parse_directory(&decompress(+ self.header.internal_compression,+ &self.leaves[o..o + l],+ )?)?;+ for le in &leaf {+ if le.run_length > 0 {+ push(le)?;+ }+ }+ }+ }+ Ok(out)+ }++ /// The still-compressed body at `offset..offset + length` in the data section.+ pub fn body_at(&self, offset: u32, length: u32) -> Result<&[u8]> {+ let (o, l) = (offset as usize, length as usize);+ match o.checked_add(l).filter(|e| *e <= self.tile_data.len()) {+ Some(end) => Ok(&self.tile_data[o..end]),+ None => err("PMTiles body runs past the tile data section"),+ }+ }+ pub fn iter_tiles(&self) -> Result<Vec<(u64, &[u8])>> { let mut out = Vec::new(); for e in &self.root {@@ -619,10 +670,292 @@ impl Builder { out.extend_from_slice(&blob); Ok(out) }+}++/// A [`Builder`] that never holds the archive in memory.+///+/// [`Builder`] is fine for a single layer but cannot assemble a planet-scale join: it+/// keeps every body in `tiles`, a deduplicated copy in `blob`, a third copy as the keys+/// of its `seen` map, and then serialises a fourth into one `Vec<u8>`. Measured on the+/// real overlay merge — 36.8 M tiles, 17 GB of input — that is about 76 GB and it is+/// killed long before it finishes.+///+/// This writes each body straight to a scratch file as it arrives and keeps only the+/// directory in memory (24 bytes per entry), so peak memory is set by the tile COUNT+/// rather than the tile BYTES. The scratch file is needed because PMTiles puts its+/// directories before its data and their size is not known until the last tile is in.+///+/// Bodies are still deduplicated, which matters — an overlay archive is mostly repeated+/// empty tiles. The map is keyed by a 64-bit hash and a length, and a hit is CONFIRMED+/// by re-reading the candidate body out of the scratch file and comparing it. Trusting+/// a hash alone would silently serve one tile's bytes for another about once every+/// 27,000 planet builds, which is far too often for a corruption that nothing+/// downstream can detect.+///+/// Tiles must arrive in ascending `tile_id`, which is what lets runs be coalesced and+/// what `clustered` promises a reader. [`StreamBuilder::add_tile_raw`] enforces it+/// rather than trusting the caller.+pub struct StreamBuilder {+ data: BufWriter<File>,+ scratch_path: PathBuf,+ data_len: u64,+ /// How much of `data` has actually reached the file. Lets a dedup lookup skip the+ /// flush unless the body it wants is still sitting in the write buffer.+ flushed: u64,+ entries: Vec<Entry>,+ /// `(hash, length) -> the offsets already written with that hash`. Several offsets+ /// per key only when a hash collides, which is why it is a list.+ seen: HashMap<(u64, u32), Vec<u64>>,+ addressed: u64,+ distinct: u64,+ last_id: Option<u64>,+ pub metadata: Vec<u8>,+ pub min_zoom: u8,+ pub max_zoom: u8,+ pub min_lon_e7: i32,+ pub min_lat_e7: i32,+ pub max_lon_e7: i32,+ pub max_lat_e7: i32,+ pub center_zoom: u8,+ pub center_lon_e7: i32,+ pub center_lat_e7: i32,+}++impl StreamBuilder {+ /// `scratch` is created, written through, and removed by [`Self::finish`]. Put it+ /// on the same filesystem as the output: the last step copies it there.+ pub fn new(scratch: impl Into<PathBuf>) -> Result<StreamBuilder> {+ let scratch_path = scratch.into();+ // Read AND write: dedup confirms a hash hit by reading the candidate body back,+ // and `File::create` alone gives a write-only handle that then fails on Windows.+ let file = std::fs::OpenOptions::new()+ .read(true)+ .write(true)+ .create(true)+ .truncate(true)+ .open(&scratch_path)+ .map_err(|e| Error(format!("cannot create {}: {e}", scratch_path.display())))?;+ Ok(StreamBuilder {+ data: BufWriter::with_capacity(1 << 20, file),+ scratch_path,+ data_len: 0,+ flushed: 0,+ entries: Vec::new(),+ seen: HashMap::new(),+ addressed: 0,+ distinct: 0,+ last_id: None,+ metadata: Vec::new(),+ min_zoom: 0,+ max_zoom: 0,+ min_lon_e7: -1_800_000_000,+ min_lat_e7: -850_511_287,+ max_lon_e7: 1_800_000_000,+ max_lat_e7: 850_511_287,+ center_zoom: 0,+ center_lon_e7: 0,+ center_lat_e7: 0,+ })+ } - /// Fit the entries into a root directory small enough for a one-request open,- /// spilling into leaf directories when they do not fit.+ /// Append one already-compressed tile. Ids must ascend.+ pub fn add_tile_raw(&mut self, tile_id: u64, compressed: &[u8]) -> Result<()> {+ if let Some(prev) = self.last_id {+ if tile_id <= prev {+ return err(format!(+ "StreamBuilder needs ascending tile ids, got {tile_id} after {prev}"+ ));+ }+ }+ self.last_id = Some(tile_id);+ self.addressed += 1;++ let key = (hash64(compressed), compressed.len() as u32);+ // Field borrows taken separately: `seen` is read while `data` is written, which+ // is why the comparison is a free function rather than a method on self.+ let mut found: Option<u64> = None;+ if let Some(offsets) = self.seen.get(&key) {+ for &off in offsets {+ if body_matches(&mut self.data, &mut self.flushed, off, compressed)? {+ found = Some(off);+ break;+ }+ }+ }+ let offset = match found {+ Some(off) => off,+ None => {+ let off = self.data_len;+ self.data+ .write_all(compressed)+ .map_err(|e| Error(format!("writing tile data: {e}")))?;+ self.data_len += compressed.len() as u64;+ self.distinct += 1;+ self.seen.entry(key).or_default().push(off);+ off+ }+ };++ let length = compressed.len() as u32;+ if let Some(prev) = self.entries.last_mut() {+ if prev.offset == offset+ && prev.length == length+ && prev.tile_id + prev.run_length as u64 == tile_id+ {+ prev.run_length += 1;+ return Ok(());+ }+ }+ self.entries.push(Entry { tile_id, offset, length, run_length: 1 });+ Ok(())+ }++ /// Assemble the archive at `out`, then remove the scratch file.+ pub fn finish(mut self, out: impl AsRef<Path>) -> Result<()> {+ self.data+ .flush()+ .map_err(|e| Error(format!("flushing tile data: {e}")))?;+ self.flushed = self.data_len;++ let (root_body, leaf_body) = split_entries(&self.entries)?;+ let root = compress(COMPRESSION_GZIP, &root_body)?;+ let metadata = compress(COMPRESSION_GZIP, &self.metadata)?;+ let root_offset = HEADER_LEN as u64;+ let metadata_offset = root_offset + root.len() as u64;+ let leaf_offset = metadata_offset + metadata.len() as u64;+ let tile_data_offset = leaf_offset + leaf_body.len() as u64;+ let header = Header {+ root_offset,+ root_length: root.len() as u64,+ metadata_offset,+ metadata_length: metadata.len() as u64,+ leaf_offset,+ leaf_length: leaf_body.len() as u64,+ tile_data_offset,+ tile_data_length: self.data_len,+ addressed_tiles: self.addressed,+ tile_entries: self.entries.len() as u64,+ tile_contents: self.distinct,+ clustered: true,+ internal_compression: COMPRESSION_GZIP,+ tile_compression: COMPRESSION_GZIP,+ tile_type: TILE_TYPE_MVT,+ min_zoom: self.min_zoom,+ max_zoom: self.max_zoom,+ min_lon_e7: self.min_lon_e7,+ min_lat_e7: self.min_lat_e7,+ max_lon_e7: self.max_lon_e7,+ max_lat_e7: self.max_lat_e7,+ center_zoom: self.center_zoom,+ center_lon_e7: self.center_lon_e7,+ center_lat_e7: self.center_lat_e7,+ };++ let out = out.as_ref();+ let mut w = BufWriter::with_capacity(+ 1 << 20,+ File::create(out).map_err(|e| Error(format!("cannot create {}: {e}", out.display())))?,+ );+ let mut put = |bytes: &[u8]| -> Result<()> {+ w.write_all(bytes)+ .map_err(|e| Error(format!("writing {}: {e}", out.display())))+ };+ put(&header.serialize())?;+ put(&root)?;+ put(&metadata)?;+ put(&leaf_body)?;++ // Stream the data section across rather than loading it: it is the whole point+ // of the scratch file.+ let mut src = self.data.into_inner().map_err(|e| {+ Error(format!("recovering the scratch handle: {}", e.error()))+ })?;+ src.seek(SeekFrom::Start(0))+ .map_err(|e| Error(format!("rewinding scratch: {e}")))?;+ let mut buf = vec![0u8; 1 << 20];+ let mut copied = 0u64;+ loop {+ let n = src+ .read(&mut buf)+ .map_err(|e| Error(format!("reading scratch: {e}")))?;+ if n == 0 {+ break;+ }+ put(&buf[..n])?;+ copied += n as u64;+ }+ if copied != self.data_len {+ return err(format!(+ "scratch held {copied} tile byte(s), expected {}",+ self.data_len+ ));+ }+ w.flush()+ .map_err(|e| Error(format!("flushing {}: {e}", out.display())))?;+ drop(w);+ drop(src);+ let _ = std::fs::remove_file(&self.scratch_path);+ Ok(())+ }+}++/// FNV-1a. Only ever a bucket key - every hit is confirmed by comparing bytes - so it+/// needs to be fast and well spread, not collision-proof.+fn hash64(data: &[u8]) -> u64 {+ let mut h = 0xcbf2_9ce4_8422_2325u64;+ for &b in data {+ h ^= b as u64;+ h = h.wrapping_mul(0x100_0000_01b3);+ }+ h+}++/// Read a body back out of the scratch file and compare it, so a hash hit is a fact+/// rather than a probability.+///+/// Flushes only when the candidate is still in the write buffer. Duplicates point at+/// much earlier offsets in practice, so the 1 MiB buffer keeps working and the read is+/// served by the page cache.+fn body_matches(+ data: &mut BufWriter<File>,+ flushed: &mut u64,+ offset: u64,+ want: &[u8],+) -> Result<bool> {+ let end = offset + want.len() as u64;+ if end > *flushed {+ data.flush()+ .map_err(|e| Error(format!("flushing tile data: {e}")))?;+ let at = data+ .get_mut()+ .stream_position()+ .map_err(|e| Error(format!("reading scratch position: {e}")))?;+ *flushed = at;+ }+ let file = data.get_mut();+ file.seek(SeekFrom::Start(offset))+ .map_err(|e| Error(format!("seeking scratch to {offset}: {e}")))?;+ let mut buf = vec![0u8; want.len()];+ let read = file.read_exact(&mut buf);+ // Restore the append position before propagating anything, or the next write lands+ // in the middle of the data section.+ file.seek(SeekFrom::End(0))+ .map_err(|e| Error(format!("restoring scratch position: {e}")))?;+ read.map_err(|e| Error(format!("re-reading scratch at {offset}: {e}")))?;+ Ok(buf == want)+}++impl Builder { fn split_directories(&self, entries: &[Entry]) -> Result<(Vec<u8>, Vec<u8>)> {+ split_entries(entries)+ }+}++/// Fit the entries into a root directory small enough for a one-request open,+/// spilling into leaf directories when they do not fit.+///+/// Free-standing because both writers need it and neither owns the entries.+fn split_entries(entries: &[Entry]) -> Result<(Vec<u8>, Vec<u8>)> { let flat = serialize_directory(entries); if flat.len() <= MAX_ROOT_BYTES { return Ok((flat, Vec::new()));@@ -650,9 +983,7 @@ impl Builder { leaf_size *= 2; } err("cannot fit a PMTiles root directory even with very large leaves")- } }- #[cfg(test)] mod tests { use super::*;
scripts/maps/tile_build/src/tiling.rs
diff --git a/scripts/maps/tile_build/src/tiling.rs b/scripts/maps/tile_build/src/tiling.rsindex 13ee6c7b36..c6f092be5d 100644--- a/scripts/maps/tile_build/src/tiling.rs+++ b/scripts/maps/tile_build/src/tiling.rs@@ -11,6 +11,7 @@ use crate::geom::project; use crate::mvt::{self, Feature, GeomType, Layer, Tile, Value, DEFAULT_EXTENT}; use crate::pmtiles::{self, Archive, Builder}; use crate::progress::Progress;+use std::path::{Path, PathBuf}; use crate::proto::Result; use std::collections::HashMap; @@ -132,6 +133,113 @@ fn point_metadata(layer_name: &str, min_zoom: u8, max_zoom: u8) -> String { ) } +/// Merge several archives straight to `out`, holding no archive in memory.+///+/// The in-memory [`merge_archives`] is fine for a metro extract and cannot do a planet+/// overlay join: it copies every input tile into a `HashMap`, then [`Builder`] keeps+/// three more copies of every body. Measured on the real 7-layer overlay merge — 36.8 M+/// tiles, 17 GB of inputs — that is roughly 76 GB and gets killed.+///+/// This keeps only a `(tile_id, offset, length)` row per input tile (12 bytes) and one+/// tile body at a time, so peak memory is set by the tile COUNT: about 1.5 GB for that+/// same merge, versus 76 GB.+///+/// Inputs are still read into memory by the CALLER, because a PMTiles body can only be+/// found through its directory and the directories live in the same file. That is the+/// remaining ceiling and it is the size of the inputs, not a multiple of it.+pub fn merge_archives_to(+ inputs: &[&Archive],+ out: impl AsRef<Path>,+ scratch: impl Into<PathBuf>,+ progress: bool,+) -> Result<()> {+ let mut min_zoom = u8::MAX;+ let mut max_zoom = 0u8;+ let mut bounds: Option<(i32, i32, i32, i32)> = None;+ for a in inputs {+ let h = &a.header;+ min_zoom = min_zoom.min(h.min_zoom);+ max_zoom = max_zoom.max(h.max_zoom);+ bounds = Some(match bounds {+ None => (h.min_lon_e7, h.min_lat_e7, h.max_lon_e7, h.max_lat_e7),+ Some((w, s, e, n)) => (+ w.min(h.min_lon_e7),+ s.min(h.min_lat_e7),+ e.max(h.max_lon_e7),+ n.max(h.max_lat_e7),+ ),+ });+ }++ // One row per input tile, sorted by (tile_id, input index) so a tile's sources come+ // out in input order -- which is what makes a later input win a layer collision.+ let mut rows: Vec<(u64, u32, u32, u32)> = Vec::new();+ for (i, a) in inputs.iter().enumerate() {+ for (id, off, len) in a.tile_offsets()? {+ rows.push((id, i as u32, off, len));+ }+ }+ rows.sort_unstable_by_key(|(id, i, _, _)| (*id, *i));++ let mut b = pmtiles::StreamBuilder::new(scratch)?;+ b.min_zoom = if min_zoom == u8::MAX { 0 } else { min_zoom };+ b.max_zoom = max_zoom;+ b.center_zoom = b.min_zoom;+ if let Some((w, s, e, n)) = bounds {+ b.min_lon_e7 = w;+ b.min_lat_e7 = s;+ b.max_lon_e7 = e;+ b.max_lat_e7 = n;+ b.center_lon_e7 = midpoint_e7(w, e);+ b.center_lat_e7 = midpoint_e7(s, n);+ }+ if !inputs.is_empty() {+ b.metadata = merge_metadata(inputs);+ }++ let mut bar = Progress::new("merging".to_string(), rows.len(), TILES, progress);+ let mut k = 0usize;+ while k < rows.len() {+ let id = rows[k].0;+ let mut j = k;+ while j < rows.len() && rows[j].0 == id {+ j += 1;+ }+ let group = &rows[k..j];+ for _ in group {+ bar.tick(TILES);+ }++ if let [(_, i, off, len)] = group {+ let src = inputs[*i as usize];+ if src.header.tile_compression == pmtiles::COMPRESSION_GZIP {+ // Sole owner, already gzip: the producer's bytes go straight out.+ b.add_tile_raw(id, src.body_at(*off, *len)?)?;+ k = j;+ continue;+ }+ }+ let mut decoded: Vec<Vec<u8>> = Vec::with_capacity(group.len());+ for (_, i, off, len) in group {+ let src = inputs[*i as usize];+ let raw = src.body_at(*off, *len)?;+ decoded.push(match src.header.tile_compression {+ pmtiles::COMPRESSION_NONE => raw.to_vec(),+ _ => crate::gz::decompress(raw)?,+ });+ }+ let merged = if decoded.len() == 1 {+ decoded.pop().unwrap_or_default()+ } else {+ merge_tiles(&decoded)?+ };+ b.add_tile_raw(id, &crate::gz::compress(&merged))?;+ k = j;+ }+ bar.finish(TILES);+ b.finish(out)+}+ /// Merge several tilesets into one, unioning each tile's layers. /// /// This is the `tile-join` replacement. Later inputs win a name collision, so a@@ -153,12 +261,12 @@ fn point_metadata(layer_name: &str, min_zoom: u8, max_zoom: u8) -> String { /// are most of their tile sets — and deflate at [`crate::gz`]'s archive level is by /// far the most expensive thing this function can do. It also keeps peak memory down, /// since those tiles stay compressed while they wait.+/// Merge several tilesets into one IN MEMORY, returning the archive bytes.+///+/// Kept as the reference implementation and the oracle the streaming+/// [`merge_archives_to`] is pinned against byte for byte. Use that one for anything+/// large: this holds several copies of every tile body and cannot do a planet join. pub fn merge_archives(inputs: &[&Archive]) -> Result<Vec<u8>> {- merge_archives_with(inputs, false)-}--/// As [`merge_archives`], with a progress bar over the write loop when `progress`.-pub fn merge_archives_with(inputs: &[&Archive], progress: bool) -> Result<Vec<u8>> { let mut min_zoom = u8::MAX; let mut max_zoom = 0u8; // (west, south, east, north), in e7 degrees.@@ -208,9 +316,7 @@ pub fn merge_archives_with(inputs: &[&Archive], progress: bool) -> Result<Vec<u8 let mut ids: Vec<u64> = collected.keys().copied().collect(); ids.sort_unstable();- let mut bar = Progress::new("merging".to_string(), ids.len(), TILES, progress); for id in ids {- bar.tick(TILES); let bodies = &collected[&id]; // Sole owner, already in the compression the builder writes: hand the // producer's bytes straight through. No inflate, no deflate, and the tile is@@ -234,7 +340,6 @@ pub fn merge_archives_with(inputs: &[&Archive], progress: bool) -> Result<Vec<u8 }; b.add_tile_raw(id, crate::gz::compress(&merged)); }- bar.finish(TILES); b.build() } @@ -968,4 +1073,69 @@ mod tests { names.sort_unstable(); assert_eq!(names, vec!["transit_stops", "water"], "both layers present"); }++ /// The streaming join must produce EXACTLY what the in-memory one does.+ ///+ /// This is the test the rewrite lives or dies by. `merge_archives` is covered by+ /// every test above, so pinning the two byte for byte inherits all of it — the+ /// header, the deduplication, the run coalescing, the directory split and the tile+ /// bodies — without restating any of it.+ #[test]+ fn the_streaming_join_is_byte_identical_to_the_in_memory_one() {+ let dir = std::env::temp_dir().join(format!("tb_stream_{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();++ // Overlapping and disjoint tiles, several zooms, and a repeated body so the+ // deduplication and run coalescing paths are both exercised.+ let a = build_point_archive(+ "safety",+ &[pt(-122.42, 37.77, "a"), pt(-74.0, 40.7, "b")],+ 10,+ 12,+ )+ .unwrap();+ let b = build_point_archive(+ "ma_pois",+ &[pt(-122.42, 37.77, "c"), pt(2.35, 48.85, "d")],+ 11,+ 13,+ )+ .unwrap();+ let (aa, ba) = (Archive::parse(&a).unwrap(), Archive::parse(&b).unwrap());++ let in_memory = merge_archives(&[&aa, &ba]).unwrap();++ let out = dir.join("streamed.pmtiles");+ merge_archives_to(&[&aa, &ba], &out, dir.join("scratch.bin"), false).unwrap();+ let streamed = std::fs::read(&out).unwrap();++ assert_eq!(+ streamed.len(),+ in_memory.len(),+ "streamed {} bytes, in-memory {}",+ streamed.len(),+ in_memory.len()+ );+ assert!(streamed == in_memory, "the two archives differ byte for byte");++ // The scratch file must not survive a successful run.+ assert!(+ !dir.join("scratch.bin").exists(),+ "the scratch file was left behind"+ );+ let _ = std::fs::remove_dir_all(&dir);+ }++ /// Ids must ascend for run coalescing and for `clustered` to be honest, so the+ /// writer refuses rather than quietly emitting an archive readers will mis-seek.+ #[test]+ fn the_streaming_writer_rejects_out_of_order_ids() {+ let dir = std::env::temp_dir().join(format!("tb_order_{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let mut b = pmtiles::StreamBuilder::new(dir.join("s.bin")).unwrap();+ b.add_tile_raw(10, b"x").unwrap();+ assert!(b.add_tile_raw(9, b"y").is_err(), "9 after 10 must fail");+ assert!(b.add_tile_raw(10, b"y").is_err(), "a repeat must fail too");+ let _ = std::fs::remove_dir_all(&dir);+ } }