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

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

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