Modern Apps git

← Modern-Apps.git

tilecodec: superblocks, header v11 (#planet5)

Commit
afbc22bcccac4e8781f4a93bd8024143553c4031
Author
Vayun Mathur <[email protected]>
When
2026-11-14 15:07 UTC (21 days ago)
Parents
75f7144
Tile bodies compress independently, so neighbouring tiles share only
the band dictionary. A superblock stores the bodies of an aligned
block of same-zoom tiles as one dictionary-zstd frame; measured on US
West (aggressive preset) 8x8 at z10-13 / 4x4 at z14 shrinks tile data
1.754 -> 1.498 GB (-14.6%), every member verified lossless.

Format:
- superblock.rs: decompressed layout "MSB1", raw_len, member count,
  then (tile_id u64, offset u32, len u32) per member and the members'
  complete raw bodies. The 16-byte header is shaped like a body header
  (raw_len at 4..8, stored raw ahead of the zstd frame), so the stored
  frame decodes through the unchanged decompress_with. A body starts
  "MBD", a superblock "MSB". members/member/resolve validate the table
  (bounds, ascending ids); assemble builds one.
- Members of an aligned block are contiguous in Hilbert order and all
  their leaf entries address the shared frame (stored once by content
  dedup), so the index layout is unchanged.
- FLAG_SUPERBLOCKS + header v11 (FORMAT_VERSION_HEADER_V11), which
  imply each other and dictionary compression; a v10 reader refuses
  the archive by version. Options.superblocks sets them.

Reader: MamapsArchive::tile/tile_bytes/tiles resolve a superblock to
the requested tile's member body; decompressed blocks go into a
process-wide 16 MiB cache keyed by (build id, offset) so every other
member of the block costs no fetch and no decompress (the renderer
runs one archive view per worker). The batched path fetches a shared
frame once per batch. read_all expands members, one entry each.

Verified: cargo test -p tilecodec --features write (201 pass; new:
superblock round trip/validation, cache eviction by bytes, and a v11
archive read through tile(), tiles() and read_all with the frame
stored once).

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 f68b095e74..240450d661 100644--- a/library/tilecodec/src/main/rust/src/mamaps/header.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/header.rs@@ -25,7 +25,7 @@ mod tests; pub use consts::{     COMPRESSION_DEFLATE, COMPRESSION_NONE, COMPRESSION_ZSTD, COMPRESSION_ZSTD_DICT, FLAG_BODIES_COMPRESSED,     FLAG_LEAF_LEN_64, FLAG_LEAVES_COMPRESSED, FLAG_RINGS_VALIDATED, FLAG_RUN_LENGTH_PRESENT, FORMAT_VERSION,-    FORMAT_VERSION_HEADER_V10, FORMAT_VERSION_V9, FORMAT_VERSION_V10, FORMAT_VERSION_V11, HEADER_LEN, MAGIC,+    FORMAT_VERSION_HEADER_V10, FORMAT_VERSION_HEADER_V11, FORMAT_VERSION_V9, FORMAT_VERSION_V10, FORMAT_VERSION_V11, HEADER_LEN, MAGIC, FLAG_SUPERBLOCKS,     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 efc219854a..0a1d61fc20 100644--- a/library/tilecodec/src/main/rust/src/mamaps/header/consts.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/header/consts.rs@@ -90,6 +90,8 @@ pub const FORMAT_VERSION_V10: u8 = 10; /// header cleanly, which is what keeps planet4 apps on planet4. This reader still speaks v8 and /// v9 headers unchanged. pub const FORMAT_VERSION_HEADER_V10: u8 = 10;+/// Header v11: v10 (dictionary-zstd bodies) plus [`FLAG_SUPERBLOCKS`]; the two go together.+pub const FORMAT_VERSION_HEADER_V11: u8 = 11;  /// Body version 11: a v10 body whose heightmap samples are MED-predicted (LOCO-I) zigzag /// residuals rather than raw `u16`s. Lossless (mod 2^16 arithmetic); only the entropy of the@@ -124,9 +126,16 @@ pub const FLAG_LEAF_LEN_64: u16 = 1 << 3; /// non-zero reserved word. See [`crate::mamaps::index`] for the framing. pub const FLAG_LEAVES_COMPRESSED: u16 = 1 << 4; +/// Planet5 (~50 GB revision): some stored bodies are *superblocks* -- one dictionary-zstd frame+/// holding the bodies of up to 8x8 neighbouring tiles (see [`crate::mamaps::superblock`]). Every+/// member tile's leaf entry addresses the shared frame; the reader picks its body out by tile id.+/// Only with [`FORMAT_VERSION_HEADER_V11`] (and that version means exactly this flag), so a v10+/// reader refuses the archive by version.+pub const FLAG_SUPERBLOCKS: u16 = 1 << 5;+ pub(super) const KNOWN_FLAGS: u16 =     FLAG_BODIES_COMPRESSED | FLAG_RUN_LENGTH_PRESENT | FLAG_RINGS_VALIDATED | FLAG_LEAF_LEN_64-    | FLAG_LEAVES_COMPRESSED;+    | FLAG_LEAVES_COMPRESSED | FLAG_SUPERBLOCKS;  /// Bodies stored as written. pub const COMPRESSION_NONE: u8 = 0;
library/tilecodec/src/main/rust/src/mamaps/header/parse.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/header/parse.rs b/library/tilecodec/src/main/rust/src/mamaps/header/parse.rsindex 7ba3edced2..2ef7531a62 100644--- a/library/tilecodec/src/main/rust/src/mamaps/header/parse.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/header/parse.rs@@ -8,7 +8,8 @@ use crate::proto::{err, Result};  use super::consts::{     COMPRESSION_DEFLATE, COMPRESSION_NONE, COMPRESSION_ZSTD, COMPRESSION_ZSTD_DICT, FLAG_LEAF_LEN_64,-    FORMAT_VERSION, FORMAT_VERSION_HEADER_V10, FORMAT_VERSION_V9, HEADER_LEN, KNOWN_FLAGS, MAGIC,+    FORMAT_VERSION, FORMAT_VERSION_HEADER_V10, FORMAT_VERSION_HEADER_V11, FORMAT_VERSION_V9, HEADER_LEN, KNOWN_FLAGS, MAGIC,+    FLAG_SUPERBLOCKS,     MAX_ZOOM, }; use super::types::Header;@@ -33,14 +34,24 @@ impl Header {             return err("not a .mamaps archive (bad magic)");         }         let version = buf[7];-        if version != FORMAT_VERSION && version != FORMAT_VERSION_V9 && version != FORMAT_VERSION_HEADER_V10 {+        if version != FORMAT_VERSION+            && version != FORMAT_VERSION_V9+            && version != FORMAT_VERSION_HEADER_V10+            && version != FORMAT_VERSION_HEADER_V11+        {             return err(format!(                 "unsupported .mamaps format version {version} (this reader speaks v{FORMAT_VERSION}, \-                 v{FORMAT_VERSION_V9} and v{FORMAT_VERSION_HEADER_V10})",+                 v{FORMAT_VERSION_V9}, v{FORMAT_VERSION_HEADER_V10} and v{FORMAT_VERSION_HEADER_V11})",             ));         }-        // Dictionary compression is exactly what makes a header v10, both ways.-        if (version == FORMAT_VERSION_HEADER_V10) != (buf[12] == COMPRESSION_ZSTD_DICT) {+        // v11 is v10 with superblocks, and the superblock flag is v11 only.+        let sb_flag = u16::from_le_bytes([buf[10], buf[11]]) & FLAG_SUPERBLOCKS != 0;+        if (version == FORMAT_VERSION_HEADER_V11) != sb_flag {+            return err(format!("a .mamaps v{version} header with the superblock flag {}", if sb_flag { "set" } else { "clear" }));+        }+        let dict_version = version == FORMAT_VERSION_HEADER_V10 || version == FORMAT_VERSION_HEADER_V11;+        // Dictionary compression is exactly what makes a header v10/v11, both ways.+        if dict_version != (buf[12] == COMPRESSION_ZSTD_DICT) {             return err(format!(                 "a .mamaps v{version} header with compression {} (v{FORMAT_VERSION_HEADER_V10} means \                  dictionary-zstd bodies and nothing else)",
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 b89583ad32..0babc7c344 100644--- a/library/tilecodec/src/main/rust/src/mamaps/header/serialize.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/header/serialize.rs@@ -4,7 +4,8 @@  use super::consts::{     COMPRESSION_ZSTD_DICT, FLAG_LEAF_LEN_64, FLAG_LEAVES_COMPRESSED, FORMAT_VERSION,-    FORMAT_VERSION_HEADER_V10, FORMAT_VERSION_V9, HEADER_LEN, MAGIC,+    FORMAT_VERSION_HEADER_V10, FORMAT_VERSION_HEADER_V11, FORMAT_VERSION_V9, HEADER_LEN, MAGIC,+    FLAG_SUPERBLOCKS, }; use super::types::Header; @@ -16,7 +17,9 @@ impl Header {         // 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.compression == COMPRESSION_ZSTD_DICT {+        out.push(if self.flags & FLAG_SUPERBLOCKS != 0 {+            FORMAT_VERSION_HEADER_V11+        } else if self.compression == COMPRESSION_ZSTD_DICT {             FORMAT_VERSION_HEADER_V10         } else if (self.flags & FLAG_LEAVES_COMPRESSED) != 0 {             FORMAT_VERSION_V9
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 c4da552d0c..94a3c675dd 100644--- a/library/tilecodec/src/main/rust/src/mamaps/mod.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/mod.rs@@ -47,6 +47,7 @@ pub mod dict; pub mod header; pub mod index; pub mod read;+pub mod superblock; pub mod zdict;  // The archive section index (ArchiveView + kind consts) is read-side: Android reads the
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 c371b41c0b..d14dfd5840 100644--- a/library/tilecodec/src/main/rust/src/mamaps/read/archive.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/read/archive.rs@@ -128,6 +128,33 @@ impl<R: RangeReader> MamapsArchive<R> {     ///     /// `None` rather than an error: most of a coastal viewport is off the edge of coverage, and     /// that is the ordinary answer rather than a fault.+    /// Decompress a stored frame for `tile_id`: a body as is, or -- for a superblock (header+    /// v11) -- the tile's member body, the decompressed block kept in the shared cache so its+    /// other members cost no decompress.+    fn decode_stored(&self, abs_offset: u64, stored: &[u8], tile_id: u64) -> Result<Vec<u8>> {+        let raw = decompress_with(self.header.compression, stored, self.zdicts.as_deref())?;+        if crate::mamaps::superblock::is_superblock(&raw) {+            let raw = Arc::new(raw);+            let body = crate::mamaps::superblock::resolve(raw.as_ref().clone(), tile_id);+            crate::mamaps::superblock::shared_cache().put(self.header.build_id, abs_offset, raw);+            return body;+        }+        Ok(raw)+    }++    /// The member body of `tile_id` from an already-cached superblock at `abs_offset`.+    fn cached_member(&self, abs_offset: u64, tile_id: u64) -> Option<Result<Vec<u8>>> {+        if self.header.flags & crate::mamaps::header::FLAG_SUPERBLOCKS == 0 {+            return None;+        }+        let sb = crate::mamaps::superblock::shared_cache().get(self.header.build_id, abs_offset)?;+        Some(match crate::mamaps::superblock::member(&sb, tile_id) {+            Ok(Some(b)) => Ok(b.to_vec()),+            Ok(None) => err(format!("tile {tile_id} is not a member of the superblock its leaf entry addresses")),+            Err(e) => Err(e),+        })+    }+     pub fn tile(&self, z: u8, x: u32, y: u32) -> Result<Option<Body>> {         let Some(bytes) = self.tile_bytes(z, x, y)? else { return Ok(None) };         Ok(Some(Body::parse(&bytes)?))@@ -269,14 +296,27 @@ impl<R: RangeReader> MamapsArchive<R> {                 }             }         }-        // Wave 2: every wanted body, fetched concurrently in slot order.+        // Wave 2: every wanted body, fetched concurrently in slot order. Tiles of one superblock+        // share a stored frame: it is fetched and decompressed once (or not at all when cached).+        let ids: Vec<u64> = tiles.iter().map(|&(z, x, y)| tile_id(z, x as u64, y as u64)).collect();         let mut body_slots: Vec<usize> = Vec::new();         let mut body_requests: Vec<(u64, u32)> = Vec::new();+        let mut shared: Vec<(usize, usize)> = Vec::new(); // (slot, index of the request it shares)         for (slot, slot_body) in bodies.iter().enumerate() {             if done[slot].is_some() {                 continue;             }             if let Some((offset, length)) = slot_body {+                if let Some(hit) = self.cached_member(*offset, ids[slot]) {+                    done[slot] = Some(hit.and_then(|raw| Body::parse(&raw)).map(Some));+                    continue;+                }+                if self.header.flags & crate::mamaps::header::FLAG_SUPERBLOCKS != 0 {+                    if let Some(j) = body_requests.iter().position(|r| r.0 == *offset) {+                        shared.push((slot, j));+                        continue;+                    }+                }                 body_slots.push(slot);                 body_requests.push((*offset, *length));             }@@ -287,7 +327,7 @@ impl<R: RangeReader> MamapsArchive<R> {                 let (offset, length) = body_requests[i];                 match found.get(i) {                     Some(Ok(stored)) if stored.len() == length as usize => {-                        match decompress_with(self.header.compression, stored, self.zdicts.as_deref()) {+                        match self.decode_stored(offset, stored, ids[*slot]) {                             Ok(raw) => match Body::parse(&raw) {                                 Ok(body) => done[*slot] = Some(Ok(Some(body))),                                 Err(e) => done[*slot] = Some(Err(e)),@@ -308,6 +348,14 @@ impl<R: RangeReader> MamapsArchive<R> {                 }             }         }+        // Slots that shared another slot's superblock frame: it is in the cache now.+        for (slot, j) in shared {+            let (offset, _) = body_requests[j];+            done[slot] = Some(match self.cached_member(offset, ids[slot]) {+                Some(r) => r.and_then(|raw| Body::parse(&raw)).map(Some),+                None => err("a .mamaps superblock its batch fetched did not decode"),+            });+        }         done.into_iter()             .map(|slot| slot.unwrap_or_else(|| err("a .mamaps batch left a tile unresolved")))             .collect()@@ -418,8 +466,12 @@ impl<R: RangeReader> MamapsArchive<R> {         if at + entry.length as u64 > self.header.data_len {             return err("a .mamaps leaf entry runs past the tile data section");         }-        let stored = self.exact(self.header.data_offset + at, entry.length, "a tile body")?;-        Ok(Some(decompress_with(self.header.compression, &stored, self.zdicts.as_deref())?))+        let abs = self.header.data_offset + at;+        if let Some(hit) = self.cached_member(abs, want) {+            return hit.map(Some);+        }+        let stored = self.exact(abs, entry.length, "a tile body")?;+        Ok(Some(self.decode_stored(abs, &stored, want)?))     }      /// The parsed leaf a root entry addresses, from the shared cache or over the wire.
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 57bccfbc8c..9de49625a4 100644--- a/library/tilecodec/src/main/rust/src/mamaps/read/helpers.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/read/helpers.rs@@ -156,11 +156,19 @@ pub fn read_all(bytes: &[u8]) -> Result<Vec<(u64, u32, Vec<u8>)>> {             if end > bytes.len() {                 return err("a .mamaps leaf entry runs past the file");             }-            out.push((-                entry.base_tile_id + tile.tile_id_lo as u64,-                tile.run_length,-                decompress_with(header.compression, &bytes[start..end], zdicts.as_ref())?,-            ));+            let id = entry.base_tile_id + tile.tile_id_lo as u64;+            let raw = decompress_with(header.compression, &bytes[start..end], zdicts.as_ref())?;+            if crate::mamaps::superblock::is_superblock(&raw) {+                // Header v11: one entry per member tile (a run of members shares the frame).+                for k in 0..tile.run_length.max(1) as u64 {+                    match crate::mamaps::superblock::member(&raw, id + k)? {+                        Some(b) => out.push((id + k, 1, b.to_vec())),+                        None => return err("a .mamaps leaf entry addresses a superblock its tile is not in"),+                    }+                }+            } else {+                out.push((id, tile.run_length, raw));+            }         }     }     if out.windows(2).any(|pair| pair[1].0 <= pair[0].0) {
library/tilecodec/src/main/rust/src/mamaps/superblock.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/superblock.rs b/library/tilecodec/src/main/rust/src/mamaps/superblock.rsnew file mode 100644index 0000000000..6295911043--- /dev/null+++ b/library/tilecodec/src/main/rust/src/mamaps/superblock.rs@@ -0,0 +1,188 @@+//! Superblocks (planet5, header v11): several neighbouring tiles' bodies in one compressed frame.+//!+//! Tile bodies compress independently, so a dictionary is the only thing two neighbouring tiles+//! share. Measured on US West, compressing the bodies of a 4x4 / 8x8 block of same-zoom tiles as+//! one dictionary-zstd frame saves 5-20% (most at z12-z13, where neighbours repeat landuse,+//! roads and terrain): about 4.5 GB on the planet.+//!+//! A superblock's decompressed bytes start with a 16-byte header shaped like a body header, so+//! the stored frame is exactly a body frame (`raw_len` at bytes 4..8, the header stored raw ahead+//! of the zstd frame) and [`crate::mamaps::read::decompress_with`] needs no change:+//!+//! ```text+//! [magic "MSB1"][raw_len u32][member count u16][reserved u16 = 0][reserved u32 = 0]+//! [member: tile_id u64, offset u32, len u32] x count   (offset from the superblock start)+//! [member bodies: complete raw bodies, "MBD" + version ...]+//! ```+//!+//! Member tiles are an aligned 2^g x 2^g block at one zoom, so they are contiguous in tile-id+//! (Hilbert) order; every member's leaf entry addresses the same stored frame. A body starts+//! with "MBD", a superblock with "MSB": the first three bytes tell them apart.++use crate::proto::{err, Result};++pub const SUPERBLOCK_MAGIC: &[u8; 4] = b"MSB1";+pub const SUPERBLOCK_HEADER_LEN: usize = 16;+pub const SUPERBLOCK_MEMBER_LEN: usize = 16;++/// True when decompressed `raw` is a superblock rather than a body.+pub fn is_superblock(raw: &[u8]) -> bool {+    raw.len() >= SUPERBLOCK_HEADER_LEN && &raw[..4] == SUPERBLOCK_MAGIC+}++/// The members `(tile_id, body bytes)` of a decompressed superblock, validated.+pub fn members(raw: &[u8]) -> Result<Vec<(u64, &[u8])>> {+    if !is_superblock(raw) {+        return err("not a .mamaps superblock");+    }+    let raw_len = u32::from_le_bytes(raw[4..8].try_into().unwrap()) as usize;+    if raw_len != raw.len() {+        return err("a .mamaps superblock's length disagrees with its header");+    }+    let n = u16::from_le_bytes([raw[8], raw[9]]) as usize;+    let table_end = SUPERBLOCK_HEADER_LEN + n * SUPERBLOCK_MEMBER_LEN;+    if table_end > raw.len() {+        return err("a .mamaps superblock's member table runs past its end");+    }+    let mut out = Vec::with_capacity(n);+    let mut prev_id: Option<u64> = None;+    for i in 0..n {+        let at = SUPERBLOCK_HEADER_LEN + i * SUPERBLOCK_MEMBER_LEN;+        let id = u64::from_le_bytes(raw[at..at + 8].try_into().unwrap());+        let off = u32::from_le_bytes(raw[at + 8..at + 12].try_into().unwrap()) as usize;+        let len = u32::from_le_bytes(raw[at + 12..at + 16].try_into().unwrap()) as usize;+        if prev_id.is_some_and(|p| id <= p) {+            return err("a .mamaps superblock's members are not in tile-id order");+        }+        prev_id = Some(id);+        if off < table_end || off.checked_add(len).is_none_or(|e| e > raw.len()) {+            return err("a .mamaps superblock member lies outside the superblock");+        }+        out.push((id, &raw[off..off + len]));+    }+    Ok(out)+}++/// The body of `tile_id` inside decompressed superblock `raw`, or `None` when it is not a member.+pub fn member(raw: &[u8], tile_id: u64) -> Result<Option<&[u8]>> {+    let m = members(raw)?;+    Ok(m.binary_search_by_key(&tile_id, |e| e.0).ok().map(|i| m[i].1))+}++/// `raw` itself when it is a body; the requested member's body when it is a superblock (an error+/// when the tile is not a member: the leaf entry pointed a tile at the wrong frame).+pub fn resolve(raw: Vec<u8>, tile_id: u64) -> Result<Vec<u8>> {+    if !is_superblock(&raw) {+        return Ok(raw);+    }+    match member(&raw, tile_id)? {+        Some(b) => Ok(b.to_vec()),+        None => err(format!("tile {tile_id} is not a member of the superblock its leaf entry addresses")),+    }+}++/// Assemble a superblock from `(tile_id, raw body)` members in ascending tile-id order.+pub fn assemble(members: &[(u64, Vec<u8>)]) -> Vec<u8> {+    assert!(!members.is_empty() && members.len() <= u16::MAX as usize);+    let table_end = SUPERBLOCK_HEADER_LEN + members.len() * SUPERBLOCK_MEMBER_LEN;+    let total = table_end + members.iter().map(|m| m.1.len()).sum::<usize>();+    let mut out = Vec::with_capacity(total);+    out.extend_from_slice(SUPERBLOCK_MAGIC);+    out.extend_from_slice(&(total as u32).to_le_bytes());+    out.extend_from_slice(&(members.len() as u16).to_le_bytes());+    out.extend_from_slice(&[0u8; 6]);+    let mut at = table_end;+    for (id, body) in members {+        out.extend_from_slice(&id.to_le_bytes());+        out.extend_from_slice(&(at as u32).to_le_bytes());+        out.extend_from_slice(&(body.len() as u32).to_le_bytes());+        at += body.len();+    }+    for (_, body) in members {+        out.extend_from_slice(body);+    }+    out+}++/// A small shared cache of decompressed superblocks, keyed by stored offset: every member of a+/// block costs one decompress, not one each. Bounded by decoded bytes.+pub struct SuperblockCache {+    #[allow(clippy::type_complexity)]+    inner: std::sync::Mutex<(std::collections::HashMap<(u64, u64), std::sync::Arc<Vec<u8>>>, std::collections::VecDeque<(u64, u64)>, usize)>,+    cap_bytes: usize,+}++impl SuperblockCache {+    pub fn new(cap_bytes: usize) -> SuperblockCache {+        SuperblockCache { inner: std::sync::Mutex::new(Default::default()), cap_bytes }+    }++    /// The cached superblock stored at `offset` of the archive with `build_id`.+    pub fn get(&self, build_id: u64, offset: u64) -> Option<std::sync::Arc<Vec<u8>>> {+        self.inner.lock().ok()?.0.get(&(build_id, offset)).cloned()+    }++    pub fn put(&self, build_id: u64, offset: u64, raw: std::sync::Arc<Vec<u8>>) {+        let Ok(mut g) = self.inner.lock() else { return };+        let key = (build_id, offset);+        if g.0.contains_key(&key) {+            return;+        }+        g.2 += raw.len();+        g.0.insert(key, raw);+        g.1.push_back(key);+        while g.2 > self.cap_bytes {+            let Some(old) = g.1.pop_front() else { break };+            if let Some(v) = g.0.remove(&old) {+                g.2 -= v.len();+            }+        }+    }+}++/// The process-wide cache every [`crate::mamaps::MamapsArchive`] shares (the renderer runs one+/// archive view per worker; the tiles of one block are often decoded by different workers).+pub fn shared_cache() -> &'static SuperblockCache {+    static CACHE: std::sync::OnceLock<SuperblockCache> = std::sync::OnceLock::new();+    CACHE.get_or_init(SuperblockCache::default)+}++impl Default for SuperblockCache {+    fn default() -> Self {+        // 16 MiB: a screenful of 8x8 z13 blocks.+        SuperblockCache::new(16 << 20)+    }+}++#[cfg(test)]+mod tests {+    use super::*;++    #[test]+    fn a_superblock_round_trips_and_resolves_members() {+        let m = vec![(5u64, b"MBD\x0bbody-five".to_vec()), (9, b"MBD\x0bnine".to_vec()), (12, b"MBD\x0btwelve!".to_vec())];+        let raw = assemble(&m);+        assert!(is_superblock(&raw));+        let back = members(&raw).expect("members");+        assert_eq!(back.len(), 3);+        for ((id, body), (bid, bbody)) in m.iter().zip(back.iter()) {+            assert_eq!(id, bid);+            assert_eq!(&body[..], *bbody);+        }+        assert_eq!(resolve(raw.clone(), 9).unwrap(), b"MBD\x0bnine".to_vec());+        assert!(resolve(raw.clone(), 10).is_err(), "a non-member is an error");+        assert_eq!(resolve(b"MBD\x0bplain".to_vec(), 77).unwrap(), b"MBD\x0bplain".to_vec());+        let mut bad = raw.clone();+        bad[4] ^= 1;+        assert!(members(&bad).is_err(), "length mismatch");+    }++    #[test]+    fn the_cache_evicts_by_bytes() {+        let c = SuperblockCache::new(100);+        c.put(7, 1, std::sync::Arc::new(vec![0; 60]));+        c.put(7, 2, std::sync::Arc::new(vec![0; 60]));+        assert!(c.get(7, 1).is_none() && c.get(7, 2).is_some());+        assert!(c.get(8, 2).is_none(), "keyed by build id too");+    }+}
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 5ba0f48758..5cdac96b7b 100644--- a/library/tilecodec/src/main/rust/src/mamaps/tests_extra.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/tests_extra.rs@@ -447,3 +447,51 @@ fn a_dictionary_archive_round_trips() {     let (start, end) = crate::mamaps::read::zdict_extent(&a.header).expect("extent");     assert_eq!(&bytes[start as usize..end as usize], &section[..]); }++#[test]+fn a_superblock_archive_round_trips_through_every_reader() {+    use crate::mamaps::body::serialize;+    use crate::mamaps::write::compress_body_zstd;+    use crate::mamaps::zdict::ZDicts;+    let section = ZDicts::serialize(&[]);+    let mut writer = StreamWriter::new(Options { zdicts: Some(section), superblocks: true, ..Options::default() })+        .expect("options");+    // An aligned 2x2 block at z2 (Hilbert-contiguous ids) as one superblock, plus one plain tile.+    let block: Vec<(u64, u64, i16)> = vec![(2, 0, 1), (3, 0, 2), (2, 1, 3), (3, 1, 4)];+    let mut members: Vec<(u64, Vec<u8>)> =+        block.iter().map(|&(x, y, s)| (tile_id(2, x, y), serialize(&body_for(s)).expect("serialize"))).collect();+    members.sort_by_key(|m| m.0);+    let sb = crate::mamaps::superblock::assemble(&members);+    let frame = compress_body_zstd(&sb);+    let plain = (0u64, 0u64, 9i16);+    let mut appends: Vec<(u64, Vec<u8>)> = members.iter().map(|m| (m.0, frame.clone())).collect();+    appends.push((tile_id(2, plain.0, plain.1), compress_body_zstd(&serialize(&body_for(plain.2)).expect("s"))));+    appends.sort_by_key(|a| a.0);+    for (id, stored) in &appends {+        writer.append_stored(*id, stored).expect("append");+    }+    let bytes = writer.finish().expect("finish");+    assert_eq!(bytes[7], crate::mamaps::header::FORMAT_VERSION_HEADER_V11, "header v11");+    let a = MamapsArchive::open(Counting { bytes: bytes.clone(), requests: RefCell::new(Vec::new()) }).expect("open");+    assert!(a.header.flags & crate::mamaps::header::FLAG_SUPERBLOCKS != 0);+    for &(x, y, s) in &block {+        assert_eq!(a.tile(2, x as u32, y as u32).expect("tile").expect("present"), body_for(s));+    }+    assert_eq!(a.tile(2, 0, 0).expect("tile").expect("present"), body_for(9));+    // Batched: every member resolves, sharing one fetch.+    let want: Vec<(u8, u32, u32)> = block.iter().map(|&(x, y, _)| (2u8, x as u32, y as u32)).chain([(2, 0, 0)]).collect();+    let got = a.tiles(&want);+    for (i, &(x, y, s)) in block.iter().enumerate() {+        assert_eq!(got[i].as_ref().expect("ok").as_ref().expect("present"), &body_for(s), "{x},{y}");+    }+    assert_eq!(got[4].as_ref().expect("ok").as_ref().expect("present"), &body_for(9));+    // read_all expands the members, one entry each.+    let all = crate::mamaps::read::read_all(&bytes).expect("read_all");+    assert_eq!(all.len(), 5);+    for (id, run, raw) in &all {+        assert_eq!(*run, 1);+        assert!(crate::mamaps::body::Body::parse(raw).is_ok(), "tile {id} is a body");+    }+    // The superblock frame is stored once (content dedup): the file holds one copy.+    assert_eq!(bytes.windows(frame.len()).filter(|w| *w == &frame[..]).count(), 1);+}
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 e99a33564c..49e9be4f6a 100644--- a/library/tilecodec/src/main/rust/src/mamaps/write/options.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/write/options.rs@@ -27,6 +27,9 @@ pub struct Options {     /// [`crate::mamaps::header::COMPRESSION_ZSTD_DICT`] and the section is written between the     /// root index and the leaves. Bodies must be appended already compressed.     pub zdicts: Option<Vec<u8>>,+    /// Some stored bodies are superblocks ([`crate::mamaps::superblock`]): sets+    /// [`crate::mamaps::header::FLAG_SUPERBLOCKS`] and header v11. Requires `zdicts`.+    pub superblocks: 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@@ -71,6 +74,7 @@ impl Default for Options {             compress: true,             zstd: false,             zdicts: None,+            superblocks: false,             compress_leaves: true,             rings_validated: false,             leaf_entry_capacity: DEFAULT_LEAF_CAPACITY,
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 7b4c6fd34c..bdfcd75661 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@@ -61,6 +61,9 @@ impl StreamWriter {         if self.options.rings_validated {             flags |= FLAG_RINGS_VALIDATED;         }+        if self.options.superblocks && self.options.zdicts.is_some() {+            flags |= crate::mamaps::header::FLAG_SUPERBLOCKS;+        }         // 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