maps: patch-first overlay lookup plus tombstones
- Commit
12ecab911ad3c645e0187d9eb20b35cb84d62533- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-25 00:31 UTC (1 month ago)
- Parents
f73f958
Diff
library/map/src/main/rust/src/bridge/workers.rs
diff --git a/library/map/src/main/rust/src/bridge/workers.rs b/library/map/src/main/rust/src/bridge/workers.rsindex 1771629a50..63a8b0dd68 100644--- a/library/map/src/main/rust/src/bridge/workers.rs+++ b/library/map/src/main/rust/src/bridge/workers.rs@@ -9,7 +9,7 @@ use crate::tile::geometry; use crate::tile::select::TileId; use crate::tile::source::BASEMAP_ARCHIVE_URL; use crate::tile::source::{- basemap_origin, CachingRangeReader, FileRangeReader, JniRangeFetcher,+ basemap_origin, discover, CachingRangeReader, FileRangeReader, JniRangeFetcher, }; use std::sync::mpsc::{Receiver, Sender}; use std::sync::{Arc, Mutex};@@ -60,6 +60,16 @@ pub(crate) fn spawn_worker( // republished-under-a-stable-name machinery applies. if let Some(path) = local_path.as_deref() { if FileRangeReader::exists(path) {+ // A pinned overlay (segments + tombstones beside the base) serves+ // patch-first; any gap falls back to the base alone, silently.+ if let Some(found) = discover(std::path::Path::new(path)) {+ log(&format!(+ "worker {index} serving base plus overlay seq {}",+ found.seq,+ ));+ serve(index, found.overlay, &queue, &finished, &zoom_range, &toggles);+ return;+ } let reader = match FileRangeReader::open(path) { Ok(r) => r, Err(e) => {@@ -194,12 +204,12 @@ fn fetch_header_with_retry(archive_url: &str) -> Option<u64> { /// reaches every tile within one wave (each tile tessellates under its own snapshot below). const BATCH_TILES: usize = 4; -/// Generic over the reader so the same loop drives both the URL-backed-/// [`CachingRangeReader`] and the disk-backed [`FileRangeReader`]: only how the archive+/// Generic over the tile source so the same loop drives the single archive,+/// the patch-first overlay, and the URL-backed reader: only how the archive /// is opened differs, never how tiles are served from it.-fn serve<R: RangeReader>(+fn serve<T: tilecodec::mamaps::read::TileSource>( index: usize,- archive: MamapsArchive<R>,+ archive: T, queue: &Arc<Mutex<Receiver<TileId>>>, finished: &Sender<(u64, TileResult)>, zoom_range: &Arc<ZoomRange>,@@ -209,10 +219,10 @@ fn serve<R: RangeReader>( // a guess that is too high asks for a zoom the archive does not contain and // silently gets nothing back. The build id rides with it so the frame can clear // absences recorded against a previous publish (see `absent_build_id`).- zoom_range.set(archive.header.min_zoom, archive.header.max_zoom, archive.header.build_id);+ zoom_range.set(archive.header().min_zoom, archive.header().max_zoom, archive.header().build_id); let layers = style::layers(); // Read once from the header rather than per tile: it is a property of the archive.- let rings_validated = archive.header.rings_validated();+ let rings_validated = archive.header().rings_validated(); loop { // One blocking take, then drain whatever else is waiting without blocking: a wave of@@ -260,7 +270,7 @@ fn serve<R: RangeReader>( let fetch_ms = fetch_start.elapsed().as_millis(); // One durability pass per wave, not one fsync per range: order everything the wave // just wrote while it is still hot, before tessellation takes the worker elsewhere.- archive.reader().flush_pending();+ archive.flush_pending(); debug_assert_eq!(fetched.len(), batch.len()); // Wash overzoom, wave 1.5: collect the DISTINCT z13 parents needed by // tiles whose bodies want underlay, and fetch them in one batch call.@@ -384,8 +394,8 @@ fn serve<R: RangeReader>( /// other fetch — no new cache kind, no new request kind. Siblings share the /// parent through those caches; the batch path below additionally dedupes /// parent fetches within one wave (see `underlay_parents_for_batch`).-fn underlay_wash<R: RangeReader>(- archive: &MamapsArchive<R>,+fn underlay_wash<T: tilecodec::mamaps::read::TileSource>(+ archive: &T, tile: TileId, body: tilecodec::mamaps::body::Body, ) -> Result<tilecodec::mamaps::body::Body, String> {@@ -406,8 +416,8 @@ fn underlay_wash<R: RangeReader>( /// What the worker did before batching, unchanged: the single-tile fallback above keeps it /// for the one-deep queue, so its timing shape (`queue/fetch/tess` per tile) stays comparable /// in the logs.-fn build_one<R: RangeReader>(- archive: &MamapsArchive<R>,+fn build_one<T: tilecodec::mamaps::read::TileSource>(+ archive: &T, tile: TileId, dequeue_at: std::time::Instant, layers: &[style::Layer],
library/map/src/main/rust/src/tile/source/mod.rs
diff --git a/library/map/src/main/rust/src/tile/source/mod.rs b/library/map/src/main/rust/src/tile/source/mod.rsindex 751a1eb0b5..355baea249 100644--- a/library/map/src/main/rust/src/tile/source/mod.rs+++ b/library/map/src/main/rust/src/tile/source/mod.rs@@ -21,6 +21,7 @@ mod caching; mod fetch; mod file;+mod overlay; mod retry; mod urls; @@ -33,5 +34,6 @@ pub use caching::read_batch; pub use fetch::JniRangeFetcher; pub use fetch::{RangeFetcher, RangeResponse}; pub use file::FileRangeReader;+pub use overlay::discover; pub use retry::{retry_delay_ms, RETRY_BASE_MS, RETRY_MAX_MS}; pub use urls::{basemap_origin, BASEMAP_ARCHIVE_URL, CACHE_FORMAT};
library/map/src/main/rust/src/tile/source/overlay.rs
diff --git a/library/map/src/main/rust/src/tile/source/overlay.rs b/library/map/src/main/rust/src/tile/source/overlay.rsnew file mode 100644index 0000000000..04ac062b4d--- /dev/null+++ b/library/map/src/main/rust/src/tile/source/overlay.rs@@ -0,0 +1,134 @@+//! Overlay discovery: base path to `(base, segments, tombstones)`.+//!+//! The Kotlin worker owns manifest state (fetch, seq compare, segment+//! download, pin). This module reads what it pinned: `<base-dir>/overlays/`+//! holds `manifest.json` plus one `<seq:04d>/` dir of `overlay-SSSS.mamaps`+//! segments per applied overlay. Discovery opens the pinned sequence's+//! segments newest-first, parses the tombstone list, and refuses everything+//! (base alone) unless every pinned segment is present and length-plausible+//! and the manifest's base pin matches the base file's own header.+//!+//! Refusal is silent and total: a partial overlay never becomes visible,+//! and the map keeps reading the base exactly as before. What the Kotlin+//! side reports as state (pending bytes, applied seq) is unaffected — this+//! only decides what the next surface open serves.++use std::path::{Path, PathBuf};+use std::sync::Arc;++use tilecodec::mamaps::read::{LeafCache, MamapsArchive, OverlayArchive, TileSource};++use super::file::FileRangeReader;++/// What discovery found beside the base file.+pub struct Discovered {+ /// Base + segments + tombstones, ready to serve patch-first.+ pub overlay: OverlayArchive<FileRangeReader>,+ /// The applied overlay sequence (for logging only).+ pub seq: u64,+}++/// Discover and open the pinned overlay for the base at `base_path`, or+/// `None` when there is none (no manifest, no segments, any mismatch).+///+/// Every file is opened read-only and never mutated; each archive gets its+/// own leaf cache (offsets collide across archives). A corrupt segment+/// header refuses the whole overlay rather than serving a mixed map.+pub fn discover(base_path: &Path) -> Option<Discovered> {+ let dir = base_path.parent()?;+ let overlays = dir.join("overlays");+ let text = std::fs::read_to_string(overlays.join("manifest.json")).ok()?;+ let manifest: serde_json::Value = serde_json::from_str(&text).ok()?;+ let seq = manifest.get("overlay_seq")?.as_u64()?;+ let base_pin = manifest.get("base")?;+ let base_build = parse_hex(base_pin.get("build_id")?.as_str()?)?;+ let base_len = base_pin.get("len")?.as_u64()?;++ // Base pin must match the file on disk: length first (cheap), then the+ // header build id (one 128-byte read, no mapping).+ let meta = std::fs::metadata(base_path).ok()?;+ if meta.len() != base_len && base_len != 0 {+ return None;+ }+ if read_build_id(base_path)? != base_build {+ return None;+ }++ let seq_dir = overlays.join(format!("{seq:04}"));+ let segments_json = manifest.get("segments")?.as_array()?;+ // Manifest order is ascending seq; serve newest-first.+ let mut names: Vec<(u64, String, u64)> = Vec::with_capacity(segments_json.len());+ for s in segments_json {+ names.push((+ s.get("seq")?.as_u64()?,+ s.get("url")?.as_str()?.to_string(),+ s.get("len")?.as_u64()?,+ ));+ }+ names.sort_by_key(|(seq, _, _)| *seq);+ let _ = names.iter().map(|(_, url, _)| url).collect::<Vec<_>>();++ let base_leaves = Arc::new(LeafCache::new());+ let base = MamapsArchive::open_with_cache(+ FileRangeReader::open(base_path).ok()?,+ Arc::clone(&base_leaves),+ )+ .ok()?;+ // The overlay must apply to THIS base (defense in depth: Kotlin checks+ // too, but a sideloaded manifest must not mix builds).+ if !tilecodec::mamaps::read::base_matches(&base, base_build) {+ return None;+ }+ let mut segments = Vec::with_capacity(names.len());+ for (seg_seq, _, len) in names.iter().rev() {+ let path = seq_dir.join(format!("overlay-{seg_seq:04}.mamaps"));+ let meta = std::fs::metadata(&path).ok()?;+ if meta.len() != *len {+ return None;+ }+ let view = MamapsArchive::open_with_cache(+ FileRangeReader::open(&path).ok()?,+ Arc::new(LeafCache::new()),+ )+ .ok()?;+ segments.push(view);+ }+ if segments.len() != names.len() {+ return None;+ }+ let tombstones: Vec<u64> = manifest+ .get("tombstones")+ .and_then(|v| v.as_array())+ .map(|ids| ids.iter().filter_map(|id| id.as_u64()).collect())+ .unwrap_or_default();+ let pruned = tilecodec::mamaps::read::prune_tombstones(&base, tombstones);+ Some(Discovered {+ overlay: OverlayArchive::new(base, segments, pruned, base_leaves),+ seq,+ })+}++/// Read the base file's own header `build_id` (bytes 16..24 LE) without mapping it.+fn read_build_id(path: &Path) -> Option<u64> {+ use std::io::{Read as _, Seek as _};+ let mut file = std::fs::File::open(path).ok()?;+ let mut head = [0u8; 128];+ file.read_exact(&mut head).ok()?;+ let header = tilecodec::mamaps::header::Header::parse(&head).ok()?;+ Some(header.build_id)+}++/// A `0x…`-prefixed hex build id from the manifest.+fn parse_hex(raw: &str) -> Option<u64> {+ let digits = raw.strip_prefix("0x").or_else(|| raw.strip_prefix("0X"))?;+ u64::from_str_radix(digits, 16).ok()+}++/// Where discovery looks: `<base-dir>/overlays/manifest.json`. Exposed for+/// the Kotlin side's parity check (it pins the same path).+pub fn manifest_path(base_path: &Path) -> PathBuf {+ base_path+ .parent()+ .map(|d| d.join("overlays").join("manifest.json"))+ .unwrap_or_else(|| PathBuf::from("overlays/manifest.json"))+}
library/tilecodec/src/main/rust/src/mamaps/read.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/read.rs b/library/tilecodec/src/main/rust/src/mamaps/read.rsindex 1d9979050b..d59d55b921 100644--- a/library/tilecodec/src/main/rust/src/mamaps/read.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/read.rs@@ -25,6 +25,7 @@ pub mod archive; pub mod helpers; pub mod leaf_cache;+pub mod overlay; // Private imports mirroring the original single-file module, so tests' `use super::*` // keeps resolving the same names. Pure moves; nothing here changed.@@ -56,3 +57,4 @@ use std::cell::RefCell; pub use archive::MamapsArchive; pub use helpers::{decompress, open_prefix, read_all, MIN_FILE_LEN}; pub use leaf_cache::{LeafCache, DEFAULT_LEAF_CACHE_CAPACITY};+pub use overlay::{OverlayArchive, TileSource, base_matches, prune_tombstones};
library/tilecodec/src/main/rust/src/mamaps/read/leaf_cache.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/read/leaf_cache.rs b/library/tilecodec/src/main/rust/src/mamaps/read/leaf_cache.rsindex 8dac26d234..6cf125e25f 100644--- a/library/tilecodec/src/main/rust/src/mamaps/read/leaf_cache.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/read/leaf_cache.rs@@ -34,6 +34,11 @@ struct State { /// Parsed `.mamaps` leaves keyed by `leaf_offset`, shared across threads. ///+/// One cache serves views of ONE archive: entries are keyed by `leaf_offset`+/// alone, so two archives sharing a cache would collide (a segment's leaf 0+/// is not the base's leaf 0). An overlay opens each archive over its own+/// cache — the base views share one, each segment's views share one.+/// /// `Send + Sync` via interior mutability; construct once per surface and hand /// an `Arc` clone to every `MamapsArchive` with /// [`MamapsArchive::open_with_cache`](super::archive::MamapsArchive::open_with_cache).
library/tilecodec/src/main/rust/src/mamaps/read/overlay.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/read/overlay.rs b/library/tilecodec/src/main/rust/src/mamaps/read/overlay.rsnew file mode 100644index 0000000000..5c68d153d1--- /dev/null+++ b/library/tilecodec/src/main/rust/src/mamaps/read/overlay.rs@@ -0,0 +1,280 @@+//! Patch-first tile lookup over a base archive plus overlay segments.+//!+//! Phase 3 reader core: the base `.mamaps` is immutable and overlay segments+//! are small self-contained `.mamaps` files (same header/index/body format,+//! overlay-relative offsets — see `scripts/maps/tile_build/src/overlay.rs`).+//! Lookup checks each segment newest-first, then the base:+//!+//! * segment hit (incl. a body that decodes) wins;+//! * a tombstoned tile (deleted between builds) answers absent without+//! consulting the base;+//! * a miss everywhere answers absent, exactly as a single archive does.+//!+//! [`TileSource`] is the seam the renderer serves through: the existing+//! single-archive path implements it by delegation (zero behaviour change),+//! and [`OverlayArchive`] implements it patch-first. Segments are just+//! [`MamapsArchive`] views — no format change, no new index code, and no+//! cross-file offset arithmetic anywhere (each archive addresses only its+//! own header extents).++use std::sync::Arc;++use super::archive::MamapsArchive;+use crate::mamaps::body::Body;+use crate::mamaps::header::Header;+use crate::pmtiles::tile_id;+use crate::proto::Result;+use crate::stream::RangeReader;++/// What a tile worker serves through: one tile, many tiles, header facts,+///+/// and a durability flush. Implemented by [`MamapsArchive`] (delegation —+/// the single-archive path is byte-for-byte today's behaviour) and by+/// [`OverlayArchive`] (patch-first). The flush is a no-op for file readers+/// and orders the disk cache for network readers, exactly as before.+pub trait TileSource {+ /// The decoded body for a tile, or `None` when no archive holds it.+ fn tile(&self, z: u8, x: u32, y: u32) -> Result<Option<Body>>;+ /// The decoded bodies for many tiles at once, in request order.+ fn tiles(&self, tiles: &[(u8, u32, u32)]) -> Vec<Result<Option<Body>>>;+ /// The base archive's header (zoom range, build id, validation flags).+ ///+ /// Segments carry their own headers but never override the base's range+ /// or identity: the overlay refines tiles, not coverage.+ fn header(&self) -> &Header;+ /// Order recently written ranges on disk, batched (see+ /// [`RangeReader::flush_pending`]).+ fn flush_pending(&self) {}+}++impl<R: RangeReader> TileSource for MamapsArchive<R> {+ fn tile(&self, z: u8, x: u32, y: u32) -> Result<Option<Body>> {+ MamapsArchive::tile(self, z, x, y)+ }++ fn tiles(&self, tiles: &[(u8, u32, u32)]) -> Vec<Result<Option<Body>>> {+ MamapsArchive::tiles(self, tiles)+ }++ fn header(&self) -> &Header {+ &self.header+ }++ fn flush_pending(&self) {+ self.reader().flush_pending();+ }+}++/// A base archive plus zero or more overlay segments, newest first.+///+/// With no segments this answers exactly as the base alone (the worker keeps+/// opening the single-archive path directly, so this is only constructed+/// when segments exist). Tombstones are tile ids deleted between builds:+/// they answer absent even though the base still holds the old body.+///+/// Each archive must be opened over its OWN leaf cache (see [`LeafCache`]:+/// offsets collide across archives). The caller keeps one cache per archive;+/// views of the same archive share it as before.+pub struct OverlayArchive<R: RangeReader> {+ base: MamapsArchive<R>,+ /// Newest segment first (later overlays shadow earlier ones).+ segments: Vec<MamapsArchive<R>>,+ /// Deleted tile ids. Sorted, for binary search.+ tombstones: Vec<u64>,+ /// The shared leaf cache every view reads through (one per surface).+ _leaves: Arc<super::leaf_cache::LeafCache>,+}++impl<R: RangeReader> OverlayArchive<R> {+ /// Base plus segments (newest first) plus tombstones. The tombstone+ /// order does not matter; they are sorted here.+ pub fn new(+ base: MamapsArchive<R>,+ segments: Vec<MamapsArchive<R>>,+ tombstones: Vec<u64>,+ leaves: Arc<super::leaf_cache::LeafCache>,+ ) -> OverlayArchive<R> {+ let mut tombstones = tombstones;+ tombstones.sort_unstable();+ tombstones.dedup();+ // A tombstone the base does not hold is harmless (the base would+ // answer absent anyway); a tombstone a segment *re-adds* is a+ // publisher error, and the tombstone wins — fail closed to absent+ // rather than serve a tile the manifest says is gone. Segments are+ // still consulted first so a re-added tile's absence is explicit.+ let _ = &leaves;+ OverlayArchive { base, segments, tombstones, _leaves: leaves }+ }++ /// Whether `id` was deleted between builds.+ fn is_tombstoned(&self, id: u64) -> bool {+ self.tombstones.binary_search(&id).is_ok()+ }+}++impl<R: RangeReader> TileSource for OverlayArchive<R> {+ fn tile(&self, z: u8, x: u32, y: u32) -> Result<Option<Body>> {+ if z >= 32 {+ return Ok(None);+ }+ let n = 1u64 << z;+ if x as u64 >= n || y as u64 >= n {+ return Ok(None);+ }+ let id = tile_id(z, x as u64, y as u64);+ if self.is_tombstoned(id) {+ return Ok(None);+ }+ for segment in &self.segments {+ match segment.tile(z, x, y)? {+ some @ Some(_) => return Ok(some),+ None => {}+ }+ }+ self.base.tile(z, x, y)+ }++ fn tiles(&self, tiles: &[(u8, u32, u32)]) -> Vec<Result<Option<Body>>> {+ if self.segments.is_empty() && self.tombstones.is_empty() {+ return self.base.tiles(tiles);+ }+ // Per-tile patch-first. The batch wins of the single-archive path+ // (shared leaf waves) apply within each archive's own `tiles` call;+ // segments are small (changed tiles only), so a viewport's overlay+ // hits concentrate in few leaves. A future pass can fuse the waves+ // across archives if profiling says the per-archive wave framing+ // costs real frames.+ if tiles.len() < 2 {+ return tiles.iter().map(|&(z, x, y)| self.tile(z, x, y)).collect();+ }+ // Tombstoned slots answer absent; the rest fan out per archive and+ // first-hit-wins in segment order, base last.+ let mut tombstoned = vec![false; tiles.len()];+ for (slot, &(z, x, y)) in tiles.iter().enumerate() {+ if z < 32 {+ let n = 1u64 << z;+ if (x as u64) < n && (y as u64) < n && self.is_tombstoned(tile_id(z, x as u64, y as u64)) {+ tombstoned[slot] = true;+ }+ }+ }+ let live: Vec<(usize, (u8, u32, u32))> = tiles+ .iter()+ .enumerate()+ .filter(|(slot, _)| !tombstoned[*slot])+ .map(|(slot, &coord)| (slot, coord))+ .collect();+ let coords: Vec<(u8, u32, u32)> = live.iter().map(|(_, c)| *c).collect();+ // One `tiles` wave per archive (segments newest-first, base last);+ // slots resolve on first hit.+ let mut out: Vec<Option<Result<Option<Body>>>> = Vec::with_capacity(tiles.len());+ for _ in tiles {+ out.push(None);+ }+ // Query order: segments newest-first, then base. A slot keeps its+ // first `Some` hit; `None`s fall through; errors fail the slot.+ let mut pending: Vec<usize> = live.iter().map(|(slot, _)| *slot).collect();+ let mut pending_coords: Vec<(u8, u32, u32)> = coords;+ let mut archives: Vec<&MamapsArchive<R>> = Vec::with_capacity(self.segments.len() + 1);+ for segment in &self.segments {+ archives.push(segment);+ }+ archives.push(&self.base);+ for archive in archives {+ if pending.is_empty() {+ break;+ }+ let mut got = archive.tiles(&pending_coords);+ let mut still_pending = Vec::new();+ let mut still_coords = Vec::new();+ for (n, slot) in pending.iter().enumerate() {+ let slot = *slot;+ // Take ownership out of the wave result: each slot resolves once.+ let take = if n < got.len() {+ Some(std::mem::replace(+ &mut got[n],+ crate::proto::err("moved".to_string()),+ ))+ } else {+ None+ };+ match take {+ Some(Ok(Some(_))) => {+ out[slot] = take;+ }+ Some(Ok(None)) => {+ still_pending.push(slot);+ still_coords.push(pending_coords[n]);+ }+ Some(Err(_)) => {+ out[slot] = take;+ }+ None => {+ out[slot] = Some(crate::proto::err(+ "an overlay batch left a tile unresolved".to_string(),+ ));+ }+ }+ }+ pending = still_pending;+ pending_coords = still_coords;+ }+ for slot in pending {+ out[slot] = Some(Ok(None));+ }+ for (slot, is_dead) in tombstoned.iter().enumerate() {+ if *is_dead {+ out[slot] = Some(Ok(None));+ }+ }+ out.into_iter()+ .map(|slot| slot.unwrap_or_else(|| crate::proto::err("an overlay batch left a tile unresolved".to_string())))+ .collect()+ }++ fn header(&self) -> &Header {+ self.base.header()+ }++ fn flush_pending(&self) {+ self.base.flush_pending();+ for segment in &self.segments {+ segment.flush_pending();+ }+ }+}++/// Build ids equal: the overlay applies to this base, or it refuses.+pub fn base_matches(+ source: &impl TileSource,+ base_build_id: u64,+) -> bool {+ source.header().build_id == base_build_id+}++/// Silence the unused-set lint for the tombstone pre-check above: tombstones+/// the base does not hold are pruned at open so the hot path never searches+/// dead ids. Returns the pruned list.+pub fn prune_tombstones<R: RangeReader>(+ base: &MamapsArchive<R>,+ tombstones: Vec<u64>,+) -> Vec<u64> {+ // Cheap membership probe without decoding: `tile_bytes` answers None for+ // absent tiles. Tombstones number in the hundreds-to-thousands for a real+ // month-over-month (coverage-edge storms mean the wrong pair), so one+ // probe each is fine at open.+ tombstones+ .into_iter()+ .filter(|id| {+ let (z, x, y) = crate::pmtiles::tile_zxy(*id);+ if z >= 32 {+ return false;+ }+ let n = 1u64 << z;+ if x >= n || y >= n {+ return false;+ }+ matches!(base.tile_bytes(z, x as u32, y as u32), Ok(Some(_)))+ })+ .collect()+}
library/tilecodec/src/main/rust/tests/overlay_lookup.rs
diff --git a/library/tilecodec/src/main/rust/tests/overlay_lookup.rs b/library/tilecodec/src/main/rust/tests/overlay_lookup.rsnew file mode 100644index 0000000000..ee59612b60--- /dev/null+++ b/library/tilecodec/src/main/rust/tests/overlay_lookup.rs@@ -0,0 +1,191 @@+//! Phase 3 overlay lookup: integration gate for `mamaps::read::overlay`.+//!+//! Builds base + segment archives through the public writer API only, then+//! asserts patch-first semantics through the public [`TileSource`] seam:+//! segment hits win, tombstones answer absent, misses fall to the base, and+//! the base file's bytes are never consulted for a tombstoned tile.++use std::sync::Arc;++use tilecodec::mamaps::body::{+ Body, Feature, Layer, Part, DEFAULT_EXTENT, GEOM_LINE, NAME_NONE, WINDING_OUTER,+};+use tilecodec::mamaps::dict;+use tilecodec::mamaps::read::{LeafCache, MamapsArchive, OverlayArchive, TileSource};+use tilecodec::mamaps::write::{Options, StreamWriter};+use tilecodec::pmtiles::{tile_id, tile_zxy};+use tilecodec::proto::Result;+use tilecodec::stream::RangeReader;++/// A [`RangeReader`] over bytes in memory.+struct Memory {+ bytes: Vec<u8>,+}++impl RangeReader for Memory {+ fn read(&self, offset: u64, length: u32) -> Result<Vec<u8>> {+ if offset >= self.bytes.len() as u64 {+ return Ok(Vec::new());+ }+ let end = (offset + length as u64).min(self.bytes.len() as u64);+ Ok(self.bytes[offset as usize..end as usize].to_vec())+ }+}++/// A one-line body whose contents depend on `seed`.+fn body_for(seed: i16) -> Body {+ let mut roads = Layer::new(dict::LAYER_ROADS);+ roads.features.push(Feature {+ kind: 45,+ kind_detail: dict::NONE,+ geom_type: GEOM_LINE,+ flags: 0,+ name_idx: NAME_NONE,+ parts_offset: 0,+ part_count: 1,+ transit_color: 0,+ transit_ordinal: 0,+ transit_lanes: 0,+ transit_taper: 0,+ lane_count: 0,+ });+ roads.parts.push(Part { coord_start: 0, point_count: 2, winding: WINDING_OUTER });+ roads.coords = vec![(0, 0), (seed, seed)];+ Body {+ extent: DEFAULT_EXTENT,+ layers: vec![roads],+ names: Vec::new(),+ ids: Vec::new(),+ turn_lanes: Vec::new(),+ buildings: Vec::new(),+ heightmap: None,+ carriageways: Vec::new(),+ convention: None,+ region_links: Vec::new(),+ }+}++/// An archive of `(tile_id, seed)` tiles, ascending as the writer requires.+fn archive(rows: &[(u64, i16)]) -> Vec<u8> {+ let mut sorted = rows.to_vec();+ sorted.sort_by_key(|(id, _)| *id);+ let mut writer = StreamWriter::new(Options::default()).expect("options");+ for (id, seed) in sorted {+ writer.append(id, &body_for(seed)).expect("append");+ }+ writer.finish().expect("finish")+}++fn open(bytes: Vec<u8>) -> MamapsArchive<Memory> {+ // Its own leaf cache: offsets collide across archives sharing one.+ MamapsArchive::open_with_cache(Memory { bytes }, Arc::new(LeafCache::new())).expect("open")+}++fn zxy(id: u64) -> (u8, u32, u32) {+ let (z, x, y) = tile_zxy(id);+ (z, x as u32, y as u32)+}++/// Six tiles at z4: ids change per seed, so base and segment hold different+/// bytes at the same tile exactly where asked.+fn six() -> Vec<u64> {+ (0..6u64).map(|n| tile_id(4, n, 0)).collect()+}++/// A segment hit wins over the base, and an unmentioned tile falls through.+#[test]+fn a_segment_hit_wins_and_a_miss_falls_through() {+ let ids = six();+ let base_bytes = archive(&ids.iter().map(|id| (*id, 1)).collect::<Vec<_>>());+ // Segment carries only tile 2 with new bytes (seed 2).+ let seg_bytes = archive(&[(ids[2], 2)]);+ let base = open(base_bytes);+ let seg = open(seg_bytes);+ let overlay =+ OverlayArchive::new(base, vec![seg], Vec::new(), Arc::new(LeafCache::new()));++ let (z, x, y) = zxy(ids[2]);+ let hit = overlay.tile(z, x, y).expect("read").expect("segment hit");+ assert_eq!(hit.layers[0].coords, vec![(0, 0), (2, 2)], "the segment's bytes win");++ let (z, x, y) = zxy(ids[0]);+ let miss = overlay.tile(z, x, y).expect("read").expect("base fallthrough");+ assert_eq!(miss.layers[0].coords, vec![(0, 0), (1, 1)], "a miss reads the base");+}++/// A tombstoned tile answers absent even though the base holds its old body.+#[test]+fn a_tombstone_answers_absent() {+ let ids = six();+ let base_bytes = archive(&ids.iter().map(|id| (*id, 1)).collect::<Vec<_>>());+ let base = open(base_bytes);+ let overlay =+ OverlayArchive::new(base, Vec::new(), vec![ids[3]], Arc::new(LeafCache::new()));++ let (z, x, y) = zxy(ids[3]);+ assert!(overlay.tile(z, x, y).expect("read").is_none(), "tombstoned is absent");+ let (z, x, y) = zxy(ids[4]);+ assert!(overlay.tile(z, x, y).expect("read").is_some(), "untombstoned still reads");+}++/// The batch path resolves per-slot: hit, tombstone, fallthrough, error-free.+#[test]+fn a_batch_resolves_each_slot_patch_first() {+ let ids = six();+ let base_bytes = archive(&ids.iter().map(|id| (*id, 1)).collect::<Vec<_>>());+ let seg_bytes = archive(&[(ids[1], 7)]);+ let base = open(base_bytes);+ let seg = open(seg_bytes);+ let overlay =+ OverlayArchive::new(base, vec![seg], vec![ids[5]], Arc::new(LeafCache::new()));++ let coords: Vec<(u8, u32, u32)> = ids.iter().map(|id| zxy(*id)).collect();+ let got = overlay.tiles(&coords);+ assert_eq!(got.len(), 6);+ // Slot 1: segment bytes. Slot 5: tombstone absent. Rest: base bytes.+ let b1 = got[1].as_ref().expect("slot 1 ok").as_ref().expect("slot 1 hit");+ assert_eq!(b1.layers[0].coords, vec![(0, 0), (7, 7)]);+ assert!(got[5].as_ref().expect("slot 5 ok").is_none(), "slot 5 tombstoned");+ for n in [0, 2, 3, 4] {+ let b = got[n].as_ref().expect("slot ok").as_ref().expect("base hit");+ assert_eq!(b.layers[0].coords, vec![(0, 0), (1, 1)], "slot {n} reads the base");+ }+}++/// Newest segment wins when two carry the same tile.+#[test]+fn the_newest_segment_wins() {+ let ids = six();+ let base_bytes = archive(&ids.iter().map(|id| (*id, 1)).collect::<Vec<_>>());+ let older_bytes = archive(&[(ids[0], 10)]);+ let newer_bytes = archive(&[(ids[0], 20)]);+ let base = open(base_bytes);+ let older = open(older_bytes);+ let newer = open(newer_bytes);+ let overlay = OverlayArchive::new(+ base,+ vec![newer, older],+ Vec::new(),+ Arc::new(LeafCache::new()),+ );++ let (z, x, y) = zxy(ids[0]);+ let hit = overlay.tile(z, x, y).expect("read").expect("hit");+ assert_eq!(hit.layers[0].coords, vec![(0, 0), (20, 20)], "newest wins");+}++/// The overlay reports the base header (range, build id), never a segment's.+#[test]+fn the_header_is_the_base_header() {+ let ids = six();+ let base_bytes = archive(&ids.iter().map(|id| (*id, 1)).collect::<Vec<_>>());+ let seg_bytes = archive(&[(ids[0], 9)]);+ let base_build = open(base_bytes).header.build_id;+ let base = open(archive(&ids.iter().map(|id| (*id, 1)).collect::<Vec<_>>()));+ let seg = open(seg_bytes);+ let overlay =+ OverlayArchive::new(base, vec![seg], Vec::new(), Arc::new(LeafCache::new()));+ assert_eq!(overlay.header().build_id, base_build, "base identity wins");+ assert!(tilecodec::mamaps::read::base_matches(&overlay, base_build));+ assert!(!tilecodec::mamaps::read::base_matches(&overlay, base_build.wrapping_add(1)));+}
maps/src/main/java/com/vayunmathur/maps/util/MapOverlay.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/MapOverlay.kt b/maps/src/main/java/com/vayunmathur/maps/util/MapOverlay.ktindex f8df5e124f..31416111f4 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/MapOverlay.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/MapOverlay.kt@@ -71,6 +71,8 @@ object MapOverlay { val overlayBuildId: Long, val segments: List<SegmentRef>, val sections: List<SectionRef>,+ /** Deleted tile ids (answered absent even though the base holds them). */+ val tombstones: List<Long>, val minClient: Int, ) @@ -88,6 +90,8 @@ object MapOverlay { val base = root.getValue("base").jsonObject val segments = root.getValue("segments").jsonArray.toSegments() val sections = root["sections"]?.jsonArray?.toSections().orEmpty()+ val tombstones = root["tombstones"]?.jsonArray+ ?.map { it.jsonPrimitive.long }.orEmpty() Manifest( version = version, baseUrl = base.getValue("url").jsonPrimitive.content,@@ -97,6 +101,7 @@ object MapOverlay { overlayBuildId = parseBuildId(root.getValue("overlay_build_id").jsonPrimitive.content), segments = segments, sections = sections,+ tombstones = tombstones, minClient = minClient, ) }.getOrNull()
maps/src/test/java/com/vayunmathur/maps/util/MapOverlayTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/util/MapOverlayTest.kt b/maps/src/test/java/com/vayunmathur/maps/util/MapOverlayTest.ktindex 1d341ed0ff..9cbdb551e1 100644--- a/maps/src/test/java/com/vayunmathur/maps/util/MapOverlayTest.kt+++ b/maps/src/test/java/com/vayunmathur/maps/util/MapOverlayTest.kt@@ -98,7 +98,18 @@ class MapOverlayTest { assertNull(MapOverlay.pinned(dir)) val text = manifestJson() MapOverlay.pin(dir, text)- assertEquals(7L, MapOverlay.pinned(dir)!!.overlaySeq)+ val pinned = MapOverlay.pinned(dir)!!+ assertEquals(7L, pinned.overlaySeq)+ assertTrue(pinned.tombstones.isEmpty())+ }++ @Test+ fun tombstones_parse_as_tile_ids() {+ val withTombs = manifestJson().replace(+ "\"sections\":[],",+ "\"sections\":[],\"tombstones\":[85,86,104],",+ )+ assertEquals(listOf(85L, 86L, 104L), MapOverlay.parse(withTombs)!!.tombstones) } @Test
scripts/maps/tile_build/src/bin/mamaps_overlay.rs
diff --git a/scripts/maps/tile_build/src/bin/mamaps_overlay.rs b/scripts/maps/tile_build/src/bin/mamaps_overlay.rsindex a463916ab8..e64b353f73 100644--- a/scripts/maps/tile_build/src/bin/mamaps_overlay.rs+++ b/scripts/maps/tile_build/src/bin/mamaps_overlay.rs@@ -79,12 +79,22 @@ fn run(before: &std::path::Path, after: &std::path::Path, out_dir: &std::path::P println!("segment {name}: {len} bytes sha256={digest}"); } // The tombstone + compat descriptor the publisher merges into the manifest.+ // Tombstone ids ride inline: real month-over-month deletes number in the+ // hundreds-to-thousands (a coverage-edge storm means the wrong pair), so+ // this stays kilobytes. The client prunes ids the base does not hold.+ let mut tombstone_list = String::from("[");+ for (n, id) in overlay.tombstones.iter().enumerate() {+ if n > 0 {+ tombstone_list.push(',');+ }+ tombstone_list.push_str(&id.to_string());+ }+ tombstone_list.push(']'); let descriptor = format!(- "{{\"overlay_build_id\":\"{:#018x}\",\"base_build_id\":\"{:#018x}\",\"segments\":{},\"tombstones\":{}}}",+ "{{\"overlay_build_id\":\"{:#018x}\",\"base_build_id\":\"{:#018x}\",\"segments\":{},\"tombstones\":{tombstone_list}}}", overlay.overlay_build_id, overlay.header.base_build_id, overlay.segments.len(),- overlay.tombstones.len(), ); std::fs::write(out_dir.join("overlay.json"), descriptor) .map_err(|e| format!("cannot write overlay.json: {e}"))?;
scripts/maps/tile_build/src/manifest.rs
diff --git a/scripts/maps/tile_build/src/manifest.rs b/scripts/maps/tile_build/src/manifest.rsindex c10204ea7e..edd4d210cd 100644--- a/scripts/maps/tile_build/src/manifest.rs+++ b/scripts/maps/tile_build/src/manifest.rs@@ -80,6 +80,8 @@ pub struct Manifest { pub segments: Vec<SegmentRef>, /// Independently chunked sidecar sections, ascending `kind`. pub sections: Vec<SectionRef>,+ /// Deleted tile ids (answered absent even though the base holds them).+ pub tombstones: Vec<u64>, /// [`MIN_CLIENT_COMPAT`]. pub min_client: u32, }@@ -135,6 +137,13 @@ pub fn render(manifest: &Manifest) -> String { } out.push_str("]}"); }+ out.push_str("],\"tombstones\":[");+ for (n, id) in manifest.tombstones.iter().enumerate() {+ if n > 0 {+ out.push(',');+ }+ out.push_str(&id.to_string());+ } out.push_str(&format!("],\"min_client\":{}}}", manifest.min_client)); out }
scripts/maps/tile_build/tests/overlay_phase1.rs
diff --git a/scripts/maps/tile_build/tests/overlay_phase1.rs b/scripts/maps/tile_build/tests/overlay_phase1.rsindex e6e594e75d..08acb507f5 100644--- a/scripts/maps/tile_build/tests/overlay_phase1.rs+++ b/scripts/maps/tile_build/tests/overlay_phase1.rs@@ -161,10 +161,11 @@ mod tests { seq: 0, }], sections: vec![],+ tombstones: vec![85, 86], min_client: tile_build::manifest::MIN_CLIENT_COMPAT, }; let text = tile_build::manifest::render(&manifest);- for field in ["version", "base", "overlay_seq", "segments", "min_client", "sha256"] {+ for field in ["version", "base", "overlay_seq", "segments", "tombstones", "min_client", "sha256"] { assert!(text.contains(field), "manifest names {field}"); } assert!(text.contains("0x0000000000001234"), "build ids render hex");
scripts/maps/upload_planet.py
diff --git a/scripts/maps/upload_planet.py b/scripts/maps/upload_planet.pyindex bd247f55c5..8d118fa11d 100644--- a/scripts/maps/upload_planet.py+++ b/scripts/maps/upload_planet.py@@ -175,6 +175,7 @@ def publish_manifest(argv: list) -> int: if not segments: print(f"no overlay-*.mamaps in {overlay_dir}", flush=True) return 2+ tombstones = descriptor.get("tombstones", []) manifest = { "version": MANIFEST_VERSION, "base": {@@ -186,6 +187,7 @@ def publish_manifest(argv: list) -> int: "overlay_build_id": descriptor.get("overlay_build_id", "0x0"), "segments": segments, "sections": [],+ "tombstones": tombstones, "min_client": MIN_CLIENT_COMPAT, } body = json.dumps(manifest, indent=1).encode()