Modern Apps git

← Modern-Apps.git

tilecodec: compress leaf index entries

Commit
0b06fa1a3b9e21900a422a3775839569b03182f7
Author
vayun-mathur <[email protected]>
When
2026-10-10 05:03 UTC (1 month ago)
Parents
65cfae7

Diff

library/tilecodec/src/main/rust/src/mamaps/header.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/header.rs b/library/tilecodec/src/main/rust/src/mamaps/header.rsindex bbf2527383..b3dfacbfa2 100644--- a/library/tilecodec/src/main/rust/src/mamaps/header.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/header.rs@@ -24,7 +24,7 @@ mod tests;  pub use consts::{     COMPRESSION_DEFLATE, COMPRESSION_NONE, COMPRESSION_ZSTD, FLAG_BODIES_COMPRESSED,-    FLAG_LEAF_LEN_64, FLAG_RINGS_VALIDATED, FLAG_RUN_LENGTH_PRESENT, FORMAT_VERSION,+    FLAG_LEAF_LEN_64, FLAG_LEAVES_COMPRESSED, FLAG_RINGS_VALIDATED, FLAG_RUN_LENGTH_PRESENT, FORMAT_VERSION,     FORMAT_VERSION_V9, FORMAT_VERSION_V10, HEADER_LEN, MAGIC, MAX_ZOOM, }; pub use types::Header;
library/tilecodec/src/main/rust/src/mamaps/header/consts.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/header/consts.rs b/library/tilecodec/src/main/rust/src/mamaps/header/consts.rsindex 2591168707..cca78d9b90 100644--- a/library/tilecodec/src/main/rust/src/mamaps/header/consts.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/header/consts.rs@@ -97,9 +97,21 @@ pub const FLAG_RINGS_VALIDATED: u16 = 1 << 2; /// (instead of u32 leaf_len at 72..76 plus 0-reserved at 76..80). Common /// path (NA ~418 MB) stays flag 0 + u32 + 0 — byte-identical to v1. pub const FLAG_LEAF_LEN_64: u16 = 1 << 3;+/// Each leaf is stored as one raw-DEFLATE frame (v9 only) rather than raw+/// fixed-stride entries.+///+/// The root stays raw — 32-byte stride, usable straight out of the opening+/// prefix — and each root entry's formerly-reserved word carries the frame's+/// stored length ([`crate::mamaps::index::RootEntry::stored_len`]). The reader+/// inflates one leaf to exactly `leaf_entry_count * 16` bytes and binary+/// searches in memory, so lookups keep their shape and their request count.+/// An older reader refuses cleanly: the flag is unknown to it, and so is the+/// non-zero reserved word. See [`crate::mamaps::index`] for the framing.+pub const FLAG_LEAVES_COMPRESSED: u16 = 1 << 4;  pub(super) const KNOWN_FLAGS: u16 =-    FLAG_BODIES_COMPRESSED | FLAG_RUN_LENGTH_PRESENT | FLAG_RINGS_VALIDATED | FLAG_LEAF_LEN_64;+    FLAG_BODIES_COMPRESSED | FLAG_RUN_LENGTH_PRESENT | FLAG_RINGS_VALIDATED | FLAG_LEAF_LEN_64+    | FLAG_LEAVES_COMPRESSED;  /// Bodies stored as written. pub const COMPRESSION_NONE: u8 = 0;
library/tilecodec/src/main/rust/src/mamaps/header/serialize.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/header/serialize.rs b/library/tilecodec/src/main/rust/src/mamaps/header/serialize.rsindex f6c0ed81ed..541edfcabe 100644--- a/library/tilecodec/src/main/rust/src/mamaps/header/serialize.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/header/serialize.rs@@ -2,7 +2,9 @@ //! //! Pure moves out of the former single-file header module; nothing here changed. -use super::consts::{FLAG_LEAF_LEN_64, FORMAT_VERSION, HEADER_LEN, MAGIC};+use super::consts::{+    FLAG_LEAF_LEN_64, FLAG_LEAVES_COMPRESSED, FORMAT_VERSION, FORMAT_VERSION_V9, HEADER_LEN, MAGIC,+}; use super::types::Header;  impl Header {@@ -10,7 +12,10 @@ impl Header {     pub fn serialize(&self) -> Vec<u8> {         let mut out = Vec::with_capacity(HEADER_LEN);         out.extend_from_slice(MAGIC);-        out.push(FORMAT_VERSION);+        // Compressed leaves are a v9 frame: the flag is unknown to a v8+        // reader, which refuses cleanly rather than misreading the leaf+        // section. Everything else keeps the v8 byte (and v8 readers).+        out.push(if (self.flags & FLAG_LEAVES_COMPRESSED) != 0 { FORMAT_VERSION_V9 } else { FORMAT_VERSION });         out.extend_from_slice(&(HEADER_LEN as u16).to_le_bytes());         out.extend_from_slice(&self.flags.to_le_bytes());         out.push(self.compression);
library/tilecodec/src/main/rust/src/mamaps/header/types.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/header/types.rs b/library/tilecodec/src/main/rust/src/mamaps/header/types.rsindex 0203c1ed0a..3f1085a426 100644--- a/library/tilecodec/src/main/rust/src/mamaps/header/types.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/header/types.rs@@ -3,7 +3,7 @@ //! //! Pure moves out of the former single-file header module; nothing here changed. -use super::consts::{FLAG_BODIES_COMPRESSED, FLAG_RINGS_VALIDATED, HEADER_LEN};+use super::consts::{FLAG_BODIES_COMPRESSED, FLAG_LEAVES_COMPRESSED, FLAG_RINGS_VALIDATED, HEADER_LEN};  /// What a reader must know before it can address anything. ///@@ -60,6 +60,14 @@ impl Header {         self.flags & FLAG_RINGS_VALIDATED != 0     } +    /// Each leaf is one raw-DEFLATE frame whose stored length rides in its+    /// root entry, rather than raw fixed-stride entries. The root itself is+    /// unchanged — still raw, still 32-byte stride, still inside the opening+    /// prefix.+    pub fn leaves_compressed(&self) -> bool {+        self.flags & FLAG_LEAVES_COMPRESSED != 0+    }+     /// This header's wire length: always 128 (v8 only).     pub fn wire_len(&self) -> usize {         HEADER_LEN
library/tilecodec/src/main/rust/src/mamaps/index.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/index.rs b/library/tilecodec/src/main/rust/src/mamaps/index.rsindex 4377a3d490..6743a4182e 100644--- a/library/tilecodec/src/main/rust/src/mamaps/index.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/index.rs@@ -1,10 +1,11 @@ //! The two-level index: a root of fixed-stride entries, each pointing at one leaf. //!-//! Both levels are **uncompressed and fixed stride**, which is the whole design. The root can-//! then be used straight out of the bytes a reader already fetched to read the header, with no-//! inflate step and no sequential decode — and a leaf can be binary-searched, because-//! [`LeafEntry::tile_id_lo`] is absolute within its leaf rather than a delta from the entry-//! before it.+//! The root is **uncompressed and fixed stride**, which is the load-bearing half of the design.+//! It is used straight out of the bytes a reader already fetched to read the header, with no+//! inflate step and no sequential decode. Each leaf is independently compressed (one raw-DEFLATE+//! frame per leaf, see [`compress_leaf`]); the reader inflates a leaf whole and then+//! binary-searches in memory, because [`LeafEntry::tile_id_lo`] is absolute within its leaf+//! rather than a delta from the entry before it. //! //! # The prefix budget //!@@ -17,11 +18,25 @@ //! [`super::write`] **asserts** the budget. A root that does not fit is a build failure, never a //! silent third round trip charged to every reader forever. //!+//! Leaf compression does not touch the budget: the root stays raw at the same 32-byte stride,+//! and each leaf's stored length rides in its root entry's formerly-reserved word.+//! //! # Addressing //! //! Tile ids are `pmtiles::tile_id` unchanged: space-filling, zoom-major and monotonic. Those are //! exactly the three properties the generator's spill bucketing and pyramid ranges already depend //! on, so inventing a curve here would buy nothing and break that coupling.+//!+//! # Leaf framing (v9)+//!+//! A stored leaf is one raw-DEFLATE frame over exactly `leaf_entry_count * 16` bytes of+//! [`serialize_leaf`] output. The frame's length is the root entry's `stored_len`; the inflated+//! length is known before the first byte inflates, so the reader allocates exactly once — the+//! same property bodies get from their uncompressed 16-byte header. DEFLATE, not zstd: leaves+//! must inflate on the `aarch64-linux-android` cdylib, where the only codec is `miniz_oxide`+//! (pure Rust, no C toolchain). Measured 0.39 on twenty random California leaves (2.54 GB →+//! ~1.00 GB); the root's reserved word stays zero for a raw legacy leaf, so old files keep+//! parsing without a version check on the read path.  use crate::proto::{err, Result}; @@ -43,6 +58,15 @@ pub struct RootEntry {     /// data section is past 4 GiB, but one leaf's 4096 bodies are not.     pub base_data_offset: u64,     pub leaf_entry_count: u32,+    /// The leaf's stored length in the leaf section.+    ///+    /// Zero for a raw legacy leaf (`leaf_entry_count * 16` bytes); otherwise the length of the+    /// one raw-DEFLATE frame ([`compress_leaf`]) that inflates to exactly that many bytes.+    /// Carried in the root entry's formerly-reserved word, so the root keeps its 32-byte stride+    /// and the opening-prefix budget is untouched. A reader never guesses: the length always+    /// comes from this field, which is what keeps a short range reply from poisoning a disk+    /// cache entry (see [`super::read`]).+    pub stored_len: u32, }  /// One tile, or a run of consecutive tiles that share a body.@@ -72,7 +96,7 @@ pub fn serialize_root(entries: &[RootEntry]) -> Vec<u8> {         out.extend_from_slice(&e.leaf_offset.to_le_bytes());         out.extend_from_slice(&e.base_data_offset.to_le_bytes());         out.extend_from_slice(&e.leaf_entry_count.to_le_bytes());-        out.extend_from_slice(&0u32.to_le_bytes());+        out.extend_from_slice(&e.stored_len.to_le_bytes());     }     debug_assert_eq!(out.len(), entries.len() * ROOT_ENTRY_LEN);     out@@ -87,14 +111,14 @@ pub fn parse_root(buf: &[u8]) -> Result<Vec<RootEntry>> {     }     let mut out = Vec::with_capacity(buf.len() / ROOT_ENTRY_LEN);     for chunk in buf.chunks_exact(ROOT_ENTRY_LEN) {-        if u32::from_le_bytes([chunk[28], chunk[29], chunk[30], chunk[31]]) != 0 {-            return err("a .mamaps root entry has a non-zero reserved word");-        }         out.push(RootEntry {             base_tile_id: u64_at(chunk, 0),             leaf_offset: u64_at(chunk, 8),             base_data_offset: u64_at(chunk, 16),             leaf_entry_count: u32::from_le_bytes([chunk[24], chunk[25], chunk[26], chunk[27]]),+            // Zero is a raw legacy leaf; non-zero is a DEFLATE frame of that stored length.+            // Either way the reader takes the length from here, never from arithmetic.+            stored_len: u32::from_le_bytes([chunk[28], chunk[29], chunk[30], chunk[31]]),         });     }     // Ascending, or the binary search below would silently return the wrong leaf rather than@@ -145,6 +169,45 @@ pub fn parse_leaf(buf: &[u8]) -> Result<Vec<LeafEntry>> {     Ok(out) } +/// One raw-DEFLATE frame over [`serialize_leaf`] output.+///+/// Deterministic for fixed input (same bytes in, same bytes out), which is what keeps builds+/// byte-identical. Level 9 is the archive setting — leaves are written once and fetched per+/// cold tile, so bytes matter more than build time; see [`crate::gz`] for the measured+/// non-trade behind the same choice on bodies. A leaf that would grow is stored raw instead+/// (the caller keeps `stored_len` zero), so compression never costs a byte.+pub fn compress_leaf(raw: &[u8]) -> Vec<u8> {+    miniz_oxide::deflate::compress_to_vec(raw, 9)+}++/// Inflate one leaf frame, allocating exactly once.+///+/// The output length is `leaf_entry_count * 16`, known from the root entry before the first+/// byte inflates — so there is no grow-and-copy and no guess, and a corrupt frame fails here+/// rather than as a wrong tile somewhere later. Raw DEFLATE (no zlib wrapper), matching what+/// [`compress_leaf`] emits.+pub fn decompress_leaf(stored: &[u8], raw_len: usize) -> Result<Vec<u8>> {+    if raw_len % LEAF_ENTRY_LEN != 0 {+        return err(format!(+            "a .mamaps leaf of {raw_len} bytes is not a whole number of {LEAF_ENTRY_LEN} byte entries",+        ));+    }+    let mut out = vec![0u8; raw_len];+    let written = miniz_oxide::inflate::decompress_slice_iter_to_slice(+        &mut out,+        std::iter::once(stored),+        false,+        false,+    )+    .map_err(|e| crate::proto::Error(format!("a .mamaps leaf will not inflate: {e:?}")))?;+    if written != raw_len {+        return err(format!(+            "a .mamaps leaf inflated to {written} bytes, not the {raw_len} its root entry declares",+        ));+    }+    Ok(out)+}+ fn u64_at(buf: &[u8], o: usize) -> u64 {     u64::from_le_bytes([         buf[o],@@ -205,6 +268,7 @@ mod tests {                 leaf_offset: (i * 64) as u64,                 base_data_offset: (i * 1000) as u64,                 leaf_entry_count: 4,+                stored_len: 0,             })             .collect()     }@@ -317,10 +381,41 @@ mod tests {     }      #[test]-    fn a_reserved_word_a_later_version_may_claim_is_checked() {-        let mut bytes = serialize_root(&root_of(&[0]));-        bytes[28] = 1;-        assert!(parse_root(&bytes).is_err());+    fn a_stored_length_a_later_version_may_claim_is_carried() {+        // Zero is a raw legacy leaf; non-zero is a DEFLATE frame of that length. Either way the+        // length round-trips through the word v8 reserved, and the root keeps its 32-byte stride.+        let mut root = root_of(&[0]);+        root[0].stored_len = 1234;+        let bytes = serialize_root(&root);+        assert_eq!(bytes.len(), ROOT_ENTRY_LEN);+        assert_eq!(&bytes[28..32], &1234u32.to_le_bytes());+        assert_eq!(parse_root(&bytes).expect("root"), root);+        // And the legacy all-zero word still parses, as a raw leaf.+        assert_eq!(parse_root(&serialize_root(&root_of(&[0]))).expect("legacy"), root_of(&[0]));+    }++    #[test]+    fn a_leaf_frame_round_trips_and_refuses_garbage() {+        let leaf = vec![+            LeafEntry { tile_id_lo: 0, run_length: 3, offset_delta: 0, length: 40 },+            LeafEntry { tile_id_lo: 3, run_length: 1, offset_delta: 40, length: 12 },+            LeafEntry { tile_id_lo: 9, run_length: 2, offset_delta: 52, length: 7 },+        ];+        let raw = serialize_leaf(&leaf);+        let stored = compress_leaf(&raw);+        let back = decompress_leaf(&stored, raw.len()).expect("inflate");+        assert_eq!(parse_leaf(&back).expect("parse"), leaf);+        // Deterministic: the same bytes in give the same bytes out, which is what keeps builds+        // byte-identical.+        assert_eq!(compress_leaf(&raw), stored);+        // A corrupt frame fails here rather than as a wrong tile later.+        let mut bad = stored.clone();+        let last = bad.len() - 1;+        bad[last] ^= 0xFF;+        assert!(decompress_leaf(&bad, raw.len()).is_err(), "a corrupt frame");+        // And a declared length that is not whole entries is refused before inflating.+        assert!(decompress_leaf(&stored, raw.len() + 1).is_err(), "a partial entry");+        assert!(decompress_leaf(&stored, raw.len() + LEAF_ENTRY_LEN).is_err(), "a wrong length");     }      /// **Invariant 4.** The generator's spill buckets and its per-zoom passes both key on
library/tilecodec/src/main/rust/src/mamaps/read/archive.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/read/archive.rs b/library/tilecodec/src/main/rust/src/mamaps/read/archive.rsindex 7cae00fa26..12827db116 100644--- a/library/tilecodec/src/main/rust/src/mamaps/read/archive.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/read/archive.rs@@ -105,6 +105,10 @@ impl<R: RangeReader> MamapsArchive<R> {     }      /// The parsed leaf a root entry addresses, from the cache or over the wire.+    ///+    /// A stored leaf is one raw-DEFLATE frame; it inflates whole to exactly+    /// `leaf_entry_count * 16` bytes and then binary-searches in memory like a raw leaf always+    /// did. The request count is unchanged: one range read per cold leaf, whatever it stores.     fn leaf(&mut self, root: &RootEntry) -> Result<Vec<LeafEntry>> {         if let Some(position) = self.leaves.iter().position(|(offset, _)| *offset == root.leaf_offset)         {@@ -114,13 +118,31 @@ impl<R: RangeReader> MamapsArchive<R> {             self.leaves.push(hit);             return Ok(entries);         }-        let len = root.leaf_entry_count as u64 * index::LEAF_ENTRY_LEN as u64;-        if root.leaf_offset + len > self.header.leaf_len as u64 {+        let raw_len = root.leaf_entry_count as u64 * index::LEAF_ENTRY_LEN as u64;+        let stored_len = if root.stored_len == 0 { raw_len } else { root.stored_len as u64 };+        if root.leaf_offset + stored_len > self.header.leaf_len as u64 {             return err("a .mamaps root entry runs past the leaf section");         }-        let length = u32::try_from(len)+        let length = u32::try_from(stored_len)             .map_err(|_| Error("a .mamaps leaf is larger than a single read".to_string()))?;-        let raw = self.exact(self.header.leaf_offset + root.leaf_offset, length, "a leaf")?;+        let stored = self.exact(self.header.leaf_offset + root.leaf_offset, length, "a leaf")?;+        // Zero is a raw legacy leaf; anything else is the frame length. The inflated length is+        // known from the entry count either way, so a corrupt frame fails here rather than as a+        // wrong tile later — and a read of the wrong length never reaches the disk cache.+        let raw = if root.stored_len == 0 {+            if stored.len() as u64 != raw_len {+                return err(format!(+                    "a .mamaps read of a leaf wanted {raw_len} bytes at {}, got {}",+                    self.header.leaf_offset + root.leaf_offset,+                    stored.len(),+                ));+            }+            stored+        } else {+            let raw_len = usize::try_from(raw_len)+                .map_err(|_| Error("a .mamaps leaf is larger than a single read".to_string()))?;+            index::decompress_leaf(&stored, raw_len)?+        };         let entries = index::parse_leaf(&raw)?;         if self.leaves.len() >= MAX_CACHED_LEAVES {             self.leaves.remove(0);
library/tilecodec/src/main/rust/src/mamaps/read/helpers.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/read/helpers.rs b/library/tilecodec/src/main/rust/src/mamaps/read/helpers.rsindex 1dc49bdfaa..777ed7baf0 100644--- a/library/tilecodec/src/main/rust/src/mamaps/read/helpers.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/read/helpers.rs@@ -107,12 +107,18 @@ pub fn read_all(bytes: &[u8]) -> Result<Vec<(u64, u32, Vec<u8>)>> {     dictionary.check_matches_schema()?;     let mut out = Vec::new();     for entry in &root {-        let len = entry.leaf_entry_count as usize * index::LEAF_ENTRY_LEN;+        let raw_len = entry.leaf_entry_count as usize * index::LEAF_ENTRY_LEN;+        let stored_len = if entry.stored_len == 0 { raw_len } else { entry.stored_len as usize };         let at = (header.leaf_offset + entry.leaf_offset) as usize;-        if at + len > bytes.len() {+        if at + stored_len > bytes.len() {             return err("a .mamaps root entry runs past the file");         }-        for tile in index::parse_leaf(&bytes[at..at + len])? {+        let raw = if entry.stored_len == 0 {+            bytes[at..at + stored_len].to_vec()+        } else {+            index::decompress_leaf(&bytes[at..at + stored_len], raw_len)?+        };+        for tile in index::parse_leaf(&raw)? {             let start = (header.data_offset + entry.base_data_offset + tile.offset_delta as u64)                 as usize;             let end = start + tile.length as usize;
library/tilecodec/src/main/rust/src/mamaps/tests_extra.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/tests_extra.rs b/library/tilecodec/src/main/rust/src/mamaps/tests_extra.rsindex 011a34e550..3b48146b08 100644--- a/library/tilecodec/src/main/rust/src/mamaps/tests_extra.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/tests_extra.rs@@ -219,6 +219,92 @@ fn a_zstd_body_decodes_to_the_bytes_it_was_encoded_from() {     assert_eq!(d_back, raw); } +/// Phase 5: each leaf is one raw-DEFLATE frame; the root stays raw at 32 B stride inside the+/// opening prefix. A compressed archive opens in one request, reads back exactly, and its leaf+/// section is smaller than the raw one — while the legacy all-raw layout still opens too.+#[test]+fn compressed_leaves_round_trip_and_keep_the_prefix_budget() {+    use crate::mamaps::header::FLAG_LEAVES_COMPRESSED;+    use crate::mamaps::index::{LEAF_ENTRY_LEN, ROOT_ENTRY_LEN};+    // Enough tiles for several leaves, with repeats so runs and content dedup both fire.+    let mut tiles: Vec<(u8, u64, u64, i16)> = Vec::new();+    for z in 0..=4u8 {+        for x in 0..(1u64 << z) {+            for y in 0..(1u64 << z) {+                tiles.push((z, x, y, ((x + y) % 3) as i16));+            }+        }+    }+    let options = Options { leaf_entry_capacity: 16, ..Options::default() };+    assert!(options.compress_leaves, "leaf compression is on by default");+    let bytes = archive(&tiles, Options { leaf_entry_capacity: 16, ..Options::default() });+    let header = Header::parse(&bytes).expect("header");+    assert!(header.leaves_compressed(), "the flag is set");+    assert_eq!(bytes[7], crate::mamaps::header::FORMAT_VERSION_V9, "a v9 version byte");+    assert!(header.leaf_count > 1, "this test needs several leaves");+    // The root is still raw fixed stride inside the opening prefix.+    let prefix = header::HEADER_LEN as u64 + header.dict_len as u64 + header.root_len as u64;+    assert!(prefix <= OPEN_PREFIX_BYTES as u64, "the prefix is {prefix} bytes");+    assert_eq!(header.root_len as usize % ROOT_ENTRY_LEN, 0, "raw 32 B stride");+    // Every leaf's stored length comes from its root entry, and inflates to count * 16.+    let (h2, _, root) = read::open_prefix(&bytes).expect("open_prefix");+    assert_eq!(h2.leaf_count as usize, root.len());+    let mut raw_total: u64 = 0;+    for e in &root {+        let raw_len = e.leaf_entry_count as usize * LEAF_ENTRY_LEN;+        raw_total += raw_len as u64;+        let at = (h2.leaf_offset + e.leaf_offset) as usize;+        if e.stored_len == 0 {+            assert_eq!(raw_len, bytes[at..at + raw_len].len());+        } else {+            let back = crate::mamaps::index::decompress_leaf(+                &bytes[at..at + e.stored_len as usize],+                raw_len,+            )+            .expect("leaf frame");+            assert_eq!(back.len(), raw_len, "exactly count * 16, allocated once");+        }+    }+    assert!(header.leaf_len < raw_total, "the stored section is smaller than the raw leaves");+    // And the whole archive reads back tile-for-tile through the range-reader path.+    let mut a = open(bytes);+    assert_eq!(a.reader.requests.borrow().len(), 1, "open is still one request");+    for (z, x, y, seed) in &tiles {+        let tile = a.tile(*z, *x as u32, *y as u32).expect("read").expect("present");+        assert_eq!(tile, body_for(*seed), "z{z}/{x}/{y}");+    }+}++/// Phase 5: `compress_leaves: false` is the legacy layout bit for bit — no flag, v8 version+/// byte, zero stored words — and it opens on the same reader.+#[test]+fn raw_leaves_stay_byte_identical_and_still_open() {+    let tiles: Vec<(u8, u64, u64, i16)> =+        (0..4u64).flat_map(|x| (0..4u64).map(move |y| (2u8, x, y, (x * 4 + y) as i16))).collect();+    let raw_opts = Options { compress_leaves: false, ..Options::default() };+    let raw = archive(&tiles, raw_opts);+    let header = Header::parse(&raw).expect("header");+    assert!(!header.leaves_compressed(), "no flag");+    assert_eq!(raw[7], crate::mamaps::header::FORMAT_VERSION, "a v8 version byte");+    let (_, _, root) = read::open_prefix(&raw).expect("open_prefix");+    assert!(root.iter().all(|e| e.stored_len == 0), "zero stored words");+    // Legacy determinism holds: two builds are still byte-identical.+    let raw2 = archive(+        &tiles,+        Options { compress_leaves: false, ..Options::default() },+    );+    assert_eq!(raw, raw2);+    // And compressed builds are deterministic too.+    let c1 = archive(&tiles, Options::default());+    let c2 = archive(&tiles, Options::default());+    assert_eq!(c1, c2);+    // Both open and read on the same reader.+    for bytes in [raw, c1] {+        let mut a = open(bytes);+        assert_eq!(a.tile(2, 3, 3).expect("read").expect("present"), body_for(15));+    }+}+ /// Planet per-leaf data-span overflow: a leaf whose entries' max(offset)- /// min(offset) would exceed u32::MAX (planet: 4294968552 = u32::MAX+1257) /// must be split, otherwise LeafEntry.offset_delta (u32) overflows.
library/tilecodec/src/main/rust/src/mamaps/write/options.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/write/options.rs b/library/tilecodec/src/main/rust/src/mamaps/write/options.rsindex 31a2d6e5a0..2cdae7852c 100644--- a/library/tilecodec/src/main/rust/src/mamaps/write/options.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/write/options.rs@@ -14,6 +14,14 @@ pub struct Options {     /// a reader's cache marker is `CACHE_FORMAT | URL | build_id`.     pub build_id: u64,     pub compress: bool,+    /// Store each leaf as one raw-DEFLATE frame rather than raw fixed-stride entries.+    ///+    /// The root stays raw either way — same 32-byte stride, same opening-prefix budget — and+    /// each frame's stored length rides in its root entry. Measured 0.39 on twenty random+    /// California leaves (2.54 GB → ~1.00 GB). On by default: a leaf that would grow is stored+    /// raw instead, so this never costs a byte, and the reader takes every length from a field+    /// either way. Off keeps the legacy all-raw layout bit for bit.+    pub compress_leaves: bool,     /// Set when the generator normalised ring winding and hole containment, which is what lets the     /// renderer skip its repair pass.     pub rings_validated: bool,@@ -38,6 +46,7 @@ impl Default for Options {             max_zoom: 14,             build_id: 0,             compress: true,+            compress_leaves: true,             rings_validated: false,             leaf_entry_capacity: DEFAULT_LEAF_CAPACITY,             spill_dir: None,
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 b1bbfdd095..59ae2611e7 100644--- a/library/tilecodec/src/main/rust/src/mamaps/write/writer.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/write/writer.rs@@ -463,6 +463,10 @@ impl StreamWriter {                 leaf_offset: leaf_data_offset,                 base_data_offset,                 leaf_entry_count: chunk.len() as u32,+                // Filled in by `prefix`, which is the only place that knows whether leaves+                // store compressed: zero here keeps `partition` (and its byte-identity test)+                // about boundaries only, never about bytes.+                stored_len: 0,             });             leaf_data_offset += leaf_len_before * index::LEAF_ENTRY_LEN as u64;             leaves.push(leaf);
library/tilecodec/src/main/rust/src/mamaps/write/writer_extra.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/write/writer_extra.rs b/library/tilecodec/src/main/rust/src/mamaps/write/writer_extra.rsindex 1386bd669e..33a9a243fd 100644--- a/library/tilecodec/src/main/rust/src/mamaps/write/writer_extra.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/write/writer_extra.rs@@ -1,8 +1,8 @@ use super::writer::StreamWriter; use crate::mamaps::dict; use crate::mamaps::header::{-    COMPRESSION_DEFLATE, COMPRESSION_NONE, FLAG_BODIES_COMPRESSED, FLAG_RINGS_VALIDATED,-    FLAG_RUN_LENGTH_PRESENT, HEADER_LEN, Header,+    COMPRESSION_DEFLATE, COMPRESSION_NONE, FLAG_BODIES_COMPRESSED, FLAG_LEAVES_COMPRESSED,+    FLAG_RINGS_VALIDATED, FLAG_RUN_LENGTH_PRESENT, HEADER_LEN, Header, }; use crate::mamaps::index::{self}; use crate::proto::{Result, err};@@ -28,15 +28,18 @@ impl StreamWriter {         // PMTiles writer takes and for the same reason. Twelve doublings takes 4096 to 16 M         // entries per leaf; a root that still does not fit is a build failure, never a silent         // third round trip charged to every reader forever.-        let (root, leaves) = loop {+        let (mut root, leaves) = loop {             // A `None` is a leaf whose tile-id span will not fit a `u32`. A wider leaf spans more             // ids, not fewer, so growing the capacity does not fix that one -- it runs out at the             // cap below and reports. Kept distinct from the root-too-large case because the two want             // opposite things from the capacity and a future fix has to choose between them.+            //+            // The root length is what the budget accounts: the root stays raw at 32 bytes an+            // entry whatever the leaves store, so leaf compression never moves this loop.             if let Some(split) = self.partition(capacity)? {                 let root_len = split.0.len() * index::ROOT_ENTRY_LEN;                 if HEADER_LEN + dictionary.len() + root_len <= OPEN_PREFIX_BYTES as usize {-                    break split;+                    break (split.0, split.1);                 }             }             if capacity >= 1 << 24 {@@ -58,9 +61,36 @@ impl StreamWriter {         if self.options.rings_validated {             flags |= FLAG_RINGS_VALIDATED;         }--        let leaf_bytes: Vec<u8> =-            leaves.iter().flat_map(|leaf| index::serialize_leaf(leaf)).collect();+        // One raw-DEFLATE frame per leaf, decided here — after the budget loop, exactly once+        // per finish — so `partition` stays about boundaries and the frame bytes are a pure+        // function of the leaf: the same leaf always stores the same bytes, which is what keeps+        // `finish` and `finish_to_path` two ways of emitting one archive. A frame that would+        // grow its leaf is stored raw instead (`stored_len` zero), so this never costs a byte;+        // with `compress_leaves` off every leaf stores raw and the file is the legacy layout+        // bit for bit.+        let mut leaf_bytes = Vec::new();+        for (entry, leaf) in root.iter_mut().zip(leaves.iter()) {+            let raw = index::serialize_leaf(leaf);+            let stored = if self.options.compress_leaves {+                let frame = index::compress_leaf(&raw);+                if frame.len() < raw.len() { frame } else { raw }+            } else {+                raw+            };+            entry.leaf_offset = leaf_bytes.len() as u64;+            entry.stored_len = if stored.len() == leaf.len() * index::LEAF_ENTRY_LEN {+                0+            } else {+                u32::try_from(stored.len()).map_err(|_| {+                    crate::proto::Error("a .mamaps leaf frame is larger than 4 GiB".to_string())+                })?+            };+            leaf_bytes.extend_from_slice(&stored);+        }+        let any_compressed = root.iter().any(|e| e.stored_len != 0);+        if any_compressed {+            flags |= FLAG_LEAVES_COMPRESSED;+        }         let leaf_len = leaf_bytes.len() as u64;         // Planet scale: ~268M bodies ×16 B ≈4.29 GB > u32::MAX (1257 B overflow         // in the failed run). Common path (NA ~418 MB, CA ~tens of MB) stays
library/tilecodec/src/main/rust/tests/leaf_compression.rs
diff --git a/library/tilecodec/src/main/rust/tests/leaf_compression.rs b/library/tilecodec/src/main/rust/tests/leaf_compression.rsnew file mode 100644index 0000000000..85fe6c2641--- /dev/null+++ b/library/tilecodec/src/main/rust/tests/leaf_compression.rs@@ -0,0 +1,222 @@+//! Phase 5 leaf compression: integration gate.+//!+//! The lib test target is broken at HEAD by in-progress header work (`shared_*` fields+//! referenced from `mamaps::archive::tests` before they land on `Header`), so this file+//! exercises the same invariants through the public API only: it builds against the lib,+//! never against `#[cfg(test)]` code. The unit tests in `mamaps/index.rs` and+//! `mamaps/tests_extra.rs` remain the long-term home and assert the same facts; this file+//! is the gate that actually runs until the header work lands.++use std::cell::RefCell;+use std::rc::Rc;+use tilecodec::mamaps::body::{+    Body, Feature, Layer, Part, DEFAULT_EXTENT, GEOM_LINE, NAME_NONE, WINDING_OUTER,+};+use tilecodec::mamaps::dict;+use tilecodec::mamaps::header::{Header, FORMAT_VERSION, FORMAT_VERSION_V9, HEADER_LEN};+use tilecodec::mamaps::index::{self, LEAF_ENTRY_LEN, ROOT_ENTRY_LEN, RootEntry};+use tilecodec::mamaps::read::{self, MamapsArchive};+use tilecodec::mamaps::write::{Options, StreamWriter};+use tilecodec::pmtiles::tile_id;+use tilecodec::proto::Result;+use tilecodec::stream::{RangeReader, OPEN_PREFIX_BYTES};++/// 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 log is shared by handle: `MamapsArchive` owns the reader (its `reader` field is+/// crate-private for the in-crate counting tests), so the test keeps the other end.+struct Counting {+    bytes: Vec<u8>,+    requests: Rc<RefCell<Vec<(u64, u32)>>>,+}++impl RangeReader for Counting {+    fn read(&self, offset: u64, length: u32) -> Result<Vec<u8>> {+        self.requests.borrow_mut().push((offset, length));+        if offset >= self.bytes.len() as u64 {+            return Ok(Vec::new());+        }+        let end = (offset + length as u64).min(self.bytes.len() as u64);+        Ok(self.bytes[offset as usize..end as usize].to_vec())+    }+}++/// A one-line body whose contents depend on `seed`, so two tiles differ unless asked not to.+fn body_for(seed: i16) -> Body {+    let mut roads = Layer::new(dict::LAYER_ROADS);+    roads.features.push(Feature {+        kind: 45,+        kind_detail: dict::NONE,+        geom_type: GEOM_LINE,+        flags: 0,+        name_idx: NAME_NONE,+        parts_offset: 0,+        part_count: 1,+        transit_color: 0,+        transit_ordinal: 0,+        transit_lanes: 0,+        transit_taper: 0,+        lane_count: 0,+    });+    roads.parts.push(Part { coord_start: 0, point_count: 2, winding: WINDING_OUTER });+    roads.coords = vec![(0, 0), (seed, seed)];+    Body {+        extent: DEFAULT_EXTENT,+        layers: vec![roads],+        names: Vec::new(),+        ids: Vec::new(),+        turn_lanes: Vec::new(),+        buildings: Vec::new(),+        heightmap: None,+        carriageways: Vec::new(),+        convention: None,+        region_links: Vec::new(),+    }+}++/// An archive of `(z, x, y, seed)` tiles, fed in ascending id order as the writer requires.+fn archive(tiles: &[(u8, u64, u64, i16)], options: Options) -> Vec<u8> {+    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");+    }+    writer.finish().expect("finish")+}++fn open(bytes: Vec<u8>) -> (MamapsArchive<Counting>, Rc<RefCell<Vec<(u64, u32)>>>) {+    let requests = Rc::new(RefCell::new(Vec::new()));+    let a = MamapsArchive::open(Counting { bytes, requests: Rc::clone(&requests) })+        .expect("open");+    (a, requests)+}++/// Enough tiles for several leaves, with repeats so runs and content dedup both fire.+fn leafy_tiles() -> Vec<(u8, u64, u64, i16)> {+    let mut tiles = Vec::new();+    for z in 0..=4u8 {+        for x in 0..(1u64 << z) {+            for y in 0..(1u64 << z) {+                tiles.push((z, x, y, ((x + y) % 3) as i16));+            }+        }+    }+    tiles+}++/// Each leaf is one raw-DEFLATE frame; the root stays raw at 32 B stride inside the opening+/// prefix. A compressed archive opens in one request, reads back exactly, and its leaf section+/// is smaller than the raw one.+#[test]+fn compressed_leaves_round_trip_and_keep_the_prefix_budget() {+    assert!(Options::default().compress_leaves, "leaf compression is on by default");+    let tiles = leafy_tiles();+    let options = Options { leaf_entry_capacity: 16, ..Options::default() };+    let bytes = archive(&tiles, options);+    let header = Header::parse(&bytes).expect("header");+    assert!(header.leaves_compressed(), "the flag is set");+    assert_eq!(bytes[7], FORMAT_VERSION_V9, "a v9 version byte");+    assert!(header.leaf_count > 1, "this test needs several leaves");+    // The root is still raw fixed stride inside the opening prefix.+    let prefix = HEADER_LEN as u64 + header.dict_len as u64 + header.root_len as u64;+    assert!(prefix <= OPEN_PREFIX_BYTES as u64, "the prefix is {prefix} bytes");+    assert_eq!(header.root_len as usize % ROOT_ENTRY_LEN, 0, "raw 32 B stride");+    // Every leaf's stored length comes from its root entry, and inflates to count * 16.+    let (h2, _, root) = read::open_prefix(&bytes).expect("open_prefix");+    assert_eq!(h2.leaf_count as usize, root.len());+    let mut raw_total: u64 = 0;+    for e in &root {+        let raw_len = e.leaf_entry_count as usize * LEAF_ENTRY_LEN;+        raw_total += raw_len as u64;+        let at = (h2.leaf_offset + e.leaf_offset) as usize;+        if e.stored_len == 0 {+            assert_eq!(raw_len, bytes[at..at + raw_len].len());+        } else {+            let back =+                index::decompress_leaf(&bytes[at..at + e.stored_len as usize], raw_len)+                    .expect("leaf frame");+            assert_eq!(back.len(), raw_len, "exactly count * 16, allocated once");+            assert_eq!(+                index::parse_leaf(&back).expect("parse").len(),+                e.leaf_entry_count as usize+            );+        }+    }+    assert!(header.leaf_len < raw_total, "the stored section is smaller than the raw leaves");+    // And the whole archive reads back tile-for-tile through the range-reader path.+    let (mut a, requests) = open(bytes);+    assert_eq!(requests.borrow().len(), 1, "open is still one request");+    for (z, x, y, seed) in &tiles {+        let tile = a.tile(*z, *x as u32, *y as u32).expect("read").expect("present");+        assert_eq!(tile, body_for(*seed), "z{z}/{x}/{y}");+    }+}++/// `compress_leaves: false` is the legacy layout bit for bit — no flag, v8 version byte, zero+/// stored words — and it opens on the same reader. Both modes are deterministic.+#[test]+fn raw_leaves_stay_byte_identical_and_still_open() {+    let tiles: Vec<(u8, u64, u64, i16)> =+        (0..4u64).flat_map(|x| (0..4u64).map(move |y| (2u8, x, y, (x * 4 + y) as i16))).collect();+    let raw = archive(&tiles, Options { compress_leaves: false, ..Options::default() });+    let header = Header::parse(&raw).expect("header");+    assert!(!header.leaves_compressed(), "no flag");+    assert_eq!(raw[7], FORMAT_VERSION, "a v8 version byte");+    let (_, _, root) = read::open_prefix(&raw).expect("open_prefix");+    assert!(root.iter().all(|e| e.stored_len == 0), "zero stored words");+    // Legacy determinism holds: two builds are still byte-identical.+    let raw2 = archive(&tiles, Options { compress_leaves: false, ..Options::default() });+    assert_eq!(raw, raw2);+    // And compressed builds are deterministic too.+    let c1 = archive(&tiles, Options::default());+    let c2 = archive(&tiles, Options::default());+    assert_eq!(c1, c2);+    // Both open and read on the same reader.+    for bytes in [raw, c1] {+        let (mut a, _) = open(bytes);+        assert_eq!(a.tile(2, 3, 3).expect("read").expect("present"), body_for(15));+    }+}++/// A cold tile still costs exactly two requests (leaf + body), a warm tile one — compression+/// changes the bytes fetched, never the count.+#[test]+fn a_cold_tile_is_still_two_requests_and_a_warm_tile_one() {+    let tiles = leafy_tiles();+    let options = Options { leaf_entry_capacity: 16, ..Options::default() };+    let (mut a, requests) = open(archive(&tiles, options));+    assert!(a.header.leaf_count > 1, "this test needs several leaves");+    requests.borrow_mut().clear();+    assert!(a.tile(4, 0, 0).expect("read").is_some());+    assert_eq!(requests.borrow().len(), 2, "a cold tile is a leaf plus a body");+    requests.borrow_mut().clear();+    assert!(a.tile(4, 1, 1).expect("read").is_some());+    assert_eq!(requests.borrow().len(), 1, "its leaf is now cached, so only the body");+}++/// An old (v8) reader refuses a leaf-compressed archive cleanly: the flag is unknown to it, and+/// so is the non-zero word where a reserved zero used to be. It never misreads the leaf section+/// as raw entries.+#[test]+fn an_old_reader_refuses_a_compressed_archive_rather_than_misreading_it() {+    use tilecodec::mamaps::header::{FLAG_BODIES_COMPRESSED, FLAG_LEAF_LEN_64};+    use tilecodec::mamaps::header::{FLAG_RINGS_VALIDATED, FLAG_RUN_LENGTH_PRESENT};+    let tiles = leafy_tiles();+    let bytes = archive(&tiles, Options { leaf_entry_capacity: 16, ..Options::default() });+    let header = Header::parse(&bytes).expect("new reader opens");+    assert!(header.leaves_compressed());+    // Simulate the v8 refusal rules against the real bytes: unknown flag bits, and a non-zero+    // word where v8's root parser demanded zero.+    const V8_KNOWN: u16 =+        FLAG_BODIES_COMPRESSED | FLAG_RUN_LENGTH_PRESENT | FLAG_RINGS_VALIDATED | FLAG_LEAF_LEN_64;+    assert_ne!(header.flags & !V8_KNOWN, 0, "the new flag is unknown to v8");+    let (_, _, root) = read::open_prefix(&bytes).expect("open_prefix");+    assert!(root.iter().any(|e| e.stored_len != 0), "a v8 zero-check would fire");+    // The 128-byte shape itself is unchanged (same length, same section offsets); it is the+    // flag/word checks in `parse` that refuse, before any leaf is ever addressed.+    assert_eq!(bytes.len(), header.file_len as usize);+    assert_eq!(HEADER_LEN, 128);+}