maps: one DEFLATE state per worker, not per tile: encode 7.8x faster
- Commit
f8eaeb7945b981c515ac3339a2b331a5e5f3716f- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-28 22:46 UTC (3 months ago)
- Parents
fb3f3c8
Diff
library/tilecodec/src/main/rust/src/gz.rs
diff --git a/library/tilecodec/src/main/rust/src/gz.rs b/library/tilecodec/src/main/rust/src/gz.rsindex fdbfde1c07..9dcde721b9 100644--- a/library/tilecodec/src/main/rust/src/gz.rs+++ b/library/tilecodec/src/main/rust/src/gz.rs@@ -17,6 +17,12 @@ const FCOMMENT: u8 = 1 << 4; /// DEFLATE level. 9 is the usual archive setting: tiles are written once and /// streamed by range request many times, so bytes matter more than build time.+///+/// Six was tried, on the theory that `encode`'s 43.9 s of a 135.8 s California build was+/// mostly compression. It is not: level six measured 44.8 s — inside the noise — for 0.12%+/// more bytes. The cost in that phase is stage C, body serialisation and *building the+/// compressor* ([`Compressor`]), not the deflate itself, so there is nothing here to trade+/// and the better ratio is free. Worth recording so nobody re-runs the experiment. const LEVEL: u8 = 9; /// Wrap `data` in a gzip stream.@@ -81,6 +87,19 @@ impl Compressor { /// Wrap `data` in a gzip stream, reusing this compressor's state. pub fn compress(&mut self, data: &[u8]) -> Vec<u8> {+ // Length first, so the mutable borrow ends before `frame` reads `scratch`.+ let n = self.deflate(data).len();+ frame(data, &self.scratch[..n])+ }++ /// Raw DEFLATE of `data`, reusing this compressor's state.+ ///+ /// Exactly the bytes `miniz_oxide::deflate::compress_to_vec(data, LEVEL)` returns, minus+ /// the 65,712-byte state it would build to return them. Split out of [`Self::compress`]+ /// because `.mamaps` bodies are raw DEFLATE behind an uncompressed header rather than a+ /// gzip frame, and that path needs the reuse just as badly — see+ /// [`crate::mamaps::write::compress_body_with`].+ pub fn deflate(&mut self, data: &[u8]) -> &[u8] { use miniz_oxide::deflate::core::{compress, TDEFLFlush, TDEFLStatus}; if self.used {@@ -115,7 +134,7 @@ impl Compressor { other => panic!("deflate failed unexpectedly: {other:?}"), } }- frame(data, &self.scratch[..at])+ &self.scratch[..at] } } @@ -240,6 +259,40 @@ mod tests { /// behind would still produce a VALID gzip stream, just a different one, and only /// comparing the bytes of the second and later calls catches it. So the corpus is /// run through a single compressor in sequence, and each result is checked against+ /// [`Compressor::deflate`] is what `.mamaps` bodies go through, so it has to match the+ /// one-shot call just as [`Compressor::compress`] does — and it must keep matching across a+ /// run of bodies, because a generator reuses one state for a whole zoom.+ ///+ /// The sizes below are the shape a tiler actually produces: one large body, then hundreds of+ /// small ones. A `reset` that dropped the dictionary would still pass on the first body.+ #[test]+ fn the_reusable_deflate_matches_the_one_shot_one() {+ let mut corpus: Vec<Vec<u8>> = vec![+ Vec::new(),+ b"x".to_vec(),+ REAL_RAW.to_vec(),+ vec![7u8; 250_000],+ ];+ for i in 0..200u32 {+ corpus.push(+ format!("body {i}: a tile layer with repeated repeated repeated keys")+ .into_bytes(),+ );+ }+ let mut reusable = Compressor::new();+ for (i, data) in corpus.iter().enumerate() {+ let want = miniz_oxide::deflate::compress_to_vec(data, LEVEL);+ let got = reusable.deflate(data).to_vec();+ assert!(+ got == want,+ "corpus[{i}] ({} byte(s)): reused {} byte(s), one-shot {}",+ data.len(),+ got.len(),+ want.len(),+ );+ }+ }+ /// a fresh one-shot call. #[test] fn the_reusable_compressor_matches_the_one_shot_one() {
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 cfa75e895d..c37043c988 100644--- a/library/tilecodec/src/main/rust/src/mamaps/write.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/write.rs@@ -67,15 +67,7 @@ use crate::stream::OPEN_PREFIX_BYTES; /// Leaf entries per leaf to start with, matching what the published PMTiles archive uses. pub const DEFAULT_LEAF_CAPACITY: u32 = 4096; -/// DEFLATE level.-///-/// Nine, as `gz.rs` uses, because a basemap is written once and read forever.-///-/// Six was tried, on the theory that `encode`'s 43.9 s of a 135.8 s California build was mostly-/// compression. It is not: level six measured 44.8 s — inside the noise — for 0.12% more bytes. The-/// cost in that phase is stage C and body serialisation, not the deflate, so there is nothing here to-/// trade and the better ratio is free. Worth recording so nobody re-runs the experiment.-const LEVEL: u8 = 9;+/// Raw DEFLATE over everything but the body header. /// What a build declares about itself before the first tile. pub struct Options {@@ -708,10 +700,28 @@ fn scratch_error(path: &Path, doing: &str, e: std::io::Error) -> crate::proto::E /// 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. pub fn compress_body(encoded: &[u8]) -> Vec<u8> {+ compress_body_with(&mut crate::gz::Compressor::new(), encoded)+}++/// [`compress_body`], reusing a DEFLATE state the caller owns.+///+/// **This is the one a generator should call.** `miniz_oxide::deflate::compress_to_vec` builds+/// a fresh `CompressorOxide` per call — 65,712 bytes of inline arrays, much of it zeroed on+/// construction — and a tiler calls it once per tile across every core it has. At that point+/// the construction *is* the encode pass: a us-west z13 build compressed 237,040 tiles, so+/// 15.6 GB of allocate-and-zero on 64 threads, and encode measured 226 s against 34 s for the+/// zoom below it at 1.6x the output. Every thread was busy and none of them was compressing.+///+/// [`crate::gz::Compressor`] carries the same story from the gzip side, where it was measured+/// going *backwards* past four threads. This is that fix applied to `.mamaps`.+///+/// Byte-identical to [`compress_body`], because `reset` keeps the parameters and DEFLATE+/// output is a function of the input and the parameters alone.+pub fn compress_body_with(deflate: &mut crate::gz::Compressor, 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]);- out.extend_from_slice(&miniz_oxide::deflate::compress_to_vec(&encoded[header_len..], LEVEL));+ out.extend_from_slice(deflate.deflate(&encoded[header_len..])); out }
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 3e0b67a63b..b350f3f3f6 100644--- a/scripts/maps/mamaps_build/src/tiler.rs+++ b/scripts/maps/mamaps_build/src/tiler.rs@@ -650,7 +650,11 @@ fn encode_batch( batch .into_par_iter() .with_min_len(min_len)- .map(|(id, mut layers)| {+ // One DEFLATE state per worker, not one per tile. `compress_to_vec` builds a+ // 65,712-byte `CompressorOxide` every call, and at a tile each across 64 cores that+ // construction swamps the compression it exists to do -- see+ // `mamaps::write::compress_body_with`.+ .map_init(tilecodec::gz::Compressor::new, |deflate, (id, mut layers)| { // **Stage C**, per tile: winding normalised, hole containment resolved, degenerate // rings dropped. Once, here, in `f64` with no frame budget, instead of every frame // on device in `i32` under one. This is what makes `FLAG_RINGS_VALIDATED` true.@@ -668,7 +672,7 @@ fn encode_batch( let body = Body { extent: EXTENT as u16, layers }; let encoded = tilecodec::mamaps::body::serialize(&body)?; let raw_len = encoded.len();- let stored = tilecodec::mamaps::write::compress_body(&encoded);+ let stored = tilecodec::mamaps::write::compress_body_with(deflate, &encoded); Ok((id, Some((stored, raw_len)), rings)) }) .collect()