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

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

shared_leaf_cache.rs223 lines · 7.8 KiBRaw
1//! Shared leaf cache: the issue-815 MapLibre-parity gate.
2//!
3//! The lib test target is broken at HEAD by in-progress header work (`shared_*`
4//! fields referenced from `mamaps::archive::tests` before they land on
5//! `Header`), so like `leaf_compression.rs` this exercises the public API only:
6//! it builds against the lib, never against `#[cfg(test)]` code.
7
8use std::sync::Arc;
9use tilecodec::mamaps::index::LeafEntry;
10use tilecodec::mamaps::read::{LeafCache, DEFAULT_LEAF_CACHE_CAPACITY};
11
12fn leaf(first: u32) -> Vec<LeafEntry> {
13 vec![LeafEntry { tile_id_lo: first, run_length: 1, offset_delta: 0, length: 8 }]
14}
15
16#[test]
17fn an_inserted_leaf_reads_back() {
18 let cache = LeafCache::new();
19 assert_eq!(cache.capacity(), DEFAULT_LEAF_CACHE_CAPACITY);
20 assert!(cache.is_empty());
21 cache.insert(7, leaf(10));
22 assert_eq!(cache.len(), 1);
23 let hit = cache.get(7).expect("cached");
24 assert_eq!(hit.len(), 1);
25 assert_eq!(hit[0].tile_id_lo, 10);
26 assert!(cache.get(8).is_none(), "a miss is None");
27}
28
29#[test]
30fn the_cache_evicts_least_recently_used() {
31 let cache = LeafCache::with_capacity(2);
32 cache.insert(1, leaf(1));
33 cache.insert(2, leaf(2));
34 // Touch 1 so 2 is the eviction candidate.
35 let _ = cache.get(1);
36 cache.insert(3, leaf(3));
37 assert!(cache.get(1).is_some(), "recently used survives");
38 assert!(cache.get(2).is_none(), "least-recently-used is evicted");
39 assert!(cache.get(3).is_some());
40 assert_eq!(cache.len(), 2);
41}
42
43#[test]
44fn a_zero_capacity_still_holds_one_leaf() {
45 let cache = LeafCache::with_capacity(0);
46 assert_eq!(cache.capacity(), 1);
47 cache.insert(1, leaf(1));
48 assert!(cache.get(1).is_some());
49}
50
51#[test]
52fn a_racing_insert_keeps_one_copy() {
53 let cache = LeafCache::new();
54 let first = cache.insert(9, leaf(1));
55 let second = cache.insert(9, leaf(2));
56 assert!(Arc::ptr_eq(&first, &second), "the loser uses the winner's copy");
57 assert_eq!(cache.len(), 1);
58 assert_eq!(cache.get(9).expect("cached")[0].tile_id_lo, 1);
59}
60
61#[test]
62fn the_cache_shares_across_threads() {
63 let cache = Arc::new(LeafCache::new());
64 let mut handles = Vec::new();
65 for i in 0..8u64 {
66 let cache = Arc::clone(&cache);
67 handles.push(std::thread::spawn(move || {
68 cache.insert(i, leaf(i as u32));
69 // Every thread reads every leaf; concurrent gets are safe.
70 for j in 0..8u64 {
71 let _ = cache.get(j);
72 }
73 }));
74 }
75 for h in handles {
76 h.join().expect("worker");
77 }
78 assert_eq!(cache.len(), 8);
79 for i in 0..8u64 {
80 assert!(cache.get(i).is_some(), "leaf {i} survived the race");
81 }
82}
83
84/// Two archive views over one cache fetch a shared leaf once.
85///
86/// The cost contract the container exists to hold — open is one request, a
87/// warm tile one, a cold tile two — now holds *across* readers: the second
88/// view's tile costs one request (its body) because the first view's leaf
89/// fetch already populated the shared cache. Before the shared cache this
90/// second view paid two.
91#[test]
92fn two_archives_over_one_cache_fetch_a_shared_leaf_once() {
93 use tilecodec::mamaps::body::{
94 Body, Feature, Layer, Part, DEFAULT_EXTENT, GEOM_LINE, WINDING_OUTER,
95 };
96 use tilecodec::mamaps::dict;
97 use tilecodec::mamaps::read::MamapsArchive;
98 use tilecodec::mamaps::write::{Options, StreamWriter};
99 use tilecodec::pmtiles::tile_id;
100 use tilecodec::proto::Result;
101 use tilecodec::stream::RangeReader;
102
103 struct Counting {
104 bytes: Vec<u8>,
105 requests: std::cell::RefCell<Vec<(u64, u32)>>,
106 }
107 impl RangeReader for Counting {
108 fn read(&self, offset: u64, length: u32) -> Result<Vec<u8>> {
109 self.requests.borrow_mut().push((offset, length));
110 if offset >= self.bytes.len() as u64 {
111 return Ok(Vec::new());
112 }
113 let end = (offset + length as u64).min(self.bytes.len() as u64);
114 Ok(self.bytes[offset as usize..end as usize].to_vec())
115 }
116 }
117
118 fn body_for(seed: i16) -> Body {
119 let mut roads = Layer::new(dict::LAYER_ROADS);
120 roads.features.push(Feature {
121 kind: 45,
122 kind_detail: dict::NONE,
123 geom_type: GEOM_LINE,
124 flags: 0,
125 name_idx: tilecodec::mamaps::body::NAME_NONE,
126 parts_offset: 0,
127 part_count: 1,
128 transit_color: 0,
129 transit_ordinal: 0,
130 transit_lanes: 0,
131 transit_taper: 0,
132 lane_count: 0,
133 });
134 roads.parts.push(Part { coord_start: 0, point_count: 2, winding: WINDING_OUTER });
135 roads.coords = vec![(0, 0), (seed, seed)];
136 Body {
137 extent: DEFAULT_EXTENT,
138 layers: vec![roads],
139 names: Vec::new(),
140 ids: Vec::new(),
141 turn_lanes: Vec::new(),
142 buildings: Vec::new(),
143 heightmap: None,
144 carriageways: Vec::new(),
145 convention: None,
146 region_links: Vec::new(),
147 }
148 }
149
150 // Several leaves so a tile really has a leaf to share.
151 let mut tiles: Vec<(u8, u64, u64, i16)> = Vec::new();
152 for z in 0..=3u8 {
153 for x in 0..(1u64 << z) {
154 for y in 0..(1u64 << z) {
155 tiles.push((z, x, y, (tile_id(z, x, y) + 1) as i16));
156 }
157 }
158 }
159 let options = Options { leaf_entry_capacity: 16, ..Options::default() };
160 let mut rows: Vec<(u64, i16)> =
161 tiles.iter().map(|(z, x, y, seed)| (tile_id(*z, *x, *y), *seed)).collect();
162 rows.sort_by_key(|(id, _)| *id);
163 let mut writer = StreamWriter::new(options).expect("options");
164 for (id, seed) in rows {
165 writer.append(id, &body_for(seed)).expect("append");
166 }
167 let bytes = writer.finish().expect("finish");
168
169 let leaves = Arc::new(LeafCache::new());
170 let count = |a: &MamapsArchive<Counting>| a.reader().requests.borrow().len();
171
172 // First view: cold tile costs two (leaf + body).
173 let first = MamapsArchive::open_with_cache(
174 Counting { bytes: bytes.clone(), requests: std::cell::RefCell::new(Vec::new()) },
175 Arc::clone(&leaves),
176 )
177 .expect("open");
178 assert!(first.tile(3, 0, 0).expect("read").is_some());
179 assert_eq!(count(&first), 3, "open plus a cold tile: prefix, leaf, body");
180
181 // Second view over the same bytes and the same cache: the same tile costs
182 // one request (its body) — the leaf came from the shared cache, and the
183 // prefix open is its own one request.
184 let second = MamapsArchive::open_with_cache(
185 Counting { bytes, requests: std::cell::RefCell::new(Vec::new()) },
186 Arc::clone(&leaves),
187 )
188 .expect("open");
189 assert!(second.tile(3, 0, 0).expect("read").is_some());
190 assert_eq!(
191 count(&second),
192 2,
193 "open plus a shared-leaf tile: prefix and body, no second leaf fetch"
194 );
195}
196
197#[test]
198fn planet_sized_leaves_are_bounded_by_bytes_not_count() {
199 use tilecodec::mamaps::read::DEFAULT_LEAF_CACHE_BYTES;
200 // A planet leaf: 262 144 entries x 16 B = 4 MiB parsed (planet3/planet4 capacity).
201 let big = |lo: u32| {
202 vec![LeafEntry { tile_id_lo: lo, run_length: 1, offset_delta: 0, length: 1 }; 262_144]
203 };
204 let cache = LeafCache::new();
205 for i in 0..40u64 {
206 cache.insert(i, big(i as u32));
207 }
208 assert!(cache.bytes() <= DEFAULT_LEAF_CACHE_BYTES, "held {} bytes", cache.bytes());
209 assert_eq!(cache.len(), DEFAULT_LEAF_CACHE_BYTES / (262_144 * 16));
210 assert!(cache.get(39).is_some(), "the newest leaf survives");
211 assert!(cache.get(0).is_none(), "the oldest planet leaves are evicted by bytes");
212}
213
214#[test]
215fn one_oversize_leaf_is_still_kept() {
216 let cache = LeafCache::with_limits(64, 1024);
217 cache.insert(
218 1,
219 vec![LeafEntry { tile_id_lo: 1, run_length: 1, offset_delta: 0, length: 1 }; 1000],
220 );
221 assert!(cache.get(1).is_some());
222 assert_eq!(cache.len(), 1);
223}