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

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

churn.rs400 lines · 15.9 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 ArchiveEntry, ArchiveFooter, ARCHIVE_DIR_HEADER_LEN, ARCHIVE_ENTRY_LEN, ARCHIVE_FOOTER_LEN,
34 ARCHIVE_MAGIC,
35};
36use crate::mamaps::write::hash64;
37use crate::mamaps::{header, index};
38use crate::pmtiles::tile_zxy;
39use crate::proto::{err, Result};
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>(reader: &R, located: &[(u64, u32, u32, u64)]) -> Result<Vec<Entry>> {
148 let mut hashes: HashMap<(u64, u32), u64> = HashMap::new();
149 let mut entries = Vec::with_capacity(located.len());
150 for (tile_id, run_length, length, offset) in located {
151 let key = (*offset, *length);
152 let hash = match hashes.get(&key) {
153 Some(h) => *h,
154 None => {
155 let stored = reader.read(*offset, *length)?;
156 if stored.len() as u64 != u64::from(*length) {
157 return err(format!(
158 "body at {offset} came back short: {} of {length} bytes",
159 stored.len(),
160 ));
161 }
162 let hash = hash64(&stored);
163 hashes.insert(key, hash);
164 hash
165 }
166 };
167 entries.push(Entry { tile_id: *tile_id, run_length: *run_length, length: *length, hash });
168 }
169 Ok(entries)
170}
171
172/// The `MAMA8` section directory as `(kind, length)` pairs, or empty when the
173/// file carries no footer (tiles-only archive).
174fn read_sidecar_dir<R: RangeReader>(reader: &R, file_len: u64) -> Result<Vec<(u8, u64)>> {
175 if file_len < ARCHIVE_FOOTER_LEN as u64 {
176 return Ok(Vec::new());
177 }
178 let foot = reader.read(file_len - ARCHIVE_FOOTER_LEN as u64, ARCHIVE_FOOTER_LEN as u32)?;
179 if foot.len() != ARCHIVE_FOOTER_LEN || foot[0..8] != ARCHIVE_MAGIC[..] {
180 return Ok(Vec::new());
181 }
182 let footer = ArchiveFooter::parse(&foot)?;
183 let dir = reader.read(footer.dir_offset, footer.dir_len as u32)?;
184 if dir.len() as u64 != footer.dir_len {
185 return err("a .mamaps section directory read came back short".to_string());
186 }
187 let count = u32::from_le_bytes([dir[0], dir[1], dir[2], dir[3]]) as usize;
188 if ARCHIVE_DIR_HEADER_LEN + count * ARCHIVE_ENTRY_LEN > dir.len() {
189 return err("a .mamaps section directory names more entries than it holds".to_string());
190 }
191 let mut out = Vec::with_capacity(count);
192 for i in 0..count {
193 let at = ARCHIVE_DIR_HEADER_LEN + i * ARCHIVE_ENTRY_LEN;
194 let entry = ArchiveEntry::parse(&dir[at..at + ARCHIVE_ENTRY_LEN])?;
195 out.push((entry.kind, entry.len));
196 }
197 Ok(out)
198}
199
200/// Slice `[offset, offset + len)` out of the open prefix, bounds-checked.
201fn prefix_section<'a>(prefix: &'a [u8], offset: u64, len: u64, what: &str) -> Result<&'a [u8]> {
202 let end =
203 offset.checked_add(len).ok_or_else(|| crate::proto::Error(format!("{what} overflows")))?;
204 if end > prefix.len() as u64 {
205 return err(format!(
206 "{what} ends at byte {end}, outside the {} byte prefix",
207 tilecodec::stream::OPEN_PREFIX_BYTES,
208 ));
209 }
210 Ok(&prefix[offset as usize..end as usize])
211}
212
213/// Per-zoom churn: addressed-tile counts plus the overlay's stored bytes there.
214#[derive(Debug, Default, Clone, Copy)]
215pub struct ZoomChurn {
216 /// Tiles whose body bytes differ (same tile, new bytes).
217 pub changed: u64,
218 /// Stored bytes the changed tiles' new bodies occupy (distinct bodies).
219 pub changed_bytes: u64,
220 /// Tiles only the new archive holds.
221 pub added: u64,
222 /// Stored bytes the added tiles' new bodies occupy (distinct bodies).
223 pub added_bytes: u64,
224 /// Tiles only the old archive holds (cost overlay leaf entries, not bodies).
225 pub deleted: u64,
226}
227
228/// The overlay budget answer: what an A-to-B patch-overlay would carry.
229pub struct ChurnReport {
230 /// New-archive stored bytes the overlay must ship (distinct bodies only).
231 pub overlay_bytes: u64,
232 /// Addressed tiles with different body bytes.
233 pub changed: u64,
234 /// Addressed tiles only the new archive holds.
235 pub added: u64,
236 /// Addressed tiles only the old archive holds.
237 pub deleted: u64,
238 /// Addressed tiles with identical body bytes (runs may re-split).
239 pub unchanged: u64,
240 /// Per-zoom breakdown, present zooms only.
241 pub zooms: BTreeMap<u8, ZoomChurn>,
242 /// Per-kind sidecar lengths `(kind, old_len or 0, new_len or 0)`, kind order.
243 pub sidecars: Vec<(u8, u64, u64)>,
244}
245
246/// Interval-merge two snapshots (both ascending by tile id) into a [`ChurnReport`].
247///
248/// Each entry covers `[tile_id, tile_id + run_length)`; the merge walks the
249/// overlap of the two covers. Same tile + same fingerprint = unchanged, even
250/// across run re-splits: the overlay ships bodies, not index shapes. Same
251/// tile + different fingerprint = changed. Cover on one side only =
252/// added/deleted. Overlay bytes count each distinct new body once
253/// (dedup-shared bodies ship once), attributed to the zoom of the first
254/// changed/added tile carrying it.
255///
256/// A cover spanning a zoom boundary attributes to the zoom of its first tile;
257/// ids are zoom-major so this only bites runs straddling a zoom edge.
258pub fn join(old: &Snapshot, new: &Snapshot) -> ChurnReport {
259 let mut report = ChurnReport {
260 overlay_bytes: 0,
261 changed: 0,
262 added: 0,
263 deleted: 0,
264 unchanged: 0,
265 zooms: BTreeMap::new(),
266 sidecars: join_sidecars(&old.sidecars, &new.sidecars),
267 };
268 // Distinct new bodies already counted toward the overlay, by fingerprint.
269 let mut shipped: HashSet<u64> = HashSet::new();
270 let (mut i, mut j) = (0usize, 0usize);
271 while i < old.entries.len() && j < new.entries.len() {
272 let a = &old.entries[i];
273 let b = &new.entries[j];
274 let (a0, a1) = (a.tile_id, a.tile_id + u64::from(a.run_length));
275 let (b0, b1) = (b.tile_id, b.tile_id + u64::from(b.run_length));
276 if a1 <= b0 {
277 // Old cover entirely before the new one: deleted.
278 let span = a1 - a0;
279 report.deleted += span;
280 report.zooms.entry(tile_zxy(a0).0).or_default().deleted += span;
281 i += 1;
282 } else if b1 <= a0 {
283 // New cover entirely before the old one: added.
284 let span = b1 - b0;
285 report.added += span;
286 let zoom = report.zooms.entry(tile_zxy(b0).0).or_default();
287 zoom.added += span;
288 if shipped.insert(b.hash) {
289 report.overlay_bytes += u64::from(b.length);
290 zoom.added_bytes += u64::from(b.length);
291 }
292 j += 1;
293 } else {
294 // Overlap: fingerprint decides, then advance the cover that ends first.
295 let (lo, hi) = (a0.max(b0), a1.min(b1));
296 let span = hi - lo;
297 let zoom = report.zooms.entry(tile_zxy(lo).0).or_default();
298 if a.hash == b.hash {
299 report.unchanged += span;
300 } else {
301 report.changed += span;
302 zoom.changed += span;
303 if shipped.insert(b.hash) {
304 report.overlay_bytes += u64::from(b.length);
305 zoom.changed_bytes += u64::from(b.length);
306 }
307 }
308 if a1 <= b1 {
309 i += 1;
310 }
311 if b1 <= a1 {
312 j += 1;
313 }
314 }
315 }
316 for a in &old.entries[i..] {
317 let span = u64::from(a.run_length);
318 report.deleted += span;
319 report.zooms.entry(tile_zxy(a.tile_id).0).or_default().deleted += span;
320 }
321 for b in &new.entries[j..] {
322 let span = u64::from(b.run_length);
323 report.added += span;
324 let zoom = report.zooms.entry(tile_zxy(b.tile_id).0).or_default();
325 zoom.added += span;
326 if shipped.insert(b.hash) {
327 report.overlay_bytes += u64::from(b.length);
328 zoom.added_bytes += u64::from(b.length);
329 }
330 }
331 report
332}
333
334/// Union of both sidecar kind sets with each side's length (0 when absent).
335fn join_sidecars(old: &[(u8, u64)], new: &[(u8, u64)]) -> Vec<(u8, u64, u64)> {
336 let (mut i, mut j) = (0usize, 0usize);
337 let mut out = Vec::new();
338 while i < old.len() && j < new.len() {
339 let (ko, lo) = old[i];
340 let (kn, ln) = new[j];
341 if ko == kn {
342 out.push((ko, lo, ln));
343 i += 1;
344 j += 1;
345 } else if ko < kn {
346 out.push((ko, lo, 0));
347 i += 1;
348 } else {
349 out.push((kn, 0, ln));
350 j += 1;
351 }
352 }
353 for (k, l) in &old[i..] {
354 out.push((*k, *l, 0));
355 }
356 for (k, l) in &new[j..] {
357 out.push((*k, 0, *l));
358 }
359 out
360}
361
362/// Render the report as human-readable lines, ending in a machine-readable
363/// `OVERLAY_BYTES=` line for `diff_mamaps.py --churn-budget-gb` to gate on.
364pub fn render(report: &ChurnReport) -> String {
365 let mut out = String::new();
366 out.push_str(&format!(
367 "tiles: unchanged={} changed={} added={} deleted={}\n",
368 report.unchanged, report.changed, report.added, report.deleted,
369 ));
370 out.push_str("zoom changed changed_MB added added_MB deleted\n");
371 for (z, zoom) in &report.zooms {
372 if zoom.changed == 0 && zoom.added == 0 && zoom.deleted == 0 {
373 continue;
374 }
375 out.push_str(&format!(
376 "z{z:<3} {:>7} {:>10.1} {:>6} {:>8.1} {:>7}\n",
377 zoom.changed,
378 zoom.changed_bytes as f64 / 1e6,
379 zoom.added,
380 zoom.added_bytes as f64 / 1e6,
381 zoom.deleted,
382 ));
383 }
384 out.push_str("sidecar kind: old_MB -> new_MB (delta_MB)\n");
385 for (kind, old_len, new_len) in &report.sidecars {
386 let delta = *new_len as i64 - *old_len as i64;
387 out.push_str(&format!(
388 "kind {kind:<2}: {:.1} -> {:.1} ({:+.1})\n",
389 *old_len as f64 / 1e6,
390 *new_len as f64 / 1e6,
391 delta as f64 / 1e6,
392 ));
393 }
394 out.push_str(&format!(
395 "overlay estimate: {:.3} GB of tile bodies (distinct stored bodies; index overhead not included)\n",
396 report.overlay_bytes as f64 / 1e9,
397 ));
398 out.push_str(&format!("OVERLAY_BYTES={}\n", report.overlay_bytes));
399 out
400}