tilecodec: ZSEC sections, ZBLK at zstd-19, graph v8 / TRIX v8 (#planet5)
- Commit
9619ccc8152c885136bc164cef2686f768e69276- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-14 00:53 UTC (22 days ago)
- Parents
063fd0c
The sidecar half of the planet5 format, shared by the writers in
scripts/maps and the readers in the maps app.
- zsec.rs: random-access block compression for byte-addressed
sections (transit's varint streams, string pool, fixed-stride
tables, polylines): fixed-size byte blocks, each an independent
zstd frame, behind an absolute u64 offset table ("ZSEC" header +
table + frames). Parse validates the table; block(i) inflates one
block with ruzstd. write_zsec (write feature) compresses blocks on
all cores; output is independent of the thread count. Measured on
the planet transit pack: 64 KiB blocks at zstd-19 take it 4.44 GB
-> 1.19 GB (with the v8 trimming).
- blocked.rs: ZBLK frames are written at BLOCK_LEVEL = 19 (was 10).
Same reader; planet nodes 4.34 -> 3.40 GB, edge records 4.61 ->
4.24 GB (measured by re-encoding the planet's own blocks); a cold
block decodes ~1.4x slower, cached afterwards.
- archive consts: GRAPH_VERSION 8 (GRAPH_VERSION_VARINT: varint shape
points, see the maps reader) with GRAPH_VERSION_BLOCKED = 7 naming
what "blocked" used to test via GRAPH_VERSION; TRANSIT_VERSION 8
(TRANSIT_VERSION_ZSEC: every section a ZSEC section). The archive
view's blocked check now compares against GRAPH_VERSION_BLOCKED so
v7 archives still validate as blocked.
Verified: cargo test -p tilecodec --features write (ZSEC round-trips
every block size edge, refuses truncation and bad magic), and the
graph/transit readers below.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 28e5f2e4d8..5d6e3267c5 100644--- a/library/tilecodec/src/main/rust/src/blocked.rs+++ b/library/tilecodec/src/main/rust/src/blocked.rs@@ -34,6 +34,10 @@ pub const BLOCKED_MAGIC: u32 = 0x4B4C_425A; // "ZBLK" LE /// Records per zstd frame. 4096 × 12 B = 48 KiB nodes, 4096 × 7 B = 28 KiB /// edges: small enough to inflate on a lookup, large enough to compress. pub const BLOCK_RECORDS: u32 = 4096;+/// The zstd level every ZBLK frame is written at. 19 since planet5 (was 10): the planet's+/// nodes shrink 4.34 -> 3.40 GB and edge records 4.61 -> 4.24 GB, decoded by the same reader+/// at ~1.4x the per-block cost (cold blocks only; decoded blocks are cached).+pub const BLOCK_LEVEL: i32 = 19; /// A parsed blocked section over bytes the caller keeps alive. ///@@ -260,7 +264,7 @@ pub fn write_blocked_with(records: &[u8], record_len: usize, per_block: u32) -> let count = records.len() / record_len; let block_count = count.div_ceil(per_block as usize); let cfg = zstd_rs::CompressionConfig {- level: 10,+ level: BLOCK_LEVEL, ..zstd_rs::CompressionConfig::DEFAULT }; let mut enc = zstd_rs::Compressor::new(cfg).expect("valid zstd level");@@ -276,7 +280,7 @@ pub fn write_blocked_with(records: &[u8], record_len: usize, per_block: u32) -> assemble_blocked(record_len, per_block, records.len(), &frames) } -/// One block's zstd frame: a fresh level-10 encoder over `block`, exactly what+/// One block's zstd frame: a fresh [`BLOCK_LEVEL`] encoder over `block`, exactly what /// [`BlockedStreamWriter`] writes for it. Public so a caller can compress /// blocks on its own thread pool and hand the frames to /// [`BlockedStreamWriter::push_frames`] in order.@@ -284,7 +288,7 @@ pub fn write_blocked_with(records: &[u8], record_len: usize, per_block: u32) -> pub fn compress_block(block: &[u8]) -> Vec<u8> { // One context per thread, reused for every block it compresses. A fresh // `Compressor` per block (what this used to do) allocates and zeroes the- // level-10 match tables — megabytes — for every 28-48 KiB block, which+ // [`BLOCK_LEVEL`] match tables — megabytes — for every 28-48 KiB block, which // dominated the cost of compressing a planet's nodes.bin/edges.bin. The // encoder is built for reuse: its tables are epoch-tagged, so entries from // an earlier frame are never matched, and a frame "depends only on the@@ -298,7 +302,7 @@ pub fn compress_block(block: &[u8]) -> Vec<u8> { let mut slot = cell.borrow_mut(); let enc = slot.get_or_insert_with(|| { zstd_rs::Compressor::new(zstd_rs::CompressionConfig {- level: 10,+ level: BLOCK_LEVEL, ..zstd_rs::CompressionConfig::DEFAULT }) .expect("valid zstd level")@@ -623,7 +627,7 @@ mod tests { } let fresh = |b: &[u8]| { let mut enc = zstd_rs::Compressor::new(zstd_rs::CompressionConfig {- level: 10,+ level: BLOCK_LEVEL, ..zstd_rs::CompressionConfig::DEFAULT }) .unwrap();
library/tilecodec/src/main/rust/src/lib.rs
diff --git a/library/tilecodec/src/main/rust/src/lib.rs b/library/tilecodec/src/main/rust/src/lib.rsindex de54b8c11b..3bfc5aaa54 100644--- a/library/tilecodec/src/main/rust/src/lib.rs+++ b/library/tilecodec/src/main/rust/src/lib.rs@@ -42,3 +42,5 @@ pub mod stream; /// tables. Read side always linked; the writer ([`blocked::write_blocked`]) /// is behind the `write` feature like the tile writer. pub mod blocked;+/// Byte-addressed block compression for planet5 sidecars ([`zsec`]).+pub mod zsec;
library/tilecodec/src/main/rust/src/mamaps/archive/consts.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/archive/consts.rs b/library/tilecodec/src/main/rust/src/mamaps/archive/consts.rsindex 14912cff3d..b52ae2321e 100644--- a/library/tilecodec/src/main/rust/src/mamaps/archive/consts.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/archive/consts.rs@@ -53,7 +53,13 @@ pub const ARCHIVE_KIND_MAX_KNOWN: u8 = ARCHIVE_KIND_POI_ADMIN; pub const GRAPH_MAGIC: u32 = 0x4752_414D; /// Newest (and only, for the single archive) graph version: v7 blocked record /// sections (nodes, edges records, elevation).-pub const GRAPH_VERSION: u32 = 7;+pub const GRAPH_VERSION: u32 = 8;+/// First graph version whose nodes/edges/elevation are ZBLK blocked (v7 and later).+pub const GRAPH_VERSION_BLOCKED: u32 = 7;+/// Planet5: `intermediate.bin` blobs are zigzag-varint deltas on a 1e-6 degree grid (rather+/// than fixed `i16` 1e-7 degree deltas), thinned to a 1 m bound, with 16 geometry edges per+/// coarse block (`INTERMEDIATE_BLOCK_V8`) so a block's span still fits the `u16` within-table.+pub const GRAPH_VERSION_VARINT: u32 = 8; /// Oldest graph version accepted: v6 raw tables still validate by length. pub const GRAPH_VERSION_MIN: u32 = 6; /// `metadata.bin` wire length: magic + version + 4 counts.@@ -61,7 +67,11 @@ pub const GRAPH_META_LEN: u64 = 40; /// `transit` (`TRIX`) magic, little-endian `u32`. pub const TRANSIT_MAGIC: u32 = 0x5452_4958; /// Newest transit version accepted. v7 adds a host-only section the app never reads.-pub const TRANSIT_VERSION: u32 = 7;+pub const TRANSIT_VERSION: u32 = 8;+/// Planet5: every section of a v8 pack is a [`crate::zsec`] block-compressed section, its+/// directory length the stored length (the raw length is in the ZSEC header). v8 also drops the+/// unread ROUTE_TRIPS varint stream and thins SHAPE_COORDS.+pub const TRANSIT_VERSION_ZSEC: u32 = 8; /// Oldest transit version accepted. pub const TRANSIT_VERSION_MIN: u32 = 3; /// POI index record stride.
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 007fe80526..36f00a943c 100644--- a/library/tilecodec/src/main/rust/src/mamaps/archive/mod.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/archive/mod.rs@@ -104,8 +104,8 @@ pub use consts::{ ARCHIVE_KIND_GRAPH_NODES, ARCHIVE_KIND_GRAPH_OVERLAY, ARCHIVE_KIND_MAX_KNOWN, ARCHIVE_KIND_POI_ATTRS, ARCHIVE_KIND_POI_ADMIN, ARCHIVE_KIND_POI_INDEX, ARCHIVE_KIND_POI_NAMES, ARCHIVE_KIND_POI_REGION, ARCHIVE_KIND_POI_SPATIAL, ARCHIVE_KIND_POI_WORDS, ARCHIVE_KIND_TRANSIT, GRAPH_MAGIC,- GRAPH_META_LEN, GRAPH_VERSION, GRAPH_VERSION_MIN, POI_RECORD_BYTES, TRANSIT_MAGIC, TRANSIT_VERSION,- TRANSIT_VERSION_MIN,+ GRAPH_META_LEN, GRAPH_VERSION, GRAPH_VERSION_BLOCKED, GRAPH_VERSION_MIN, GRAPH_VERSION_VARINT,+ POI_RECORD_BYTES, TRANSIT_MAGIC, TRANSIT_VERSION, TRANSIT_VERSION_MIN, TRANSIT_VERSION_ZSEC, }; pub use entry::{is_known_kind, ArchiveEntry}; pub use footer::ArchiveFooter;
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 34c24a2a20..81cb3634c7 100644--- a/library/tilecodec/src/main/rust/src/mamaps/archive/view.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/archive/view.rs@@ -227,7 +227,7 @@ impl ArchiveView { return err("a single-archive graph node count overflows u32"); } let _ = header;- (n, e, esc, named, graph_version >= GRAPH_VERSION)+ (n, e, esc, named, graph_version >= GRAPH_VERSION_BLOCKED) } }; // Nodes: (N+1) 12-byte records (the sentinel). Under v7 a ZBLK
library/tilecodec/src/main/rust/src/zsec.rs
diff --git a/library/tilecodec/src/main/rust/src/zsec.rs b/library/tilecodec/src/main/rust/src/zsec.rsnew file mode 100644index 0000000000..0ea174dbc9--- /dev/null+++ b/library/tilecodec/src/main/rust/src/zsec.rs@@ -0,0 +1,186 @@+//! ZSEC: random-access block compression for byte-addressed sidecar sections (planet5).+//!+//! [`crate::blocked`] (ZBLK) compresses *record* tables, where a lookup is `record(id)`. Transit+//! and other sidecars are addressed by byte offset instead (varint streams, string pools,+//! polyline blobs, fixed-stride tables read by index), so ZSEC blocks the raw bytes: fixed+//! `block_size` byte ranges, each an independent zstd frame, behind an offset table. A reader+//! asks for the bytes at `[pos, pos + n)`, inflates the one or two blocks they span and caches+//! them; nothing is ever decoded whole.+//!+//! ```text+//! [magic "ZSEC" u32][block_size u32][raw_len u64][block_count u32][reserved u32 = 0]+//! [offsets u64 x (block_count + 1)] absolute from the section start; last = section end+//! [zstd frame][zstd frame]...+//! ```+//!+//! Measured on the planet: 64 KiB blocks at zstd-19 shrink `world.transit` 2.56x and the POI+//! sections 1.4-40x, at ~0.4 ms of host decode per cold block.++use crate::proto::{err, Error, Result};++pub const ZSEC_MAGIC: &[u8; 4] = b"ZSEC";+pub const ZSEC_HEADER_LEN: usize = 24;+/// The block size the writers use.+pub const ZSEC_BLOCK: usize = 64 * 1024;++/// A parsed ZSEC section over bytes the caller keeps alive.+#[derive(Clone, Copy)]+pub struct ZSec<'a> {+ bytes: &'a [u8],+ block_size: usize,+ raw_len: u64,+ block_count: usize,+}++impl<'a> ZSec<'a> {+ pub fn parse(bytes: &'a [u8]) -> Result<ZSec<'a>> {+ if bytes.len() < ZSEC_HEADER_LEN || &bytes[..4] != ZSEC_MAGIC {+ return err("not a ZSEC section (bad magic)");+ }+ let u32_at = |o: usize| u32::from_le_bytes(bytes[o..o + 4].try_into().unwrap());+ let block_size = u32_at(4) as usize;+ let raw_len = u64::from_le_bytes(bytes[8..16].try_into().unwrap());+ let block_count = u32_at(16) as usize;+ if u32_at(20) != 0 {+ return err("a ZSEC section sets reserved bits");+ }+ if block_size == 0 || (raw_len as u128) > block_count as u128 * block_size as u128 {+ return err("a ZSEC section's blocks cannot hold its length");+ }+ if block_count > 0 && (raw_len as u128) <= (block_count as u128 - 1) * block_size as u128 {+ return err("a ZSEC section has more blocks than its length needs");+ }+ let table_end = ZSEC_HEADER_LEN + (block_count + 1) * 8;+ if table_end > bytes.len() {+ return err("a ZSEC offset table runs past its section");+ }+ let z = ZSec { bytes, block_size, raw_len, block_count };+ let mut prev = table_end as u64;+ for i in 0..=block_count {+ let o = z.offset(i);+ if o < prev || o > bytes.len() as u64 {+ return err("a ZSEC offset table is out of order or out of bounds");+ }+ prev = o;+ }+ if z.offset(block_count) != bytes.len() as u64 {+ return err("a ZSEC section's last offset is not its end");+ }+ Ok(z)+ }++ fn offset(&self, i: usize) -> u64 {+ let at = ZSEC_HEADER_LEN + i * 8;+ u64::from_le_bytes(self.bytes[at..at + 8].try_into().unwrap())+ }++ pub fn raw_len(&self) -> u64 {+ self.raw_len+ }++ pub fn block_size(&self) -> usize {+ self.block_size+ }++ pub fn block_count(&self) -> usize {+ self.block_count+ }++ /// The decoded length of block `b` (the last one holds the remainder).+ pub fn block_len(&self, b: usize) -> usize {+ let start = b as u64 * self.block_size as u64;+ (self.raw_len - start).min(self.block_size as u64) as usize+ }++ /// Inflate block `b`.+ pub fn block(&self, b: usize) -> Result<Vec<u8>> {+ if b >= self.block_count {+ return err(format!("ZSEC block {b} of {}", self.block_count));+ }+ let frame = &self.bytes[self.offset(b) as usize..self.offset(b + 1) as usize];+ let mut out = vec![0u8; self.block_len(b)];+ let mut dec = ruzstd::decoding::FrameDecoder::new();+ let n = dec+ .decode_all(frame, &mut out)+ .map_err(|e| Error(format!("a ZSEC block will not decode: {e:?}")))?;+ if n != out.len() {+ return err("a ZSEC block decoded to the wrong length");+ }+ Ok(out)+ }+}++/// Compress `raw` into a ZSEC section: `block_size` blocks, zstd `level`, blocks compressed on+/// all cores (each is independent, so the output is the same at any thread count).+#[cfg(feature = "write")]+pub fn write_zsec(raw: &[u8], block_size: usize, level: i32) -> Vec<u8> {+ let blocks: Vec<&[u8]> = raw.chunks(block_size.max(1)).collect();+ let threads = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1).max(1);+ let per = blocks.len().div_ceil(threads).max(1);+ let frames: Vec<Vec<u8>> = std::thread::scope(|s| {+ let handles: Vec<_> = blocks+ .chunks(per)+ .map(|run| {+ s.spawn(move || {+ let cfg = zstd_rs::CompressionConfig { level, ..zstd_rs::CompressionConfig::DEFAULT };+ let mut enc = zstd_rs::Compressor::new(cfg).expect("valid zstd level");+ run.iter()+ .map(|b| {+ let mut out = Vec::with_capacity(b.len() / 2);+ enc.compress(b, None, &mut out).expect("zstd encode of an in-memory block");+ out+ })+ .collect::<Vec<_>>()+ })+ })+ .collect();+ handles.into_iter().flat_map(|h| h.join().expect("a ZSEC compression thread")).collect()+ });+ let table_end = ZSEC_HEADER_LEN + (frames.len() + 1) * 8;+ let total = table_end + frames.iter().map(|f| f.len()).sum::<usize>();+ let mut out = Vec::with_capacity(total);+ out.extend_from_slice(ZSEC_MAGIC);+ out.extend_from_slice(&(block_size as u32).to_le_bytes());+ out.extend_from_slice(&(raw.len() as u64).to_le_bytes());+ out.extend_from_slice(&(frames.len() as u32).to_le_bytes());+ out.extend_from_slice(&0u32.to_le_bytes());+ let mut at = table_end as u64;+ for f in &frames {+ out.extend_from_slice(&at.to_le_bytes());+ at += f.len() as u64;+ }+ out.extend_from_slice(&at.to_le_bytes());+ for f in &frames {+ out.extend_from_slice(f);+ }+ out+}++#[cfg(all(test, feature = "write"))]+mod tests {+ use super::*;++ #[test]+ fn a_zsec_section_round_trips_every_block() {+ for len in [0usize, 1, 1000, ZSEC_BLOCK, ZSEC_BLOCK + 1, 3 * ZSEC_BLOCK + 17] {+ let raw: Vec<u8> = (0..len).map(|i| (i * 31 % 251) as u8).collect();+ let sec = write_zsec(&raw, ZSEC_BLOCK, 19);+ let z = ZSec::parse(&sec).expect("parse");+ assert_eq!(z.raw_len(), len as u64);+ let mut back = Vec::new();+ for b in 0..z.block_count() {+ back.extend_from_slice(&z.block(b).expect("block"));+ }+ assert_eq!(back, raw, "len {len}");+ }+ }++ #[test]+ fn a_corrupt_zsec_section_is_refused() {+ let sec = write_zsec(&[7u8; 100_000], ZSEC_BLOCK, 3);+ assert!(ZSec::parse(&sec[..sec.len() - 1]).is_err(), "truncated");+ let mut bad = sec.clone();+ bad[0] = b'X';+ assert!(ZSec::parse(&bad).is_err(), "magic");+ }+}