tilecodec: planet-sized leaf cache, shared ZBLK helpers, green tests (#planet4)
- Commit
d53e339a0d3c7b33783e279af8630250a8be341a- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-11 21:09 UTC (24 days ago)
- Parents
0d7a9bb
What changed and why: - LeafCache gains a byte budget (DEFAULT_LEAF_CACHE_BYTES = 48 MiB) on top of its 64-entry count. The count assumed small leaves, but the planet archives (planet3 and planet4) use leaf_entry_capacity 262144, i.e. 4 MiB per parsed leaf, so a long session of panning/zooming on a phone could pin 256 MiB of leaf index. The newest leaf is always kept; state-sized archives stay bound by the count. New with_limits(), bytes(), max_bytes() accessors; DEFAULT_LEAF_CACHE_BYTES re-exported. - blocked.rs: Blocked::records_per_block() and a public inflate_frame() so the app's lock-free ZBLK view (maps/src/main/rust/graph_part1.rs) can use the same header/offset validation and frame decode as the writer's reader instead of a hand-copied parser. - body/codec.rs: the unknown-body-flags check is kept but split so clippy's bad_bit_mask (all 8 bits are defined, so !KNOWN is 0) no longer fails `./check`; a future flag is still refused. - Docs: the reader speaks v8/v9 headers and v8/v9/v10 bodies with 10 layers (comments still said "v8 only, 9 layers"); TRIX v3..=7 and MARG v6..=7 in the archive validator docs. - Four lib tests were stale at HEAD and failed: the blocked-section test helper wrote 12 bytes per record whatever the stride; the streaming test pushed partial records; builds_are_v7 expected version byte 7 where the writer now emits the planet's v9; the minimal sidecar test paired a v7 MARG (which demands ZBLK) with raw v6 node records. Verified: cargo test --features write (190 lib + all integration tests green, incl. two new byte-budget tests); clippy clean of errors.
Diff
library/tilecodec/src/main/rust/src/blocked.rs
diff --git a/library/tilecodec/src/main/rust/src/blocked.rs b/library/tilecodec/src/main/rust/src/blocked.rsindex 91dd50c46e..28e5f2e4d8 100644--- a/library/tilecodec/src/main/rust/src/blocked.rs+++ b/library/tilecodec/src/main/rust/src/blocked.rs@@ -137,6 +137,11 @@ impl<'a> Blocked<'a> { self.record_len } + /// Records per block (the last block may hold fewer).+ pub fn records_per_block(&self) -> u64 {+ self.records_per_block+ }+ /// How many blocks the file holds. pub fn block_count(&self) -> usize { self.block_count@@ -156,15 +161,7 @@ impl<'a> Blocked<'a> { return err(format!("block {b} past the {} in the section", self.block_count)); } let (start, end) = (self.offset(b) as usize, self.offset(b + 1) as usize);- let frame = &self.bytes[start..end];- let mut decoder = ruzstd::decoding::StreamingDecoder::new(frame)- .map_err(|e| Error(format!("a blocked section will not decode: {e:?}")))?;- let mut out = Vec::new();- use std::io::Read as _;- decoder- .read_to_end(&mut out)- .map_err(|e| Error(format!("a blocked section will not decode: {e:?}")))?;- Ok(out)+ inflate_frame(&self.bytes[start..end], 0) } /// Copy record `id` into a caller buffer. Convenience over [`Blocked::block`]@@ -180,6 +177,23 @@ impl<'a> Blocked<'a> { } } +/// Inflate one block's zstd frame, the one decode every reader of a ZBLK section+/// shares (the host tools through [`Blocked::block`], the app's lock-free cached+/// view in `maps/src/main/rust/src/graph_part1.rs` directly).+///+/// `capacity` is a size hint for the output (the block's expected unpacked length,+/// or 0 when unknown); callers that know the exact length check it themselves.+pub fn inflate_frame(frame: &[u8], capacity: usize) -> Result<Vec<u8>> {+ let mut decoder = ruzstd::decoding::StreamingDecoder::new(frame)+ .map_err(|e| Error(format!("a blocked section will not decode: {e:?}")))?;+ let mut out = Vec::with_capacity(capacity);+ use std::io::Read as _;+ decoder+ .read_to_end(&mut out)+ .map_err(|e| Error(format!("a blocked section will not decode: {e:?}")))?;+ Ok(out)+}+ /// A tiny block cache: the last-inflated block plus an LRU spill. /// /// Routing walks neighbouring records, so a one-block cache hits constantly;@@ -489,11 +503,16 @@ mod tests { fn pattern_records(n: usize, len: usize) -> Vec<u8> { // Coordinate-like: small ints LE plus a slow counter, like NodeRecs.+ // `len` bytes per record: the 12-byte pattern truncated (7-byte edge records)+ // or zero-padded, so any stride gets whole records. let mut out = Vec::with_capacity(n * len); for i in 0..n {- out.extend_from_slice(&((350_000_000 + i as i32 * 37) as i32).to_le_bytes());- out.extend_from_slice(&((-1_200_000_000 + i as i32 * 11) as i32).to_le_bytes());- out.extend_from_slice(&(i as u32 * 3).to_le_bytes());+ let mut rec = Vec::with_capacity(12.max(len));+ rec.extend_from_slice(&((350_000_000 + i as i32 * 37) as i32).to_le_bytes());+ rec.extend_from_slice(&((-1_200_000_000 + i as i32 * 11) as i32).to_le_bytes());+ rec.extend_from_slice(&(i as u32 * 3).to_le_bytes());+ rec.resize(len, 0);+ out.extend_from_slice(&rec); } assert_eq!(out.len(), n * len); out@@ -552,8 +571,9 @@ mod tests { let scratch = dir.join("tilecodec_blocked_stream_test.tmp"); let _ = std::fs::remove_file(&scratch); let mut w = BlockedStreamWriter::create(12, &scratch).expect("create");- // Odd-sized pushes, including across block boundaries.- for chunk in records.chunks(5000) {+ // Odd-sized pushes (417 whole records each — `push` takes whole records only),+ // including across block boundaries.+ for chunk in records.chunks(417 * 12) { w.push(chunk).expect("push"); } let streamed = w.finish().expect("finish");
library/tilecodec/src/main/rust/src/mamaps/archive/mod.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/archive/mod.rs b/library/tilecodec/src/main/rust/src/mamaps/archive/mod.rsindex c0506033b7..0ff457cc42 100644--- a/library/tilecodec/src/main/rust/src/mamaps/archive/mod.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/archive/mod.rs@@ -56,7 +56,7 @@ //! //! * `offset + len <= file_len` (checked_add, no wrap), 8-byte aligned offsets. //! * No overlap: not with the tile prefix + shared section, not with each other.-//! * Magic/version per section: `MARG` v6 (graph meta), `TRIX` v3..=6+//! * Magic/version per section: `MARG` v6..=7 (graph meta), `TRIX` v3..=7 //! (transit), `MAPA` v1 (POI attrs), `PSP1`/`PNI1` (POI grid/words). //! * Count match: nodes `(N+1)*12`, edges exact length from `(E, escapes, //! named)`, intermediate trailer `G <= E`, lanes sentinel, elevation `N*2`,
library/tilecodec/src/main/rust/src/mamaps/archive/tests.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/archive/tests.rs b/library/tilecodec/src/main/rust/src/mamaps/archive/tests.rsindex be46ca74a7..c24bc97643 100644--- a/library/tilecodec/src/main/rust/src/mamaps/archive/tests.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/archive/tests.rs@@ -146,8 +146,11 @@ fn a_minimal_sidecar_parses_and_slices() { transit[4..8].copy_from_slice(&TRANSIT_VERSION.to_le_bytes()); transit[8..12].copy_from_slice(&20u32.to_le_bytes()); let mut header = v7_header(0);+ // Raw (unblocked) node records are a v6 graph; a v7 meta would demand ZBLK sections.+ let mut meta = graph_meta(4, 2, 0, 0);+ meta[4..8].copy_from_slice(&GRAPH_VERSION_MIN.to_le_bytes()); let payloads = vec![- (ARCHIVE_KIND_GRAPH_META, graph_meta(4, 2, 0, 0), 0),+ (ARCHIVE_KIND_GRAPH_META, meta, 0), (ARCHIVE_KIND_GRAPH_NODES, nodes.clone(), 0), (ARCHIVE_KIND_TRANSIT, transit.clone(), 0), ];
library/tilecodec/src/main/rust/src/mamaps/archive/view.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/archive/view.rs b/library/tilecodec/src/main/rust/src/mamaps/archive/view.rsindex e77e836858..34c24a2a20 100644--- a/library/tilecodec/src/main/rust/src/mamaps/archive/view.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/archive/view.rs@@ -373,7 +373,7 @@ impl ArchiveView { return err("a single-archive POI region covers a different index"); } }- // Transit: TRIX v3..=6 with a directory that fits.+ // Transit: TRIX v3..=7 with a directory that fits. if let Some(b) = slice(ARCHIVE_KIND_TRANSIT)? { if b.len() < 80 { return err("a single-archive transit pack ends before its header");
library/tilecodec/src/main/rust/src/mamaps/body/codec.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/body/codec.rs b/library/tilecodec/src/main/rust/src/mamaps/body/codec.rsindex 7eb64a3e20..73b616675d 100644--- a/library/tilecodec/src/main/rust/src/mamaps/body/codec.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/body/codec.rs@@ -128,7 +128,11 @@ impl Body { } let layer_count = buf[10] as usize; let body_flags = buf[11];- if body_flags & !KNOWN_BODY_FLAGS != 0 {+ // All eight bits are defined today, so `!KNOWN_BODY_FLAGS` is 0 and clippy calls this+ // a no-op; it stays so a ninth flag (or a narrowed set) is refused, not misread.+ #[allow(clippy::bad_bit_mask)]+ let unknown = body_flags & !KNOWN_BODY_FLAGS;+ if unknown != 0 { return err(format!("unknown body flags {:#04x}", body_flags)); } // Reserved word must be zero unless extended flag is set; extended uses it as spill for counts.
library/tilecodec/src/main/rust/src/mamaps/dict.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/dict.rs b/library/tilecodec/src/main/rust/src/mamaps/dict.rsindex 41dc20d774..16af988818 100644--- a/library/tilecodec/src/main/rust/src/mamaps/dict.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/dict.rs@@ -22,7 +22,7 @@ //! //! # Size //!-//! Nine layers, ~112 kinds and 41 details, at a length byte each: under 2 KiB as measured,+//! Ten layers, ~122 kinds and 45 details, at a length byte each: under 2 KiB as measured, //! which is what lets the header, the dictionary and the root index share one 16 KiB opening //! read. //!
library/tilecodec/src/main/rust/src/mamaps/dict/tables.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/dict/tables.rs b/library/tilecodec/src/main/rust/src/mamaps/dict/tables.rsindex 5055c6859f..84877b0197 100644--- a/library/tilecodec/src/main/rust/src/mamaps/dict/tables.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/dict/tables.rs@@ -13,7 +13,7 @@ pub const NONE: u16 = 0; /// The layers this format carries, in draw order. ///-/// A layer's id **is** its index here. Nine: the wash (`landtype`, everything the style+/// A layer's id **is** its index here. Ten: the wash (`landtype`, everything the style /// draws as a ground fill), then `roads`, `boundaries`, `buildings`, `places` (labels), /// `poi` (icons), `transit` (reserved by v2; populated when transit lands), `traffic` /// (v4: one line per drivable component segment, recoloured live from a pushed id→speed
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 cca78d9b90..6e370331c0 100644--- a/library/tilecodec/src/main/rust/src/mamaps/header/consts.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/header/consts.rs@@ -62,7 +62,8 @@ pub const MAGIC: &[u8; 7] = b"MAMAPS\0"; /// reject a v3 archive anyway. v1 is no longer read — the last v1 archive predates `places`, /// `poi` and `transit` entirely. ///-/// The reader speaks v8 only: any other version byte is refused on open.+/// The reader speaks v8 and v9 headers ([`FORMAT_VERSION_V9`]); any other version byte is+/// refused on open. Bodies carry their own version byte (v8, v9 or [`FORMAT_VERSION_V10`]). pub const FORMAT_VERSION: u8 = 8; /// The v9 format version: zstd bodies, compressed leaves, packed sidecars.
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 3f1085a426..0c3af92ea0 100644--- a/library/tilecodec/src/main/rust/src/mamaps/header/types.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/header/types.rs@@ -68,7 +68,7 @@ impl Header { self.flags & FLAG_LEAVES_COMPRESSED != 0 } - /// This header's wire length: always 128 (v8 only).+ /// This header's wire length: always 128 (v8 and v9). pub fn wire_len(&self) -> usize { HEADER_LEN }
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 ac8e2794c4..d5514c54cf 100644--- a/library/tilecodec/src/main/rust/src/mamaps/mod.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/mod.rs@@ -1,7 +1,8 @@ //! `.mamaps` — the container the Vulkan renderer reads, shaped like what it draws. //!-//! v8 only: a 128-byte header, 9 layers, full tile bodies. Anything else is-//! refused on open rather than reinterpreted.+//! v8 or v9 headers (always 128 bytes), 10 layers, v8/v9/v10 tile bodies (the planet+//! archives are v9 headers over v10 bodies). Anything else is refused on open rather than+//! reinterpreted. //! //! # Why not MVT inside PMTiles //!
library/tilecodec/src/main/rust/src/mamaps/read.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/read.rs b/library/tilecodec/src/main/rust/src/mamaps/read.rsindex d59d55b921..a7bd8e815b 100644--- a/library/tilecodec/src/main/rust/src/mamaps/read.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/read.rs@@ -19,8 +19,8 @@ //! only stores a `206` whose body length equals what was asked for, so a read of the wrong length //! does not merely fail, it poisons that range for every later read. //!-//! The reader speaks v8 only: a 128-byte header, 9 layers, full bodies. Anything else is-//! refused on open rather than reinterpreted.+//! The reader speaks v8 and v9 headers (128 bytes, 10 layers) and v8/v9/v10 bodies. Anything+//! else is refused on open rather than reinterpreted. pub mod archive; pub mod helpers;@@ -56,5 +56,5 @@ use std::cell::RefCell; pub use archive::MamapsArchive; pub use helpers::{decompress, open_prefix, read_all, MIN_FILE_LEN};-pub use leaf_cache::{LeafCache, DEFAULT_LEAF_CACHE_CAPACITY};+pub use leaf_cache::{LeafCache, DEFAULT_LEAF_CACHE_BYTES, DEFAULT_LEAF_CACHE_CAPACITY}; pub use overlay::{OverlayArchive, TileSource, base_matches, prune_tombstones};
library/tilecodec/src/main/rust/src/mamaps/read/leaf_cache.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/read/leaf_cache.rs b/library/tilecodec/src/main/rust/src/mamaps/read/leaf_cache.rsindex 6cf125e25f..a0ec172049 100644--- a/library/tilecodec/src/main/rust/src/mamaps/read/leaf_cache.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/read/leaf_cache.rs@@ -26,10 +26,23 @@ use crate::mamaps::index::LeafEntry; /// while each entry stays a parsed in-memory index (tens of KB), not tile data. pub const DEFAULT_LEAF_CACHE_CAPACITY: usize = 64; +/// The byte budget a shared cache keeps by default, on top of the entry count.+///+/// The count alone assumed small leaves. A planet archive's leaves hold up to+/// `leaf_entry_capacity` = 262 144 entries (planet3 and planet4 both), i.e. 4 MiB+/// parsed each, so 64 of them could pin 256 MiB on a phone over a long session of+/// panning and zooming (every zoom level lives in its own leaves). 48 MiB keeps a+/// dozen planet leaves — a viewport's walk through every zoom plus panning — and+/// leaves state-sized archives, whose leaves are kilobytes, bound by the count as+/// before. The newest entry is always kept, so one oversize leaf still resolves.+pub const DEFAULT_LEAF_CACHE_BYTES: usize = 48 * 1024 * 1024;+ struct State { entries: HashMap<u64, Arc<Vec<LeafEntry>>>, /// `leaf_offset`s in use order, most-recently-used last. order: VecDeque<u64>,+ /// Parsed bytes currently held (`entries × size_of::<LeafEntry>()`).+ bytes: usize, } /// Parsed `.mamaps` leaves keyed by `leaf_offset`, shared across threads.@@ -46,6 +59,7 @@ struct State { /// a failed worker cannot wedge the rest of the surface. pub struct LeafCache { capacity: usize,+ max_bytes: usize, state: Mutex<State>, } @@ -55,17 +69,36 @@ impl LeafCache { Self::with_capacity(DEFAULT_LEAF_CACHE_CAPACITY) } - /// A cache with `capacity` entries. A zero capacity is raised to one.+ /// A cache with `capacity` entries and the default byte budget. A zero capacity is+ /// raised to one. pub fn with_capacity(capacity: usize) -> Self {+ Self::with_limits(capacity, DEFAULT_LEAF_CACHE_BYTES)+ }++ /// A cache bounded by both `capacity` entries and `max_bytes` parsed bytes, whichever+ /// binds first. The most recently inserted leaf is always kept.+ pub fn with_limits(capacity: usize, max_bytes: usize) -> Self { LeafCache { capacity: capacity.max(1),+ max_bytes, state: Mutex::new(State { entries: HashMap::new(), order: VecDeque::new(),+ bytes: 0, }), } } + /// The byte budget this cache was built with.+ pub fn max_bytes(&self) -> usize {+ self.max_bytes+ }++ /// Parsed bytes currently held.+ pub fn bytes(&self) -> usize {+ self.state.lock().map(|s| s.bytes).unwrap_or(0)+ }+ /// The entry budget this cache was built with. pub fn capacity(&self) -> usize { self.capacity@@ -113,11 +146,16 @@ impl LeafCache { return existing; } let stored = Arc::new(entries);+ state.bytes += leaf_bytes(&stored); state.entries.insert(leaf_offset, Arc::clone(&stored)); state.order.push_back(leaf_offset);- while state.entries.len() > self.capacity {+ while state.entries.len() > 1+ && (state.entries.len() > self.capacity || state.bytes > self.max_bytes)+ { if let Some(oldest) = state.order.pop_front() {- state.entries.remove(&oldest);+ if let Some(gone) = state.entries.remove(&oldest) {+ state.bytes = state.bytes.saturating_sub(leaf_bytes(&gone));+ } } else { break; }@@ -126,6 +164,11 @@ impl LeafCache { } } +/// Parsed size of one leaf, as the byte budget counts it.+fn leaf_bytes(entries: &[LeafEntry]) -> usize {+ std::mem::size_of_val(entries)+}+ impl Default for LeafCache { fn default() -> Self { Self::new()
library/tilecodec/src/main/rust/src/mamaps/write/tests.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/write/tests.rs b/library/tilecodec/src/main/rust/src/mamaps/write/tests.rsindex 24e7720b71..f7099e6dd3 100644--- a/library/tilecodec/src/main/rust/src/mamaps/write/tests.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/write/tests.rs@@ -14,8 +14,8 @@ use crate::mamaps::body::Body; w.finish().expect("finish") } - /// Every build is v7: version byte 7, 128-byte header, `file_len` covering- /// exactly header/dictionary/root/leaves/data.+ /// Every build is a v9 container (the planet3/planet4 header): version byte 9,+ /// 128-byte header, `file_len` covering exactly header/dictionary/root/leaves/data. #[test] fn builds_are_v7_full_only() { let bytes = two_tiles(Options::default());@@ -25,6 +25,6 @@ use crate::mamaps::body::Body; "file_len covers exactly the v7 sections" ); assert_eq!(bytes.len(), 128 + header.dict_len as usize + header.root_len as usize + header.leaf_len as usize + header.data_len as usize);- assert_eq!(bytes[7], 7, "a build is version byte 7");+ assert_eq!(bytes[7], crate::mamaps::header::FORMAT_VERSION_V9, "a build is version byte 9"); assert_eq!(header.wire_len(), 128); }
library/tilecodec/src/main/rust/tests/shared_leaf_cache.rs
diff --git a/library/tilecodec/src/main/rust/tests/shared_leaf_cache.rs b/library/tilecodec/src/main/rust/tests/shared_leaf_cache.rsindex cea13cc943..2244fd16fd 100644--- a/library/tilecodec/src/main/rust/tests/shared_leaf_cache.rs+++ b/library/tilecodec/src/main/rust/tests/shared_leaf_cache.rs@@ -196,3 +196,28 @@ fn two_archives_over_one_cache_fetch_a_shared_leaf_once() { "open plus a shared-leaf tile: prefix and body, no second leaf fetch" ); }++#[test]+fn planet_sized_leaves_are_bounded_by_bytes_not_count() {+ use tilecodec::mamaps::read::DEFAULT_LEAF_CACHE_BYTES;+ // A planet leaf: 262 144 entries x 16 B = 4 MiB parsed (planet3/planet4 capacity).+ let big = |lo: u32| {+ vec![LeafEntry { tile_id_lo: lo, run_length: 1, offset_delta: 0, length: 1 }; 262_144]+ };+ let cache = LeafCache::new();+ for i in 0..40u64 {+ cache.insert(i, big(i as u32));+ }+ assert!(cache.bytes() <= DEFAULT_LEAF_CACHE_BYTES, "held {} bytes", cache.bytes());+ assert_eq!(cache.len(), DEFAULT_LEAF_CACHE_BYTES / (262_144 * 16));+ assert!(cache.get(39).is_some(), "the newest leaf survives");+ assert!(cache.get(0).is_none(), "the oldest planet leaves are evicted by bytes");+}++#[test]+fn one_oversize_leaf_is_still_kept() {+ let cache = LeafCache::with_limits(64, 1024);+ cache.insert(1, vec![LeafEntry { tile_id_lo: 1, run_length: 1, offset_delta: 0, length: 1 }; 1000]);+ assert!(cache.get(1).is_some());+ assert_eq!(cache.len(), 1);+}