Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
dependencies ▾

Modern-Apps.git / library / tilecodec / src / main / rust / tests / leaf_compression.rs

leaf_compression.rs220 lines · 10.0 KiBRaw
1//! Phase 5 leaf compression: integration gate.
2//!
3//! The lib test target is broken at HEAD by in-progress header work (`shared_*` fields
4//! referenced from `mamaps::archive::tests` before they land on `Header`), so this file
5//! exercises the same invariants through the public API only: it builds against the lib,
6//! never against `#[cfg(test)]` code. The unit tests in `mamaps/index.rs` and
7//! `mamaps/tests_extra.rs` remain the long-term home and assert the same facts; this file
8//! is the gate that actually runs until the header work lands.
9
10use std::cell::RefCell;
11use std::rc::Rc;
12use tilecodec::mamaps::body::{
13 Body, Feature, Layer, Part, DEFAULT_EXTENT, GEOM_LINE, NAME_NONE, WINDING_OUTER,
14};
15use tilecodec::mamaps::dict;
16use tilecodec::mamaps::header::{Header, FORMAT_VERSION, FORMAT_VERSION_V9, HEADER_LEN};
17use tilecodec::mamaps::index::{self, LEAF_ENTRY_LEN, ROOT_ENTRY_LEN};
18use tilecodec::mamaps::read::{self, MamapsArchive};
19use tilecodec::mamaps::write::{Options, StreamWriter};
20use tilecodec::pmtiles::tile_id;
21use tilecodec::proto::Result;
22use tilecodec::stream::{RangeReader, OPEN_PREFIX_BYTES};
23
24type Requests = Rc<RefCell<Vec<(u64, u32)>>>;
25type CountingArchive = MamapsArchive<Counting>;
26
27/// A [`RangeReader`] over bytes in memory that logs every range asked for, so a test can assert
28/// on the **number of round trips** as well as on the bytes.
29///
30/// The log is shared by handle: `MamapsArchive` owns the reader (its `reader` field is
31/// crate-private for the in-crate counting tests), so the test keeps the other end.
32struct Counting {
33 bytes: Vec<u8>,
34 requests: Rc<RefCell<Vec<(u64, u32)>>>,
35}
36
37impl RangeReader for Counting {
38 fn read(&self, offset: u64, length: u32) -> Result<Vec<u8>> {
39 self.requests.borrow_mut().push((offset, length));
40 if offset >= self.bytes.len() as u64 {
41 return Ok(Vec::new());
42 }
43 let end = (offset + length as u64).min(self.bytes.len() as u64);
44 Ok(self.bytes[offset as usize..end as usize].to_vec())
45 }
46}
47
48/// A one-line body whose contents depend on `seed`, so two tiles differ unless asked not to.
49fn body_for(seed: i16) -> Body {
50 let mut roads = Layer::new(dict::LAYER_ROADS);
51 roads.features.push(Feature {
52 kind: 45,
53 kind_detail: dict::NONE,
54 geom_type: GEOM_LINE,
55 flags: 0,
56 name_idx: NAME_NONE,
57 parts_offset: 0,
58 part_count: 1,
59 transit_color: 0,
60 transit_ordinal: 0,
61 transit_lanes: 0,
62 transit_taper: 0,
63 lane_count: 0,
64 });
65 roads.parts.push(Part { coord_start: 0, point_count: 2, winding: WINDING_OUTER });
66 roads.coords = vec![(0, 0), (seed, seed)];
67 Body {
68 extent: DEFAULT_EXTENT,
69 layers: vec![roads],
70 names: Vec::new(),
71 ids: Vec::new(),
72 turn_lanes: Vec::new(),
73 buildings: Vec::new(),
74 heightmap: None,
75 carriageways: Vec::new(),
76 convention: None,
77 region_links: Vec::new(),
78 }
79}
80
81/// An archive of `(z, x, y, seed)` tiles, fed in ascending id order as the writer requires.
82fn archive(tiles: &[(u8, u64, u64, i16)], options: Options) -> Vec<u8> {
83 let mut rows: Vec<(u64, i16)> =
84 tiles.iter().map(|(z, x, y, seed)| (tile_id(*z, *x, *y), *seed)).collect();
85 rows.sort_by_key(|(id, _)| *id);
86 let mut writer = StreamWriter::new(options).expect("options");
87 for (id, seed) in rows {
88 writer.append(id, &body_for(seed)).expect("append");
89 }
90 writer.finish().expect("finish")
91}
92
93fn open(bytes: Vec<u8>) -> (CountingArchive, Requests) {
94 let requests = Rc::new(RefCell::new(Vec::new()));
95 let a = MamapsArchive::open(Counting { bytes, requests: Rc::clone(&requests) }).expect("open");
96 (a, requests)
97}
98
99/// Enough tiles for several leaves, with repeats so runs and content dedup both fire.
100fn leafy_tiles() -> Vec<(u8, u64, u64, i16)> {
101 let mut tiles = Vec::new();
102 for z in 0..=4u8 {
103 for x in 0..(1u64 << z) {
104 for y in 0..(1u64 << z) {
105 tiles.push((z, x, y, ((x + y) % 3) as i16));
106 }
107 }
108 }
109 tiles
110}
111
112/// Each leaf is one raw-DEFLATE frame; the root stays raw at 32 B stride inside the opening
113/// prefix. A compressed archive opens in one request, reads back exactly, and its leaf section
114/// is smaller than the raw one.
115#[test]
116fn compressed_leaves_round_trip_and_keep_the_prefix_budget() {
117 assert!(Options::default().compress_leaves, "leaf compression is on by default");
118 let tiles = leafy_tiles();
119 let options = Options { leaf_entry_capacity: 16, ..Options::default() };
120 let bytes = archive(&tiles, options);
121 let header = Header::parse(&bytes).expect("header");
122 assert!(header.leaves_compressed(), "the flag is set");
123 assert_eq!(bytes[7], FORMAT_VERSION_V9, "a v9 version byte");
124 assert!(header.leaf_count > 1, "this test needs several leaves");
125 // The root is still raw fixed stride inside the opening prefix.
126 let prefix = HEADER_LEN as u64 + header.dict_len as u64 + header.root_len as u64;
127 assert!(prefix <= OPEN_PREFIX_BYTES as u64, "the prefix is {prefix} bytes");
128 assert_eq!(header.root_len as usize % ROOT_ENTRY_LEN, 0, "raw 32 B stride");
129 // Every leaf's stored length comes from its root entry, and inflates to count * 16.
130 let (h2, _, root) = read::open_prefix(&bytes).expect("open_prefix");
131 assert_eq!(h2.leaf_count as usize, root.len());
132 let mut raw_total: u64 = 0;
133 for e in &root {
134 let raw_len = e.leaf_entry_count as usize * LEAF_ENTRY_LEN;
135 raw_total += raw_len as u64;
136 let at = (h2.leaf_offset + e.leaf_offset) as usize;
137 if e.stored_len == 0 {
138 assert_eq!(raw_len, bytes[at..at + raw_len].len());
139 } else {
140 let back = index::decompress_leaf(&bytes[at..at + e.stored_len as usize], raw_len)
141 .expect("leaf frame");
142 assert_eq!(back.len(), raw_len, "exactly count * 16, allocated once");
143 assert_eq!(index::parse_leaf(&back).expect("parse").len(), e.leaf_entry_count as usize);
144 }
145 }
146 assert!(header.leaf_len < raw_total, "the stored section is smaller than the raw leaves");
147 // And the whole archive reads back tile-for-tile through the range-reader path.
148 let (a, requests) = open(bytes);
149 assert_eq!(requests.borrow().len(), 1, "open is still one request");
150 for (z, x, y, seed) in &tiles {
151 let tile = a.tile(*z, *x as u32, *y as u32).expect("read").expect("present");
152 assert_eq!(tile, body_for(*seed), "z{z}/{x}/{y}");
153 }
154}
155
156/// `compress_leaves: false` is the legacy layout bit for bit — no flag, v8 version byte, zero
157/// stored words — and it opens on the same reader. Both modes are deterministic.
158#[test]
159fn raw_leaves_stay_byte_identical_and_still_open() {
160 let tiles: Vec<(u8, u64, u64, i16)> =
161 (0..4u64).flat_map(|x| (0..4u64).map(move |y| (2u8, x, y, (x * 4 + y) as i16))).collect();
162 let raw = archive(&tiles, Options { compress_leaves: false, ..Options::default() });
163 let header = Header::parse(&raw).expect("header");
164 assert!(!header.leaves_compressed(), "no flag");
165 assert_eq!(raw[7], FORMAT_VERSION, "a v8 version byte");
166 let (_, _, root) = read::open_prefix(&raw).expect("open_prefix");
167 assert!(root.iter().all(|e| e.stored_len == 0), "zero stored words");
168 // Legacy determinism holds: two builds are still byte-identical.
169 let raw2 = archive(&tiles, Options { compress_leaves: false, ..Options::default() });
170 assert_eq!(raw, raw2);
171 // And compressed builds are deterministic too.
172 let c1 = archive(&tiles, Options::default());
173 let c2 = archive(&tiles, Options::default());
174 assert_eq!(c1, c2);
175 // Both open and read on the same reader.
176 for bytes in [raw, c1] {
177 let (a, _) = open(bytes);
178 assert_eq!(a.tile(2, 3, 3).expect("read").expect("present"), body_for(15));
179 }
180}
181
182/// A cold tile still costs exactly two requests (leaf + body), a warm tile one — compression
183/// changes the bytes fetched, never the count.
184#[test]
185fn a_cold_tile_is_still_two_requests_and_a_warm_tile_one() {
186 let tiles = leafy_tiles();
187 let options = Options { leaf_entry_capacity: 16, ..Options::default() };
188 let (a, requests) = open(archive(&tiles, options));
189 assert!(a.header.leaf_count > 1, "this test needs several leaves");
190 requests.borrow_mut().clear();
191 assert!(a.tile(4, 0, 0).expect("read").is_some());
192 assert_eq!(requests.borrow().len(), 2, "a cold tile is a leaf plus a body");
193 requests.borrow_mut().clear();
194 assert!(a.tile(4, 1, 1).expect("read").is_some());
195 assert_eq!(requests.borrow().len(), 1, "its leaf is now cached, so only the body");
196}
197
198/// An old (v8) reader refuses a leaf-compressed archive cleanly: the flag is unknown to it, and
199/// so is the non-zero word where a reserved zero used to be. It never misreads the leaf section
200/// as raw entries.
201#[test]
202fn an_old_reader_refuses_a_compressed_archive_rather_than_misreading_it() {
203 use tilecodec::mamaps::header::{FLAG_BODIES_COMPRESSED, FLAG_LEAF_LEN_64};
204 use tilecodec::mamaps::header::{FLAG_RINGS_VALIDATED, FLAG_RUN_LENGTH_PRESENT};
205 let tiles = leafy_tiles();
206 let bytes = archive(&tiles, Options { leaf_entry_capacity: 16, ..Options::default() });
207 let header = Header::parse(&bytes).expect("new reader opens");
208 assert!(header.leaves_compressed());
209 // Simulate the v8 refusal rules against the real bytes: unknown flag bits, and a non-zero
210 // word where v8's root parser demanded zero.
211 const V8_KNOWN: u16 =
212 FLAG_BODIES_COMPRESSED | FLAG_RUN_LENGTH_PRESENT | FLAG_RINGS_VALIDATED | FLAG_LEAF_LEN_64;
213 assert_ne!(header.flags & !V8_KNOWN, 0, "the new flag is unknown to v8");
214 let (_, _, root) = read::open_prefix(&bytes).expect("open_prefix");
215 assert!(root.iter().any(|e| e.stored_len != 0), "a v8 zero-check would fire");
216 // The 128-byte shape itself is unchanged (same length, same section offsets); it is the
217 // flag/word checks in `parse` that refuse, before any leaf is ever addressed.
218 assert_eq!(bytes.len(), header.file_len as usize);
219 assert_eq!(HEADER_LEN, 128);
220}