Modern Apps git

← Modern-Apps.git

library:map: render planet4 correctly; stream planet4.mamaps (#planet4)

Commit
19fe5bcbde319185558d5e09e8b8d014daa7cef1
Author
Vayun Mathur <[email protected]>
When
2026-11-11 21:09 UTC (24 days ago)
Parents
d53e339
Audit of every .mamaps structure the writer emits against the renderer
(analysis against the real 81 GB build, byte-identical to planet4): all
tile decoding already goes through the shared tilecodec decoder (no stale
copy), header v9 / v10 bodies / 10 layers / compressed leaves / heightmaps
(adaptive 9x9 and 5x5) / building, turn-lane, carriageway and region-link
tables all decode. Three real problems, fixed here:

- FLAG_RINGS_VALIDATED is not trustworthy on the published planets.
  Measured over 10 regions z6-z14: 9-11% of holed polygons at z6-z7,
  4-7% at z8-z9, ~1-2% at z10-z11 and 0.1-1% at z12-z14 have holes that
  properly cross their exterior or each other (simplification after the
  writer's validation pass). Trusting the flag fed self-intersecting
  bridged rings to earcut (slivers across forest/water washes). New
  geometry::TRUST_RINGS_VALIDATED = false keeps the repair pass on; cost
  +2-8% tessellation per tile at z12-z14, ~+25% at z8-z10, once per tile
  build. The debug-only "repair disagreed" assertion now compares hole
  sets, not hole order (the writer orders holes differently from the
  repair pass's largest-first sort, which tripped it on every city).
- Borders/region masks never loaded at z13+. The writer stops the
  boundaries layer at z12 (aa8d1d07d) but the fetch loop only asked for
  visible tiles (plus z14 wash ancestors), so a cold start at z13+ drew
  no borders and setRegionMask could never resolve. The frame now also
  fetches the covering z12 tiles while z12 is inside the ancestor window
  (BOUNDARIES_MAX_ZOOM = 12); per-layer suppression keeps their border
  draws alive under finer tiles.
- Overlay discovery gave every worker a private base LeafCache; it now
  takes the surface's shared cache (4 MiB per planet leaf, see the
  tilecodec byte budget).

URL switch: BASEMAP_ARCHIVE_URL -> https://data.maproj.org/planet4.mamaps
(weather/taxi/fooddelivery/findfamily stream it; maps reads its local
copy). The disk range cache is ONE directory whose .origin marker is
v2|url|build_id, so the first open against planet4 wipes every planet3
range rather than keeping both (pinned by a new cache test). Docs no
longer say v7/v8, "9 layers"/"12 layers" or planet3; LayerOptions.traffic
documents that the writer no longer emits a traffic layer, so the map
overlay draws nothing on planet3/planet4 (route ETAs still use live
first-party speeds). Detekt: CameraState.onGesture's globe branch moved
into onGlobeGesture (complexity), unused vp suppressed with reason.

Real-archive harness (tests/real_archive.rs, #[ignore], MAMAPS_REAL_ARCHIVE
and MAMAPS_LIVE=1 gated): header/dictionary acceptance; the section
directory carries every kind the app reads (7/elevation is absent); every
layer at z0/4/8/10/12/13/14 in SF, NYC, London, Tokyo decodes and
tessellates through geometry::build_toggled (v10 bodies only; traffic
pinned absent); DEM heightmaps sample real metres (Fuji 3697 m, Denver
~1600 m) and drape; an overlay segment over the real base is discovered
patch-first with tombstones and refused for another base; and the LIVE
planet4 header plus a cold SF z14 tile read through CachingRangeReader +
RangeCache match the local copy byte for byte.

Verified: cargo test -p map_renderer (557 lib + 7 + the real-archive
suite 6/6 against world.mamaps and the live URL), cargo clippy no errors,
:library:map detekt/lint via ./check green, Android build in the
toolchain container compiles the cdylib.

Diff

library/map/src/main/java/com/vayunmathur/library/map/CameraState.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/CameraState.kt b/library/map/src/main/java/com/vayunmathur/library/map/CameraState.ktindex 468db00831..0d1a351a4d 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/CameraState.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/CameraState.kt@@ -259,6 +259,34 @@ class CameraState(initial: CameraPosition = CameraPosition()) {      * ([globePanBy]), and the twist/tilt gestures are ignored: the globe path      * is north-up level, and tilting a planet is a separate workstream.      */+    /** [onGesture] on an active globe: pan rotates the sphere, zoom stays centroid-anchored. */+    @Suppress("LongParameterList")+    private fun onGlobeGesture(+        centroidDp: Offset,+        panDp: Offset,+        zoomChange: Float,+        minZoom: Double,+        maxZoom: Double,+        scrollEnabled: Boolean,+        zoomEnabled: Boolean,+        vp: Size,+    ) {+        var zoom = position.zoom+        var center = position.target+        if (scrollEnabled && (panDp.x != 0f || panDp.y != 0f)) {+            center = globePanBy(center, panDp, vp, position.zoom)+        }+        if (zoomEnabled && zoomChange != 1f && zoomChange > 0f) {+            val newZoom = (zoom + log2(zoomChange.toDouble())).coerceIn(minZoom, maxZoom)+            if (newZoom != zoom) {+                val zoomed = anchoredZoom(position.copy(target = center), newZoom, centroidDp, vp)+                center = zoomed.target+                zoom = zoomed.zoom+            }+        }+        position = position.copy(target = center, zoom = zoom, bearing = 0.0, pitch = 0.0)+    }+     internal fun onGesture(         centroidDp: Offset,         panDp: Offset,@@ -278,19 +306,9 @@ class CameraState(initial: CameraPosition = CameraPosition()) {         // Globe: rotate the sphere under the finger; zoom stays Mercator-anchored         // so the threshold crossing is continuous.         if (globeEnabled && position.zoom < GLOBE_DETAIL_ZOOM) {-            var center = position.target-            if (scrollEnabled && (panDp.x != 0f || panDp.y != 0f)) {-                center = globePanBy(center, panDp, vp, position.zoom)-            }-            if (zoomEnabled && zoomChange != 1f && zoomChange > 0f) {-                val newZoom = (zoom + log2(zoomChange.toDouble())).coerceIn(effectiveMinZoom, maxZoom)-                if (newZoom != zoom) {-                    val zoomed = anchoredZoom(position.copy(target = center), newZoom, centroidDp, vp)-                    center = zoomed.target-                    zoom = zoomed.zoom-                }-            }-            position = position.copy(target = center, zoom = zoom, bearing = 0.0, pitch = 0.0)+            onGlobeGesture(+                centroidDp, panDp, zoomChange, effectiveMinZoom, maxZoom, scrollEnabled, zoomEnabled, vp,+            )             return         } @@ -375,6 +393,7 @@ class CameraState(initial: CameraPosition = CameraPosition()) {  * `cos(lat)`. Longitude wraps; latitude clamps to the Mercator bound the flat path honours.  * Unused [vp]: kept so the signature matches the flat pan it replaces at the call site.  */+@Suppress("UnusedParameter") // `vp`: signature parity with the flat pan, see above. internal fun globePanBy(center: GeoPoint, panDp: Offset, vp: Size, zoom: Double): GeoPoint {     val r = globeRadius(zoom, center.latitude)     if (r <= 0.0) return center
library/map/src/main/java/com/vayunmathur/library/map/LayerOptions.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/LayerOptions.kt b/library/map/src/main/java/com/vayunmathur/library/map/LayerOptions.ktindex 422d0dcb77..b192a9b144 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/LayerOptions.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/LayerOptions.kt@@ -68,6 +68,12 @@ data class LayerOptions(      * tessellation like [poi]/[transit], so leaving it off costs nothing — only a navigation      * view wants the whole drivable network drawn a second time. A segment with no pushed      * colour draws nothing, so the basemap road shows through as the no-data look.+     *+     * **Draws nothing on planet3/planet4:** the archive writer stopped emitting `traffic`+     * features (mamaps_build "NA diet"; the layer stays in the dictionary, empty), so there is+     * no geometry to colour. Route ETAs still use live speeds from the first-party+     * `api.maproj.org/maps/traffic` feed; only this map overlay is dark until a rebuild brings+     * the layer back (the real-archive test pins its absence).      */     val traffic: Boolean = false,     /**
library/map/src/main/java/com/vayunmathur/library/map/MapNative.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/MapNative.kt b/library/map/src/main/java/com/vayunmathur/library/map/MapNative.ktindex ea50dde587..0a4e8ae5d1 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/MapNative.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/MapNative.kt@@ -44,7 +44,7 @@ internal object MapNative {      *      * [localPath] is an optional path to a `.mamaps` archive already on the device. When      * it names an existing file the renderer reads that file directly and does no-     * networking at all; `null` or empty keeps the built-in `planet3.mamaps` URL and its+     * networking at all; `null` or empty keeps the built-in `planet4.mamaps` URL and its      * range cache unchanged.      */     external fun create(
library/map/src/main/java/com/vayunmathur/library/map/MapOptions.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/MapOptions.kt b/library/map/src/main/java/com/vayunmathur/library/map/MapOptions.ktindex 0821d23dfb..764461b217 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/MapOptions.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/MapOptions.kt@@ -70,7 +70,7 @@ data class MapOptions(     val layerOptions: LayerOptions = LayerOptions(),     /**      * Where tiles come from. [TileSource.Server] (default) streams range requests for-     * `planet3.mamaps` over HTTP with a disk range cache; [TileSource.LocalFile] reads a+     * `planet4.mamaps` over HTTP with a disk range cache; [TileSource.LocalFile] reads a      * pushed `.mamaps` archive from the app's external files dir and does no networking.      * Today only `maps` pushes an archive, so every other app stays on the default.      */@@ -95,7 +95,7 @@ enum class MapBody {  * Where the renderer reads its tiles from.  */ enum class TileSource {-    /** Stream `planet3.mamaps` range requests over HTTP, cached on disk. */+    /** Stream `planet4.mamaps` range requests over HTTP, cached on disk. */     Server,     /** Read a pushed `.mamaps` archive from external files; no networking. Falls back to      * [Server] when no archive file is present, so a missing push degrades to streaming
library/map/src/main/java/com/vayunmathur/library/map/VectorMap.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/VectorMap.kt b/library/map/src/main/java/com/vayunmathur/library/map/VectorMap.ktindex 1b09dba1d1..33c62ba70a 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/VectorMap.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/VectorMap.kt@@ -47,8 +47,8 @@ internal val MapOnlineDefault: StateFlow<Boolean> = OnlineAlways /**  * The vector map.  *- * Renders the planet-scale v8 single-file `planet3.mamaps` archive- * (`data.maproj.org/planet3.mamaps`: 9 layers, 128-byte header) with our own+ * Renders the planet-scale single-file `planet4.mamaps` archive+ * (`data.maproj.org/planet4.mamaps`: v9 header, v10 bodies, 10 layers, 128-byte header) with our own  * Vulkan renderer. No third-party tile CDN and no API key, which is the whole point:  * watermarked, and that broke the basemap in five apps (#615).  *
library/map/src/main/rust/Cargo.toml
diff --git a/library/map/src/main/rust/Cargo.toml b/library/map/src/main/rust/Cargo.tomlindex 0ac0f13b2d..9387ba4c65 100644--- a/library/map/src/main/rust/Cargo.toml+++ b/library/map/src/main/rust/Cargo.toml@@ -1,8 +1,8 @@ # The Vulkan vector-tile renderer for `:library:map`. # # Replaces the CARTO raster basemap in findfamily, photos, weather, taxi and-# fooddelivery (#615) with our own renderer over the planet-scale v7-# single-file planet3.mamaps archive.+# fooddelivery (#615) with our own renderer over the planet-scale+# single-file planet4.mamaps archive (v9 header, v10 bodies, 10 layers). # # Why Vulkan and not `androidx.webgpu`: that wrapper bundles Dawn as a 5.79 MB # `libwebgpu_c_bundled.so` per ABI, to translate to the Vulkan that is already on@@ -20,7 +20,7 @@ version = "0.1.0" edition = "2021" publish = false license = "GPL-2.0-only"-description = "Vulkan vector-tile map renderer: planet3.mamaps v7 in, triangles out"+description = "Vulkan vector-tile map renderer: planet4.mamaps (v9/v10) in, triangles out"  [lib] name = "map_renderer"@@ -39,7 +39,7 @@ sha2.workspace = true serde_json.workspace = true  # The .mamaps codec, shared with `scripts/maps`, which builds the-# planet3.mamaps archive this reads. One implementation, so the two cannot drift.+# planet4.mamaps archive this reads. One implementation, so the two cannot drift. tilecodec = { path = "../../../../tilecodec/src/main/rust" }  # HTTP goes back out through Kotlin: this crate opens no sockets and carries no TLS
library/map/src/main/rust/src/bridge/frame.rs
diff --git a/library/map/src/main/rust/src/bridge/frame.rs b/library/map/src/main/rust/src/bridge/frame.rsindex 17a2c032e7..b0ac2aa76e 100644--- a/library/map/src/main/rust/src/bridge/frame.rs+++ b/library/map/src/main/rust/src/bridge/frame.rs@@ -1,7 +1,10 @@ //! One frame from a camera snapshot. //! //! Pure move out of `bridge.rs`; no logic changes.-use super::handle::{handle_mut, TileResult, RESIDENT_BYTE_BUDGET, RESIDENT_TILE_CAP, UPLOADS_PER_FRAME, WASH_MAX_ZOOM};+use super::handle::{+    handle_mut, TileResult, BOUNDARIES_MAX_ZOOM, RESIDENT_BYTE_BUDGET, RESIDENT_TILE_CAP, UPLOADS_PER_FRAME,+    WASH_MAX_ZOOM,+}; use super::log::{log, log_info}; use crate::camera::Camera; use crate::style;@@ -221,27 +224,29 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>(     // Bounded: one z14 tile covers 2^(z-14) visible tiles, so this adds at most     // a quarter of the visible count, and the existing has_tile/absent/retry     // gates dedup it exactly like a visible fetch.-    let wash_extra: Vec<select::TileId> = if fetch_zoom > WASH_MAX_ZOOM as f64 {-        let mut seen = std::collections::HashSet::new();-        let mut extra = Vec::new();-        for tile in &visible {-            if tile.z <= WASH_MAX_ZOOM {-                continue;-            }-            let shift = tile.z - WASH_MAX_ZOOM;-            let ancestor = select::TileId {-                z: WASH_MAX_ZOOM,-                x: tile.x >> shift,-                y: tile.y >> shift,-            };-            if seen.insert(ancestor.key()) {-                extra.push(ancestor);-            }-        }-        extra+    let mut wash_extra: Vec<select::TileId> = if fetch_zoom > WASH_MAX_ZOOM as f64 {+        covering_ancestors(&visible, WASH_MAX_ZOOM)     } else {         Vec::new()     };+    // Same gap one layer over: the archive's `boundaries` stop at z12 (planet3/planet4:+    // mamaps_build `schema/mod.rs`, "drop boundaries z13"), so at z13+ no visible tile+    // carries border lines or the `region_area` shapes the selection mask reads, and a cold+    // start at z13+ showed no borders and could never mask a region. Fetch the z12 covering+    // tiles too (at most 1/4 + 1/16 of the visible count); per-layer suppression keeps the+    // z12 boundary draws alive under finer tiles that carry none. Only while z12 is inside+    // the ancestor window `resident_set` keeps — past it the tile would be evicted the+    // frame after it landed.+    if fetch_zoom > BOUNDARIES_MAX_ZOOM as f64+        && fetch_zoom <= (BOUNDARIES_MAX_ZOOM + select::ANCESTOR_DEPTH) as f64+    {+        let mut seen: std::collections::HashSet<u64> = wash_extra.iter().map(|t| t.key()).collect();+        for ancestor in covering_ancestors(&visible, BOUNDARIES_MAX_ZOOM) {+            if seen.insert(ancestor.key()) {+                wash_extra.push(ancestor);+            }+        }+    }     // The wanted set for the drain-and-replace generation (issue 815): when it changes, the     // queued remainder of the previous set is stale and is drained below, so a pan does not     // wait behind fetches for tiles that scrolled out. `wash_extra` counts as wanted — it is@@ -445,3 +450,22 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_lastFrameStepT     })     .resolve::<jni::errors::LogErrorAndDefault>() }++/// The distinct `cap`-zoom ancestors of every visible tile deeper than `cap`, in first-seen+/// order: what a layer the archive stops emitting at `cap` (the z14 wash, the z12+/// boundaries) has to be fetched from when the camera is past it.+fn covering_ancestors(visible: &[select::TileId], cap: u8) -> Vec<select::TileId> {+    let mut seen = std::collections::HashSet::new();+    let mut extra = Vec::new();+    for tile in visible {+        if tile.z <= cap {+            continue;+        }+        let shift = tile.z - cap;+        let ancestor = select::TileId { z: cap, x: tile.x >> shift, y: tile.y >> shift };+        if seen.insert(ancestor.key()) {+            extra.push(ancestor);+        }+    }+    extra+}
library/map/src/main/rust/src/bridge/handle.rs
diff --git a/library/map/src/main/rust/src/bridge/handle.rs b/library/map/src/main/rust/src/bridge/handle.rsindex 238b2e2fb5..3e749c73c5 100644--- a/library/map/src/main/rust/src/bridge/handle.rs+++ b/library/map/src/main/rust/src/bridge/handle.rs@@ -120,6 +120,12 @@ pub(crate) const UPLOADS_PER_FRAME_ZOOM_OUT: usize = 16; /// the tiler's z14 is the truth and this names it. pub(crate) const WASH_MAX_ZOOM: u8 = 14; +/// The deepest zoom the `boundaries` layer (border lines + `region_area` mask shapes) tiles+/// to: the writer dropped it from z13 and z14 (mamaps_build `schema/mod.rs`, commit+/// aa8d1d07d), so a z13+ viewport reads its borders from z12 ancestors the fetch loop asks+/// for explicitly (see `frame.rs`).+pub(crate) const BOUNDARIES_MAX_ZOOM: u8 = 12;+ /// What a worker reports back about a tile. pub(crate) enum TileResult {     /// Tessellated and ready to upload.
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 63a8b0dd68..723ff90f94 100644--- a/library/map/src/main/rust/src/bridge/workers.rs+++ b/library/map/src/main/rust/src/bridge/workers.rs@@ -62,7 +62,7 @@ pub(crate) fn spawn_worker(                 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)) {+                    if let Some(found) = discover(std::path::Path::new(path), Arc::clone(&leaves)) {                         log(&format!(                             "worker {index} serving base plus overlay seq {}",                             found.seq,@@ -221,8 +221,10 @@ fn serve<T: tilecodec::mamaps::read::TileSource>(     // 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);     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();+    // Read once from the header rather than per tile: it is a property of the archive. Gated+    // by `TRUST_RINGS_VALIDATED`: the published planets set the flag without earning it.+    let rings_validated =+        archive.header().rings_validated() && geometry::TRUST_RINGS_VALIDATED;      loop {         // One blocking take, then drain whatever else is waiting without blocking: a wave of
library/map/src/main/rust/src/lib.rs
diff --git a/library/map/src/main/rust/src/lib.rs b/library/map/src/main/rust/src/lib.rsindex f1673ba3b9..4dd11b505c 100644--- a/library/map/src/main/rust/src/lib.rs+++ b/library/map/src/main/rust/src/lib.rs@@ -1,9 +1,9 @@ //! The Vulkan vector-tile map renderer behind `:library:map`. //! //! Replaces the CARTO raster basemap in findfamily, photos, weather, taxi and-//! fooddelivery (#615) with our own renderer over the planet-scale v7-//! single-file `planet3.mamaps` archive at `data.maproj.org/planet3.mamaps`-//! (12 layers, 128-byte header).+//! fooddelivery (#615) with our own renderer over the planet-scale+//! single-file `planet4.mamaps` archive at `data.maproj.org/planet4.mamaps`+//! (v9 header, v10 bodies, 10 layers, 128-byte header). //! //! # Layout //!
library/map/src/main/rust/src/style/kinds.rs
diff --git a/library/map/src/main/rust/src/style/kinds.rs b/library/map/src/main/rust/src/style/kinds.rsindex 7ed5c58389..1207539f47 100644--- a/library/map/src/main/rust/src/style/kinds.rs+++ b/library/map/src/main/rust/src/style/kinds.rs@@ -29,7 +29,7 @@ pub enum Variant { pub enum Toggle {     Poi,     Transit,-    /// The live traffic layer (`LAYER_TRAFFIC`, id 10). Gated at tessellation like the+    /// The live traffic layer (`LAYER_TRAFFIC`, id 7). Gated at tessellation like the     /// others so an archive without it — or a consumer that never enables it — pays     /// nothing; the per-segment colours arrive separately as a pushed id→ARGB table     /// (see [`crate::vulkan::renderer::Renderer::set_traffic_speeds`]).
library/map/src/main/rust/src/tess/fill/mod.rs
diff --git a/library/map/src/main/rust/src/tess/fill/mod.rs b/library/map/src/main/rust/src/tess/fill/mod.rsindex 5848462925..2f64b18106 100644--- a/library/map/src/main/rust/src/tess/fill/mod.rs+++ b/library/map/src/main/rust/src/tess/fill/mod.rs@@ -56,6 +56,19 @@ pub const FLOATS_PER_VERTEX: usize = 3; /// Coordinates below this many make a ring that encloses nothing. const MIN_RING_COORDS: usize = 6; +/// Groups with each group's holes sorted, so two groupings compare equal when they hold the+/// same exteriors with the same holes in any order. Debug-assertion support only (still+/// compiled in release: `debug_assert_eq!` type-checks its operands there).+#[cfg_attr(not(debug_assertions), allow(dead_code))]+fn canonical_groups(mut groups: Vec<Vec<usize>>) -> Vec<Vec<usize>> {+    for group in &mut groups {+        if group.len() > 2 {+            group[1..].sort_unstable();+        }+    }+    groups+}+ /// Tessellate one polygon: the exterior ring first, then holes, each flat and /// **closed** as the decoder returns them. ///@@ -102,9 +115,12 @@ pub fn tessellate(         // what `polygons` would work out anyway, at the cost of an O(holes x outers) containment         // scan per feature per frame.         let trusted = vec![(0..open.len()).collect::<Vec<usize>>()];+        // Compared up to hole order: the repair pass sorts holes largest-first, the producer+        // keeps its own order (planet-scale v10 bodies routinely differ), and earcut draws the+        // same area either way. A dropped, extra or regrouped ring still fails.         debug_assert_eq!(-            polygons(&open),-            trusted,+            canonical_groups(polygons(&open)),+            canonical_groups(trusted.clone()),             "an archive claimed validated rings and the repair pass disagreed",         );         trusted
library/map/src/main/rust/src/tile/cache/tests.rs
diff --git a/library/map/src/main/rust/src/tile/cache/tests.rs b/library/map/src/main/rust/src/tile/cache/tests.rsindex 53debe550b..d8cc9ba3f9 100644--- a/library/map/src/main/rust/src/tile/cache/tests.rs+++ b/library/map/src/main/rust/src/tile/cache/tests.rs@@ -25,8 +25,8 @@ impl Drop for Fixture {     } } -const URL: &str = "https://data.maproj.org/planet3.mamaps";-const ORIGIN: &str = "v1|https://data.maproj.org/planet3.mamaps";+const URL: &str = "https://data.maproj.org/planet4.mamaps";+const ORIGIN: &str = "v1|https://data.maproj.org/planet4.mamaps";  fn cache_with(dir: &Path, clock: Arc<AtomicU64>, max_bytes: u64) -> RangeCache {     let c = clock.clone();@@ -188,6 +188,41 @@ fn changing_the_origin_marker_drops_every_entry() {     ); } +#[test]+fn moving_from_planet3_to_planet4_wipes_the_planet3_ranges() {+    // The URL switch must not leave the old archive's ranges beside the new+    // ones: the directory is shared (not keyed per URL), and the real origin+    // marker carries the URL, so the first planet4 open drops every planet3+    // entry and the cache never holds both.+    use crate::tile::source::{basemap_origin, BASEMAP_ARCHIVE_URL};+    const PLANET3: &str = "https://data.maproj.org/planet3.mamaps";+    assert_eq!(BASEMAP_ARCHIVE_URL, URL, "the renderer reads planet4");+    let f = Fixture::new("planet3to4");+    let clock = || Box::new(|| 1_000_000u64) as Box<dyn Fn() -> u64 + Send + Sync>;+    {+        let old = RangeCache::with_clock(+            &f.dir,+            &basemap_origin(PLANET3, 0x0a90_e5e4_ab91_159e),+            DEFAULT_MAX_BYTES,+            clock(),+        );+        for i in 0..5 {+            old.write(&RangeCache::key(PLANET3, &format!("bytes={i}-{i}")), &[i as u8]);+        }+        assert_eq!(data_files(&f.dir).len(), 5);+    }+    let new = RangeCache::with_clock(+        &f.dir,+        &basemap_origin(BASEMAP_ARCHIVE_URL, 0x2ab5_ba58_33e5_4438),+        DEFAULT_MAX_BYTES,+        clock(),+    );+    assert_eq!(data_files(&f.dir).len(), 0, "planet3 ranges must be evicted on the switch");+    new.write(&RangeCache::key(BASEMAP_ARCHIVE_URL, "bytes=0-127"), &[0u8; 128]);+    assert_eq!(data_files(&f.dir).len(), 1);+    assert!(fs::read_to_string(f.dir.join(ORIGIN_FILE)).unwrap().contains("planet4.mamaps"));+}+ #[test] fn an_unchanged_origin_marker_keeps_the_cache() {     let f = Fixture::new("sameorigin");
library/map/src/main/rust/src/tile/geometry/mod.rs
diff --git a/library/map/src/main/rust/src/tile/geometry/mod.rs b/library/map/src/main/rust/src/tile/geometry/mod.rsindex 22253e2b62..f0ebd5ea53 100644--- a/library/map/src/main/rust/src/tile/geometry/mod.rs+++ b/library/map/src/main/rust/src/tile/geometry/mod.rs@@ -45,6 +45,19 @@ mod tests_extra4; mod tests_extra8;  pub use build::{build, build_toggled};++/// Whether tessellation may skip its ring-repair pass for an archive whose header sets+/// `FLAG_RINGS_VALIDATED`. **Off**: the flag is not trustworthy on the published planets.+///+/// Measured on `planet4.mamaps` (10 regions, z6-z14, analysis/ringprobe): holed polygons whose+/// holes properly cross their exterior or each other are 9-11% at z6-z7, 4-7% at z8-z9, ~1-2% at+/// z10-z11 and 0.1-1% at z12-z14 — simplification/quantisation after the writer's validation+/// pass. Trusting the flag hands those self-intersecting bridged rings straight to earcut, which+/// answers with slivers across the polygon (forest/water/landuse washes). Repairing costs+/// +2-8% tessellation time per tile at z12-z14 and ~+25% at z8-z10 (same measurement), paid once+/// per tile build, not per frame. Flip back on only for an archive whose writer validates after+/// its final coordinate change.+pub const TRUST_RINGS_VALIDATED: bool = false; pub use wash_overzoom::{needs_wash_underlay, parent_of, stitch_parent_wash, WASH_CAP_ZOOM}; pub use mesh::{     BuildingMesh, CarriagewayMesh, LayerMesh, RegionMesh, ShapedLabel, TerrainMesh, TileMesh,
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.rsindex 04ac062b4d..d86c0a976f 100644--- a/library/map/src/main/rust/src/tile/source/overlay.rs+++ b/library/map/src/main/rust/src/tile/source/overlay.rs@@ -31,10 +31,13 @@ pub struct Discovered { /// 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> {+/// Every file is opened read-only and never mutated. The base reads through+/// `base_leaves` — the surface's one shared cache, the same one the plain+/// single-archive path uses, so overlay discovery does not give every worker a+/// private copy of the (4 MiB-per-leaf, at planet scale) base index. Each segment+/// gets its own 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, base_leaves: Arc<LeafCache>) -> Option<Discovered> {     let dir = base_path.parent()?;     let overlays = dir.join("overlays");     let text = std::fs::read_to_string(overlays.join("manifest.json")).ok()?;@@ -68,7 +71,6 @@ pub fn discover(base_path: &Path) -> Option<Discovered> {     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),
library/map/src/main/rust/src/tile/source/urls.rs
diff --git a/library/map/src/main/rust/src/tile/source/urls.rs b/library/map/src/main/rust/src/tile/source/urls.rsindex 2e654ed375..270304f235 100644--- a/library/map/src/main/rust/src/tile/source/urls.rs+++ b/library/map/src/main/rust/src/tile/source/urls.rs@@ -1,6 +1,11 @@-/// Where this renderer reads its tiles from: the planet-scale v8 single-file-/// full `.mamaps` archive (9 layers, 128-byte header).-pub const BASEMAP_ARCHIVE_URL: &str = "https://data.maproj.org/planet3.mamaps";+/// Where this renderer reads its tiles from: the planet-scale single-file full `.mamaps`+/// archive (v9 header with v10 bodies, 10 layers, 128-byte header, graph/POI/transit+/// sections behind the `MAMA8` footer).+///+/// A new URL is a new cache origin: [`basemap_origin`] carries the URL, so the first open+/// against this URL wipes every range cached for the previous archive (planet3) instead of+/// keeping both — the cache directory is shared, not keyed per URL.+pub const BASEMAP_ARCHIVE_URL: &str = "https://data.maproj.org/planet4.mamaps";  /// Bumped when the on-disk cache layout changes, so old entries are dropped rather than /// misread. The URL is in the marker too, because the archive is republished under the
library/map/src/main/rust/tests/real_archive.rs
diff --git a/library/map/src/main/rust/tests/real_archive.rs b/library/map/src/main/rust/tests/real_archive.rsnew file mode 100644index 0000000000..2fd9acca4b--- /dev/null+++ b/library/map/src/main/rust/tests/real_archive.rs@@ -0,0 +1,422 @@+//! The renderer's reader against a REAL planet archive (`planet4.mamaps`, or the+//! byte-identical local build `scripts/maps/inputs/world.mamaps`).+//!+//! Ignored by default and gated on `MAMAPS_REAL_ARCHIVE`, so a normal `cargo test` never+//! needs the 80 GB input:+//!+//! ```text+//! MAMAPS_REAL_ARCHIVE=/path/to/world.mamaps \+//!   cargo test -p map_renderer --test real_archive -- --ignored --nocapture --test-threads=1+//! ```+//!+//! Everything goes through the code the app runs: `FileRangeReader` (the device's+//! `TileSource.LocalFile` path), tilecodec's `MamapsArchive` (the shared decoder the+//! writer tools also use), the app's style table, `geometry::build_toggled` (the worker's+//! tessellation entry point) and `source::discover` (overlay segments beside the base).+//! Graph/transit (the `offlinerouter` crate) and POI (Kotlin) have their own real-archive+//! tests; here the section directory is checked so every kind they read is present.++use std::collections::BTreeMap;+use std::path::{Path, PathBuf};+use std::sync::Arc;++use map_renderer::style::{self, KindFilter, LayerToggles};+use map_renderer::tile::geometry;+use map_renderer::tile::source::{discover, FileRangeReader};+use tilecodec::mamaps::archive::{self as sidecar, ArchiveView};+use tilecodec::mamaps::body::Body;+use tilecodec::mamaps::header::Header;+use tilecodec::mamaps::read::{LeafCache, MamapsArchive, TileSource};++const ENV: &str = "MAMAPS_REAL_ARCHIVE";++// planet4 claims FLAG_RINGS_VALIDATED without earning it; the renderer must keep repairing.+const _: () = assert!(!geometry::TRUST_RINGS_VALIDATED);++/// Cities the task names, plus a mountain for the DEM.+const CITIES: &[(&str, f64, f64)] = &[+    ("SF", 37.7749, -122.4194),+    ("NYC", 40.7580, -73.9855),+    ("London", 51.5074, -0.1278),+    ("Tokyo", 35.6812, 139.7671),+];+const ZOOMS: &[u8] = &[0, 4, 8, 10, 12, 13, 14];++fn archive_path() -> Option<PathBuf> {+    match std::env::var(ENV) {+        Ok(p) if !p.trim().is_empty() && Path::new(&p).is_file() => Some(PathBuf::from(p)),+        _ => {+            eprintln!("{ENV} not set (or not a file): real-archive test skipped");+            None+        }+    }+}++fn open(path: &Path) -> MamapsArchive<FileRangeReader> {+    MamapsArchive::open_with_cache(+        FileRangeReader::open(path).expect("FileRangeReader::open"),+        Arc::new(LeafCache::new()),+    )+    .expect("the app's reader refused the archive")+}++/// Slippy-map tile containing (lat, lon) at zoom `z`.+fn tile_of(lat: f64, lon: f64, z: u8) -> (u32, u32) {+    let n = (1u64 << z) as f64;+    let x = ((lon + 180.0) / 360.0 * n).floor();+    let lat_r = lat.to_radians();+    let y = ((1.0 - (lat_r.tan() + 1.0 / lat_r.cos()).ln() / std::f64::consts::PI) / 2.0 * n).floor();+    let max = n as u32 - 1;+    ((x as u32).min(max), (y as u32).min(max))+}++fn all_on() -> LayerToggles {+    LayerToggles { poi: true, transit: true, traffic: true, safety: true }+}++fn layer_name(id: u8) -> &'static str {+    tilecodec::mamaps::dict::LAYERS.get(id as usize).copied().unwrap_or("?")+}++#[test]+#[ignore = "needs MAMAPS_REAL_ARCHIVE (80 GB planet archive)"]+fn header_version_and_dictionary_are_accepted() {+    let Some(path) = archive_path() else { return };+    let mut head = vec![0u8; tilecodec::mamaps::header::HEADER_LEN];+    {+        use std::io::Read as _;+        std::fs::File::open(&path).unwrap().read_exact(&mut head).unwrap();+    }+    let header = Header::parse(&head).expect("header parse (version gate)");+    println!(+        "header: version byte {} flags {:#06x} compression {} layers {} z{}-{} build {:#018x} len {}",+        head[7], header.flags, header.compression, header.layer_count, header.min_zoom,+        header.max_zoom, header.build_id, header.file_len+    );+    assert_eq!(head[7], tilecodec::mamaps::header::FORMAT_VERSION_V9, "planet4 is a v9 archive");+    assert_eq!(header.file_len, std::fs::metadata(&path).unwrap().len());+    assert!(header.compressed() && header.rings_validated() && header.leaves_compressed());+    // The header claims validated rings, but the renderer does not trust it (see+    // geometry::TRUST_RINGS_VALIDATED, pinned off below); this test runs the same policy.+    assert_eq!(header.min_zoom, 0);+    assert_eq!(header.max_zoom, 14);++    let archive = open(&path);+    // `MamapsArchive::open` already validated the dictionary against the compiled-in+    // schema; pin the layer list the style is written against.+    assert_eq!(+        archive.dictionary.layers,+        [+            "landtype", "roads", "boundaries", "buildings", "places", "poi", "transit",+            "traffic", "junction", "safety",+        ]+    );+    assert_eq!(header.layer_count as usize, archive.dictionary.layers.len());+    println!("dictionary: {} layers, {} kinds, {} details",+        archive.dictionary.layers.len(), archive.dictionary.kinds.len(), archive.dictionary.details.len());+}++#[test]+#[ignore = "needs MAMAPS_REAL_ARCHIVE (80 GB planet archive)"]+fn section_directory_carries_every_kind_the_app_reads() {+    let Some(path) = archive_path() else { return };+    let file = std::fs::File::open(&path).unwrap();+    // SAFETY: read-only mapping of a file nobody writes while the test runs.+    let bytes = unsafe { memmap2::Mmap::map(&file) }.expect("mmap");+    let header = Header::parse(&bytes[..tilecodec::mamaps::header::HEADER_LEN]).unwrap();+    let view = ArchiveView::parse(&bytes, &header).expect("ArchiveView::parse (container checks)");+    let required = [+        (sidecar::ARCHIVE_KIND_GRAPH_META, "graph meta"),+        (sidecar::ARCHIVE_KIND_GRAPH_NODES, "graph nodes"),+        (sidecar::ARCHIVE_KIND_GRAPH_EDGES, "graph edges"),+        (sidecar::ARCHIVE_KIND_GRAPH_INTERMEDIATE, "graph intermediate"),+        (sidecar::ARCHIVE_KIND_GRAPH_NAMES, "road names"),+        (sidecar::ARCHIVE_KIND_GRAPH_LANES, "lanes"),+        (sidecar::ARCHIVE_KIND_POI_INDEX, "poi index"),+        (sidecar::ARCHIVE_KIND_POI_NAMES, "poi names"),+        (sidecar::ARCHIVE_KIND_POI_ATTRS, "poi attrs"),+        (sidecar::ARCHIVE_KIND_POI_SPATIAL, "poi spatial"),+        (sidecar::ARCHIVE_KIND_POI_WORDS, "poi words"),+        (sidecar::ARCHIVE_KIND_TRANSIT, "transit"),+        (sidecar::ARCHIVE_KIND_GRAPH_OVERLAY, "highway overlay"),+        (sidecar::ARCHIVE_KIND_POI_REGION, "poi region"),+    ];+    for (kind, name) in required {+        let (off, len) = view.location(kind).unwrap_or_else(|| panic!("kind {kind} ({name}) missing"));+        let s = view.section(&bytes, kind).unwrap();+        println!("kind {kind:2} {name:<18} @{off} len {len} magic {:02x?}", &s[..4.min(s.len())]);+    }+    // Optional, and absent from planet4 (road_graph ran without --dem): the router reads+    // a missing elevation section as "no profile".+    println!("kind  7 elevation present: {}", view.location(sidecar::ARCHIVE_KIND_GRAPH_ELEVATION).is_some());+}++#[derive(Default)]+struct LayerTally {+    tiles: usize,+    features: usize,+}++#[test]+#[ignore = "needs MAMAPS_REAL_ARCHIVE (80 GB planet archive)"]+fn every_layer_decodes_and_tessellates_in_four_cities() {+    let Some(path) = archive_path() else { return };+    let archive = open(&path);+    let layers = style::layers();+    let rings_validated = archive.header.rings_validated() && geometry::TRUST_RINGS_VALIDATED;+    let mut tally: BTreeMap<&'static str, LayerTally> = BTreeMap::new();+    let mut versions: BTreeMap<u8, usize> = BTreeMap::new();+    let (mut tiles, mut meshes, mut labels, mut buildings, mut carriageways, mut traffic, mut regions) =+        (0, 0, 0, 0, 0, 0, 0);+    let mut extra: BTreeMap<&'static str, usize> = BTreeMap::new();+    for &(city, lat, lon) in CITIES {+        for &z in ZOOMS {+            let (x, y) = tile_of(lat, lon, z);+            let raw = archive.tile_bytes(z, x, y).expect("tile_bytes");+            let body: Body = archive+                .tile(z, x, y)+                .unwrap_or_else(|e| panic!("{city} {z}/{x}/{y}: decode failed: {e}"))+                .unwrap_or_else(|| panic!("{city} {z}/{x}/{y}: absent"));+            // Byte 3 of the stored body header is the body version (v10 = narrowed records).+            if let Some(raw) = raw {+                *versions.entry(raw[3]).or_default() += 1;+            }+            tiles += 1;+            let mut line = format!("{city:<6} {z:2}/{x}/{y}:");+            for layer in &body.layers {+                let t = tally.entry(layer_name(layer.layer_id)).or_default();+                t.tiles += 1;+                t.features += layer.features.len();+                line += &format!(" {}={}", layer_name(layer.layer_id), layer.features.len());+            }+            for (name, present) in [+                ("names", !body.names.is_empty()),+                ("ids", !body.ids.is_empty()),+                ("turn_lanes", !body.turn_lanes.is_empty()),+                ("buildings_table", !body.buildings.is_empty()),+                ("heightmap", body.heightmap.is_some()),+                ("carriageways", !body.carriageways.is_empty()),+                ("convention", body.convention.is_some()),+                ("region_links", !body.region_links.is_empty()),+            ] {+                if present {+                    *extra.entry(name).or_default() += 1;+                }+            }+            let mesh = geometry::build_toggled(+                &body, layers, z, x, y, rings_validated, all_on(), &KindFilter::all(), 1,+            );+            assert_eq!((mesh.z, mesh.x, mesh.y), (z, x, y));+            meshes += mesh.meshes.iter().filter(|m| !m.indices.is_empty()).count();+            labels += mesh.labels.len();+            buildings += usize::from(!mesh.buildings.indices.is_empty());+            carriageways += mesh.carriageways.len();+            traffic += mesh.traffic.len();+            regions += mesh.regions.len();+            assert!(+                mesh.meshes.iter().any(|m| !m.indices.is_empty()),+                "{city} {z}/{x}/{y}: nothing tessellated"+            );+            println!("{line} | meshes {} labels {}", mesh.meshes.len(), mesh.labels.len());+        }+    }+    println!("body versions: {versions:?}");+    println!("optional body sections (tiles carrying): {extra:?}");+    println!(+        "tiles {tiles} non-empty meshes {meshes} labels {labels} building tiles {buildings} carriageways {carriageways} traffic {traffic} regions {regions}"+    );+    for (name, t) in &tally {+        println!("layer {name:<10} tiles {:3} features {}", t.tiles, t.features);+    }+    for name in tilecodec::mamaps::dict::LAYERS {+        if *name == "traffic" {+            // The writer stopped emitting `traffic` features (mamaps_build extract_part3.rs:+            // "dropped as of the NA diet"); the layer stays in the dictionary with zero+            // features. Pinned so a rebuild that brings it back is noticed.+            assert!(!tally.contains_key(name), "traffic layer is back: wire up and test it");+            continue;+        }+        assert!(+            tally.get(name).is_some_and(|t| t.features > 0),+            "layer {name} never appeared in {tiles} city tiles"+        );+    }+    assert!(buildings > 0, "no 3D buildings tessellated");+    // Lane rendering is switched off in the style (style::LANE_RENDERING, z16+ overzoom), so+    // carriageway meshes stay empty by design; the tables themselves must still decode.+    assert!(extra.contains_key("carriageways"), "no carriageway tables decoded");+    assert!(extra.contains_key("turn_lanes"), "no turn-lane tables decoded");+    assert_eq!(traffic, 0);+    assert!(labels > 0, "no labels shaped");+    assert!(regions > 0, "no region-mask shapes (boundaries)");+    assert!(extra.contains_key("heightmap"), "no heightmap on any city tile");+    assert!(extra.contains_key("region_links"), "no region-link tables decoded");+    assert!(versions.keys().all(|&v| v == 10), "expected v10 bodies only, got {versions:?}");+}++#[test]+#[ignore = "needs MAMAPS_REAL_ARCHIVE (80 GB planet archive)"]+fn dem_heightmaps_sample_and_drape() {+    let Some(path) = archive_path() else { return };+    let archive = open(&path);+    let layers = style::layers();+    // Mount Fuji (3776 m) and the SF hills: relief must come through with real metres.+    for &(name, lat, lon, z, min_peak) in &[+        ("Fuji", 35.3606, 138.7274, 12u8, 2500i32),+        ("Fuji", 35.3606, 138.7274, 10u8, 2000i32),+        ("SF Twin Peaks", 37.7544, -122.4477, 12u8, 150i32),+        ("Denver flat", 39.7392, -104.9903, 12u8, 1400i32),+    ] {+        let (x, y) = tile_of(lat, lon, z);+        let body = archive.tile(z, x, y).unwrap().expect("tile present");+        let hm = body.heightmap.as_ref().unwrap_or_else(|| panic!("{name} {z}/{x}/{y}: no heightmap"));+        assert_eq!(hm.samples.len(), hm.dim as usize * hm.dim as usize);+        let metres: Vec<i32> = hm.samples.iter().map(|&s| tilecodec::mamaps::body::Heightmap::metres(s)).collect();+        let (lo, hi) = (*metres.iter().min().unwrap(), *metres.iter().max().unwrap());+        let mid = hm.sample(hm.dim / 2, hm.dim / 2).map(tilecodec::mamaps::body::Heightmap::metres);+        println!("{name:<14} {z}/{x}/{y} dim {} min {lo} m max {hi} m centre {mid:?}", hm.dim);+        assert!(hi >= min_peak, "{name}: max {hi} m below {min_peak} m");+        assert!(lo > -500 && hi < 9000, "{name}: implausible range {lo}..{hi}");+        let mesh = geometry::build(&body, layers, z, x, y, archive.header.rings_validated() && geometry::TRUST_RINGS_VALIDATED);+        assert!(!mesh.terrain.indices.is_empty(), "{name}: heightmap present but no terrain mesh");+    }+}++#[test]+#[ignore = "needs MAMAPS_REAL_ARCHIVE (80 GB planet archive)"]+fn an_overlay_segment_is_discovered_and_served_patch_first() {+    use tilecodec::mamaps::write::{Options, StreamWriter};+    let Some(path) = archive_path() else { return };+    let base = open(&path);+    let build = base.header.build_id;+    let len = base.header.file_len;++    // Patch one SF z14 tile (drop its buildings layer, so the patch is visible) and+    // tombstone one London z14 tile; everything else must still come from the base.+    let (px, py) = tile_of(37.7749, -122.4194, 14);+    let (tx, ty) = tile_of(51.5074, -0.1278, 14);+    let (ux, uy) = tile_of(40.7580, -73.9855, 14);+    let mut patched = base.tile(14, px, py).unwrap().expect("SF z14");+    let before = patched.layers.len();+    patched.layers.retain(|l| layer_name(l.layer_id) != "buildings");+    patched.buildings.clear();+    assert!(patched.layers.len() < before, "SF z14 had no buildings layer to drop");++    let dir = std::env::temp_dir().join(format!("real-archive-overlay-{}", std::process::id()));+    let _ = std::fs::remove_dir_all(&dir);+    std::fs::create_dir_all(dir.join("overlays/0001")).unwrap();+    let base_link = dir.join("basemap.mamaps");+    std::os::unix::fs::symlink(&path, &base_link).unwrap();+    let mut writer = StreamWriter::new(Options {+        build_id: 0xabcd,+        rings_validated: true,+        ..Options::default()+    })+    .unwrap();+    writer.append(tilecodec::pmtiles::tile_id(14, px as u64, py as u64), &patched).unwrap();+    let seg = writer.finish().unwrap();+    std::fs::write(dir.join("overlays/0001/overlay-0000.mamaps"), &seg).unwrap();+    let manifest = format!(+        r#"{{"version":1,"base":{{"url":"https://data.maproj.org/planet4.mamaps","build_id":"{build:#018x}","len":{len}}},"overlay_seq":1,"overlay_build_id":"0xabcd","segments":[{{"url":"https://data.maproj.org/overlays/0001/overlay-0000.mamaps","len":{},"sha256":"x","seq":0}}],"sections":[],"tombstones":[{}],"min_client":1}}"#,+        seg.len(),+        tilecodec::pmtiles::tile_id(14, tx as u64, ty as u64),+    );+    std::fs::write(dir.join("overlays/manifest.json"), manifest).unwrap();++    let found = discover(&base_link, Arc::new(LeafCache::new())).expect("discover refused a valid overlay over the real base");+    assert_eq!(found.seq, 1);+    let overlay = found.overlay;+    assert_eq!(overlay.header().build_id, build, "the overlay keeps the base identity");+    let served = overlay.tile(14, px, py).unwrap().expect("patched tile");+    assert!(served.layers.iter().all(|l| layer_name(l.layer_id) != "buildings"), "segment not served first");+    assert!(overlay.tile(14, tx, ty).unwrap().is_none(), "tombstoned tile still served");+    let untouched = overlay.tile(14, ux, uy).unwrap().expect("base tile");+    assert_eq!(untouched, base.tile(14, ux, uy).unwrap().unwrap(), "base tile changed under the overlay");+    let batch = overlay.tiles(&[(14, px, py), (14, tx, ty), (14, ux, uy)]);+    assert!(batch[0].as_ref().unwrap().is_some() && batch[1].as_ref().unwrap().is_none());+    println!("overlay: seq 1 segment {} B, patch-first + tombstone + base fall-through OK", seg.len());++    // A manifest pinned to another base (planet3) must be refused: base alone.+    let stale = std::fs::read_to_string(dir.join("overlays/manifest.json"))+        .unwrap()+        .replace(&format!("{build:#018x}"), "0x0a90e5e4ab91159e");+    std::fs::write(dir.join("overlays/manifest.json"), stale).unwrap();+    assert!(discover(&base_link, Arc::new(LeafCache::new())).is_none(), "an overlay for another base was accepted");+    let _ = std::fs::remove_dir_all(&dir);+}++/// A [`RangeFetcher`] over the `curl` binary, standing in for the device's+/// `JniRangeFetcher` (`:library:network`) on the host. Honours `https_proxy`.+struct CurlFetcher;++impl map_renderer::tile::source::RangeFetcher for CurlFetcher {+    fn fetch(+        &self,+        url: &str,+        range: &str,+    ) -> tilecodec::proto::Result<map_renderer::tile::source::RangeResponse> {+        let bytes = range.strip_prefix("bytes=").unwrap_or(range);+        let out = std::env::temp_dir().join(format!("curl-range-{}-{bytes}", std::process::id()));+        let status = std::process::Command::new("curl")+            .args(["-s", "-m", "60", "-r", bytes, "-o"])+            .arg(&out)+            .args(["-w", "%{http_code}", url])+            .output()+            .map_err(|e| tilecodec::proto::Error(format!("curl: {e}")))?;+        let code: u16 = String::from_utf8_lossy(&status.stdout).trim().parse().unwrap_or(0);+        let body = std::fs::read(&out).unwrap_or_default();+        let _ = std::fs::remove_file(&out);+        Ok(map_renderer::tile::source::RangeResponse { status: code, body })+    }+}++/// The LIVE planet4 through the renderer's HTTP path: the 128-byte header range the workers+/// fetch first, the origin marker it keys the disk cache on, then a cold tile read through+/// `CachingRangeReader` + `RangeCache` + the shared decoder — compared byte-for-byte with the+/// local copy when `MAMAPS_REAL_ARCHIVE` is set too. Gated on `MAMAPS_LIVE=1` (network).+#[test]+#[ignore = "needs MAMAPS_LIVE=1 and network to data.maproj.org"]+fn live_planet4_reads_through_the_range_cache() {+    use map_renderer::tile::cache::{RangeCache, DEFAULT_MAX_BYTES};+    use map_renderer::tile::source::{+        basemap_origin, CachingRangeReader, RangeFetcher, BASEMAP_ARCHIVE_URL,+    };+    if std::env::var("MAMAPS_LIVE").as_deref() != Ok("1") {+        eprintln!("MAMAPS_LIVE not set: live test skipped");+        return;+    }+    assert_eq!(BASEMAP_ARCHIVE_URL, "https://data.maproj.org/planet4.mamaps");+    let head = CurlFetcher.fetch(BASEMAP_ARCHIVE_URL, "bytes=0-127").expect("header fetch");+    assert_eq!(head.status, 206, "the CDN must answer ranges");+    assert_eq!(head.body.len(), tilecodec::mamaps::header::HEADER_LEN);+    let header = Header::parse(&head.body).expect("live header parses");+    println!(+        "live: build {:#018x} len {} version {} layers {}",+        header.build_id, header.file_len, head.body[7], header.layer_count+    );+    assert_eq!(header.build_id, 0x2ab5_ba58_33e5_4438);+    assert_eq!(header.file_len, 81_331_811_296);++    let dir = std::env::temp_dir().join(format!("live-range-cache-{}", std::process::id()));+    let _ = std::fs::remove_dir_all(&dir);+    let origin = basemap_origin(BASEMAP_ARCHIVE_URL, header.build_id);+    let cache = RangeCache::open(&dir, &origin, DEFAULT_MAX_BYTES);+    let reader = CachingRangeReader::new(BASEMAP_ARCHIVE_URL, cache, CurlFetcher);+    let live = MamapsArchive::open_with_cache(reader, Arc::new(LeafCache::new())).expect("live open");+    assert_eq!(live.header, header);+    let (x, y) = tile_of(37.7749, -122.4194, 14);+    let body = live.tile(14, x, y).expect("live tile").expect("SF z14 present");+    let cached = std::fs::read_dir(&dir).unwrap().flatten().filter(|e| {+        e.path().extension().is_some_and(|x| x == "data")+    }).count();+    println!("live: SF z14 has {} layers; {cached} ranges cached under {origin}", body.layers.len());+    assert!(cached > 0, "nothing landed in the range cache");+    assert_eq!(std::fs::read_to_string(dir.join(".origin")).unwrap().trim(), origin);+    if let Some(path) = archive_path() {+        let local = open(&path);+        assert_eq!(local.header, header, "local world.mamaps is not the published planet4");+        assert_eq!(local.tile(14, x, y).unwrap().unwrap(), body, "live and local bodies differ");+        println!("live: header and SF z14 body identical to the local archive");+    }+    let _ = std::fs::remove_dir_all(&dir);+}