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

Modern-Apps.git / scripts / maps / tile_build / src / churn.rs

churn.rs403 lines · 16.0 KiBRaw
1//! `churn` — byte-level leaf churn between two `.mamaps` archives.
2//!
3//! Phase 0 sizing gate for incremental updates: how many stored tile bodies
4//! would a patch-overlay have to carry from build A to build B, and how many
5//! sidecar bytes moved per section kind. Answers the overlay budget question
6//! (low-single-digit GB?) without decoding a single tile.
7//!
8//! What is compared is the STORED bytes, not the picture: the overlay ships
9//! stored bodies, so a byte difference ships even when the geometry did not
10//! move (e.g. `subdivide` ring rotation). `test/diff_mamaps.py` stays the
11//! picture check; this is the byte check.
12//!
13//! Cost model: two passes per archive, both range-based, no whole-file reads.
14//! Pass 1 walks the leaf index only (root from the open prefix, one read per
15//! leaf — the same walk as `mamaps_probe --breakdown`). Pass 2 fetches each
16//! DISTINCT stored body once (dedup-shared bodies hash once) and FNV-1a-hashes
17//! it. Bodies are never inflated or parsed. Peak memory is one compact entry
18//! per stored body (~24 B: tile id, run, length, hash) on each side, plus a
19//! transient offset table dropped after fingerprinting.
20//!
21//! Body identity is the fingerprint, not the offset: offsets always shift
22//! between builds (packed layout), so comparing offsets would report
23//! everything. Two tiles with equal fingerprints hold equal bodies even when
24//! run boundaries re-split around them, and report unchanged. The join is an
25//! interval merge over tile-id ranges (not entry-by-entry), so a re-split run
26//! covering the same tiles with the same bytes counts unchanged.
27
28use std::collections::{BTreeMap, HashMap, HashSet};
29
30use tilecodec::stream::RangeReader;
31
32use crate::mamaps::archive::{
33 ARCHIVE_DIR_HEADER_LEN, ARCHIVE_ENTRY_LEN, ARCHIVE_FOOTER_LEN, ARCHIVE_MAGIC, ArchiveEntry,
34 ArchiveFooter,
35};
36use crate::mamaps::{header, index};
37use crate::mamaps::write::hash64;
38use crate::pmtiles::tile_zxy;
39use crate::proto::{Result, err};
40
41/// One stored body's identity: where its tiles are, how big the body is, and
42/// what bytes it holds. Offsets are archive-local and never compared.
43#[derive(Debug, Clone, Copy)]
44pub struct Entry {
45 /// First tile id this entry covers.
46 pub tile_id: u64,
47 /// Consecutive tiles sharing this body. Never zero.
48 pub run_length: u32,
49 /// Stored body length (compressed, if the header says bodies are).
50 pub length: u32,
51 /// FNV-1a over the stored body bytes.
52 pub hash: u64,
53}
54
55/// One archive's fingerprint set: its entries plus the sidecar directory.
56pub struct Snapshot {
57 /// One per stored body, ascending by tile id (leaf-walk order).
58 pub entries: Vec<Entry>,
59 /// Sidecar `(kind, length)` from the `MAMA8` directory. Empty for a
60 /// tiles-only archive (no footer).
61 pub sidecars: Vec<(u8, u64)>,
62}
63
64/// A file-backed [`RangeReader`], like `mamaps_probe`'s: positional reads
65/// with short-on-past-end semantics, so tools get random access without
66/// mapping multi-GB files.
67pub struct FileReader {
68 file: std::sync::Mutex<std::fs::File>,
69}
70
71impl FileReader {
72 /// Open `path` for range reads.
73 pub fn open(path: &std::path::Path) -> Result<FileReader> {
74 let file = std::fs::File::open(path)
75 .map_err(|e| crate::proto::Error(format!("cannot open {}: {e}", path.display())))?;
76 Ok(FileReader { file: std::sync::Mutex::new(file) })
77 }
78}
79
80impl RangeReader for FileReader {
81 fn read(&self, offset: u64, length: u32) -> Result<Vec<u8>> {
82 use std::io::{Read as _, Seek as _};
83 let mut file = self
84 .file
85 .lock()
86 .map_err(|_| crate::proto::Error("churn reader lock failed".to_string()))?;
87 file.seek(std::io::SeekFrom::Start(offset))
88 .map_err(|e| crate::proto::Error(format!("seek {offset}: {e}")))?;
89 let mut buf = vec![0u8; length as usize];
90 let mut got = 0usize;
91 while got < buf.len() {
92 match file.read(&mut buf[got..]) {
93 Ok(0) => break,
94 Ok(n) => got += n,
95 Err(e) => return err(format!("read at {offset}: {e}")),
96 }
97 }
98 buf.truncate(got);
99 Ok(buf)
100 }
101}
102
103/// Walk one archive's leaf index (no bodies) and fingerprint each distinct body.
104///
105/// `file_len` is the archive's length in bytes (for the footer read); it is a
106/// parameter because [`RangeReader`] has no length.
107pub fn snapshot<R: RangeReader>(reader: &R, file_len: u64) -> Result<Snapshot> {
108 let prefix = reader.read(0, tilecodec::stream::OPEN_PREFIX_BYTES)?;
109 let hdr = header::Header::parse(&prefix)?;
110 let root_bytes = prefix_section(&prefix, hdr.root_offset, hdr.root_len as u64, "root index")?;
111 let root = index::parse_root(root_bytes)?;
112 // Located entries first (offsets needed for fingerprinting), compacted after.
113 let mut located: Vec<(u64, u32, u32, u64)> = Vec::new();
114 for root_entry in &root {
115 let raw_len = root_entry.leaf_entry_count as u64 * index::LEAF_ENTRY_LEN as u64;
116 let stored_len =
117 if root_entry.stored_len == 0 { raw_len } else { root_entry.stored_len as u64 };
118 let stored = reader.read(hdr.leaf_offset + root_entry.leaf_offset, stored_len as u32)?;
119 if stored.len() as u64 != stored_len {
120 return err("a .mamaps leaf read came back short".to_string());
121 }
122 let raw = if root_entry.stored_len == 0 {
123 stored
124 } else {
125 index::decompress_leaf(&stored, raw_len as usize)?
126 };
127 for e in index::parse_leaf(&raw)? {
128 let offset = hdr.data_offset + root_entry.base_data_offset + e.offset_delta as u64;
129 located.push((
130 root_entry.base_tile_id + e.tile_id_lo as u64,
131 e.run_length,
132 e.length,
133 offset,
134 ));
135 }
136 }
137 let entries = fingerprint(reader, &located)?;
138 let sidecars = read_sidecar_dir(reader, file_len)?;
139 Ok(Snapshot { entries, sidecars })
140}
141
142/// Hash every distinct stored body once; entries sharing a body share its hash.
143///
144/// `located` is `(tile_id, run_length, length, offset)` in entry order. The
145/// returned entries drop the offsets: they are archive-local and useless for
146/// the join, and dropping them keeps the snapshot at ~24 B per body.
147fn fingerprint<R: RangeReader>(
148 reader: &R,
149 located: &[(u64, u32, u32, u64)],
150) -> Result<Vec<Entry>> {
151 let mut hashes: HashMap<(u64, u32), u64> = HashMap::new();
152 let mut entries = Vec::with_capacity(located.len());
153 for (tile_id, run_length, length, offset) in located {
154 let key = (*offset, *length);
155 let hash = match hashes.get(&key) {
156 Some(h) => *h,
157 None => {
158 let stored = reader.read(*offset, *length)?;
159 if stored.len() as u64 != u64::from(*length) {
160 return err(format!(
161 "body at {offset} came back short: {} of {length} bytes",
162 stored.len(),
163 ));
164 }
165 let hash = hash64(&stored);
166 hashes.insert(key, hash);
167 hash
168 }
169 };
170 entries.push(Entry { tile_id: *tile_id, run_length: *run_length, length: *length, hash });
171 }
172 Ok(entries)
173}
174
175/// The `MAMA8` section directory as `(kind, length)` pairs, or empty when the
176/// file carries no footer (tiles-only archive).
177fn read_sidecar_dir<R: RangeReader>(reader: &R, file_len: u64) -> Result<Vec<(u8, u64)>> {
178 if file_len < ARCHIVE_FOOTER_LEN as u64 {
179 return Ok(Vec::new());
180 }
181 let foot = reader.read(file_len - ARCHIVE_FOOTER_LEN as u64, ARCHIVE_FOOTER_LEN as u32)?;
182 if foot.len() != ARCHIVE_FOOTER_LEN || foot[0..8] != ARCHIVE_MAGIC[..] {
183 return Ok(Vec::new());
184 }
185 let footer = ArchiveFooter::parse(&foot)?;
186 let dir = reader.read(footer.dir_offset, footer.dir_len as u32)?;
187 if dir.len() as u64 != footer.dir_len {
188 return err("a .mamaps section directory read came back short".to_string());
189 }
190 let count = u32::from_le_bytes([dir[0], dir[1], dir[2], dir[3]]) as usize;
191 if ARCHIVE_DIR_HEADER_LEN + count * ARCHIVE_ENTRY_LEN > dir.len() {
192 return err("a .mamaps section directory names more entries than it holds".to_string());
193 }
194 let mut out = Vec::with_capacity(count);
195 for i in 0..count {
196 let at = ARCHIVE_DIR_HEADER_LEN + i * ARCHIVE_ENTRY_LEN;
197 let entry = ArchiveEntry::parse(&dir[at..at + ARCHIVE_ENTRY_LEN])?;
198 out.push((entry.kind, entry.len));
199 }
200 Ok(out)
201}
202
203/// Slice `[offset, offset + len)` out of the open prefix, bounds-checked.
204fn prefix_section<'a>(prefix: &'a [u8], offset: u64, len: u64, what: &str) -> Result<&'a [u8]> {
205 let end =
206 offset.checked_add(len).ok_or_else(|| crate::proto::Error(format!("{what} overflows")))?;
207 if end > prefix.len() as u64 {
208 return err(format!(
209 "{what} ends at byte {end}, outside the {} byte prefix",
210 tilecodec::stream::OPEN_PREFIX_BYTES,
211 ));
212 }
213 Ok(&prefix[offset as usize..end as usize])
214}
215
216/// Per-zoom churn: addressed-tile counts plus the overlay's stored bytes there.
217#[derive(Debug, Default, Clone, Copy)]
218pub struct ZoomChurn {
219 /// Tiles whose body bytes differ (same tile, new bytes).
220 pub changed: u64,
221 /// Stored bytes the changed tiles' new bodies occupy (distinct bodies).
222 pub changed_bytes: u64,
223 /// Tiles only the new archive holds.
224 pub added: u64,
225 /// Stored bytes the added tiles' new bodies occupy (distinct bodies).
226 pub added_bytes: u64,
227 /// Tiles only the old archive holds (cost overlay leaf entries, not bodies).
228 pub deleted: u64,
229}
230
231/// The overlay budget answer: what an A-to-B patch-overlay would carry.
232pub struct ChurnReport {
233 /// New-archive stored bytes the overlay must ship (distinct bodies only).
234 pub overlay_bytes: u64,
235 /// Addressed tiles with different body bytes.
236 pub changed: u64,
237 /// Addressed tiles only the new archive holds.
238 pub added: u64,
239 /// Addressed tiles only the old archive holds.
240 pub deleted: u64,
241 /// Addressed tiles with identical body bytes (runs may re-split).
242 pub unchanged: u64,
243 /// Per-zoom breakdown, present zooms only.
244 pub zooms: BTreeMap<u8, ZoomChurn>,
245 /// Per-kind sidecar lengths `(kind, old_len or 0, new_len or 0)`, kind order.
246 pub sidecars: Vec<(u8, u64, u64)>,
247}
248
249/// Interval-merge two snapshots (both ascending by tile id) into a [`ChurnReport`].
250///
251/// Each entry covers `[tile_id, tile_id + run_length)`; the merge walks the
252/// overlap of the two covers. Same tile + same fingerprint = unchanged, even
253/// across run re-splits: the overlay ships bodies, not index shapes. Same
254/// tile + different fingerprint = changed. Cover on one side only =
255/// added/deleted. Overlay bytes count each distinct new body once
256/// (dedup-shared bodies ship once), attributed to the zoom of the first
257/// changed/added tile carrying it.
258///
259/// A cover spanning a zoom boundary attributes to the zoom of its first tile;
260/// ids are zoom-major so this only bites runs straddling a zoom edge.
261pub fn join(old: &Snapshot, new: &Snapshot) -> ChurnReport {
262 let mut report = ChurnReport {
263 overlay_bytes: 0,
264 changed: 0,
265 added: 0,
266 deleted: 0,
267 unchanged: 0,
268 zooms: BTreeMap::new(),
269 sidecars: join_sidecars(&old.sidecars, &new.sidecars),
270 };
271 // Distinct new bodies already counted toward the overlay, by fingerprint.
272 let mut shipped: HashSet<u64> = HashSet::new();
273 let (mut i, mut j) = (0usize, 0usize);
274 while i < old.entries.len() && j < new.entries.len() {
275 let a = &old.entries[i];
276 let b = &new.entries[j];
277 let (a0, a1) = (a.tile_id, a.tile_id + u64::from(a.run_length));
278 let (b0, b1) = (b.tile_id, b.tile_id + u64::from(b.run_length));
279 if a1 <= b0 {
280 // Old cover entirely before the new one: deleted.
281 let span = a1 - a0;
282 report.deleted += span;
283 report.zooms.entry(tile_zxy(a0).0).or_default().deleted += span;
284 i += 1;
285 } else if b1 <= a0 {
286 // New cover entirely before the old one: added.
287 let span = b1 - b0;
288 report.added += span;
289 let zoom = report.zooms.entry(tile_zxy(b0).0).or_default();
290 zoom.added += span;
291 if shipped.insert(b.hash) {
292 report.overlay_bytes += u64::from(b.length);
293 zoom.added_bytes += u64::from(b.length);
294 }
295 j += 1;
296 } else {
297 // Overlap: fingerprint decides, then advance the cover that ends first.
298 let (lo, hi) = (a0.max(b0), a1.min(b1));
299 let span = hi - lo;
300 let zoom = report.zooms.entry(tile_zxy(lo).0).or_default();
301 if a.hash == b.hash {
302 report.unchanged += span;
303 } else {
304 report.changed += span;
305 zoom.changed += span;
306 if shipped.insert(b.hash) {
307 report.overlay_bytes += u64::from(b.length);
308 zoom.changed_bytes += u64::from(b.length);
309 }
310 }
311 if a1 <= b1 {
312 i += 1;
313 }
314 if b1 <= a1 {
315 j += 1;
316 }
317 }
318 }
319 for a in &old.entries[i..] {
320 let span = u64::from(a.run_length);
321 report.deleted += span;
322 report.zooms.entry(tile_zxy(a.tile_id).0).or_default().deleted += span;
323 }
324 for b in &new.entries[j..] {
325 let span = u64::from(b.run_length);
326 report.added += span;
327 let zoom = report.zooms.entry(tile_zxy(b.tile_id).0).or_default();
328 zoom.added += span;
329 if shipped.insert(b.hash) {
330 report.overlay_bytes += u64::from(b.length);
331 zoom.added_bytes += u64::from(b.length);
332 }
333 }
334 report
335}
336
337/// Union of both sidecar kind sets with each side's length (0 when absent).
338fn join_sidecars(old: &[(u8, u64)], new: &[(u8, u64)]) -> Vec<(u8, u64, u64)> {
339 let (mut i, mut j) = (0usize, 0usize);
340 let mut out = Vec::new();
341 while i < old.len() && j < new.len() {
342 let (ko, lo) = old[i];
343 let (kn, ln) = new[j];
344 if ko == kn {
345 out.push((ko, lo, ln));
346 i += 1;
347 j += 1;
348 } else if ko < kn {
349 out.push((ko, lo, 0));
350 i += 1;
351 } else {
352 out.push((kn, 0, ln));
353 j += 1;
354 }
355 }
356 for (k, l) in &old[i..] {
357 out.push((*k, *l, 0));
358 }
359 for (k, l) in &new[j..] {
360 out.push((*k, 0, *l));
361 }
362 out
363}
364
365/// Render the report as human-readable lines, ending in a machine-readable
366/// `OVERLAY_BYTES=` line for `diff_mamaps.py --churn-budget-gb` to gate on.
367pub fn render(report: &ChurnReport) -> String {
368 let mut out = String::new();
369 out.push_str(&format!(
370 "tiles: unchanged={} changed={} added={} deleted={}\n",
371 report.unchanged, report.changed, report.added, report.deleted,
372 ));
373 out.push_str("zoom changed changed_MB added added_MB deleted\n");
374 for (z, zoom) in &report.zooms {
375 if zoom.changed == 0 && zoom.added == 0 && zoom.deleted == 0 {
376 continue;
377 }
378 out.push_str(&format!(
379 "z{z:<3} {:>7} {:>10.1} {:>6} {:>8.1} {:>7}\n",
380 zoom.changed,
381 zoom.changed_bytes as f64 / 1e6,
382 zoom.added,
383 zoom.added_bytes as f64 / 1e6,
384 zoom.deleted,
385 ));
386 }
387 out.push_str("sidecar kind: old_MB -> new_MB (delta_MB)\n");
388 for (kind, old_len, new_len) in &report.sidecars {
389 let delta = *new_len as i64 - *old_len as i64;
390 out.push_str(&format!(
391 "kind {kind:<2}: {:.1} -> {:.1} ({:+.1})\n",
392 *old_len as f64 / 1e6,
393 *new_len as f64 / 1e6,
394 delta as f64 / 1e6,
395 ));
396 }
397 out.push_str(&format!(
398 "overlay estimate: {:.3} GB of tile bodies (distinct stored bodies; index overhead not included)\n",
399 report.overlay_bytes as f64 / 1e9,
400 ));
401 out.push_str(&format!("OVERLAY_BYTES={}\n", report.overlay_bytes));
402 out
403}