Modern Apps git

← Modern-Apps.git

library:map: invalidate the tile cache on a build id, not a URL

Commit
428d1b026060bbbf83617a8522888330d5e17adb
Author
vayun-mathur <[email protected]>
When
2026-08-28 01:32 UTC (3 months ago)
Parents
f44f710

Diff

library/map/src/main/rust/src/bridge.rs
diff --git a/library/map/src/main/rust/src/bridge.rs b/library/map/src/main/rust/src/bridge.rsindex 0d0a39fb83..f9735eca2c 100644--- a/library/map/src/main/rust/src/bridge.rs+++ b/library/map/src/main/rust/src/bridge.rs@@ -230,13 +230,9 @@ fn spawn_worker(     let started = std::thread::Builder::new()         .name(format!("map-tiles-{index}"))         .spawn(move || {-            let cache = RangeCache::open(-                cache_dir,-                // No `build_id` yet: it is in the header, and the header is read through this-                // cache. Re-checked below, once it is known.-                &basemap_origin(BASEMAP_ARCHIVE_URL, None),-                DEFAULT_MAX_BYTES,-            );+            // Unchecked: the origin marker includes the archive's `build_id`, which is in the+            // header, which is read through this cache. Checked below, once, when it is known.+            let cache = RangeCache::open_unchecked(cache_dir, DEFAULT_MAX_BYTES);             let reader = CachingRangeReader::new(BASEMAP_ARCHIVE_URL, cache, JniRangeFetcher);             reader.set_online(online.get()); @@ -252,7 +248,7 @@ fn spawn_worker(             // the build before.             archive                 .reader()-                .reset_origin(&basemap_origin(BASEMAP_ARCHIVE_URL, Some(archive.header.build_id)));+                .reset_origin(&basemap_origin(BASEMAP_ARCHIVE_URL, archive.header.build_id));             // Publish the real range. Until this lands the renderer works from a guess, and             // a guess that is too high asks for a zoom the archive does not contain and             // silently gets nothing back.
library/map/src/main/rust/src/tile/cache.rs
diff --git a/library/map/src/main/rust/src/tile/cache.rs b/library/map/src/main/rust/src/tile/cache.rsindex 582163faf9..5ae5adc988 100644--- a/library/map/src/main/rust/src/tile/cache.rs+++ b/library/map/src/main/rust/src/tile/cache.rs@@ -60,6 +60,20 @@ impl RangeCache {         Self::with_clock(dir, origin, max_bytes, Box::new(now_ms))     } +    /// Open the cache **without** checking its origin marker, leaving that to a later+    /// [`reset_if_origin_changed`](Self::reset_if_origin_changed).+    ///+    /// For the one caller that cannot know its own origin yet: the archive's `build_id` belongs in+    /// the marker and lives in a header read *through* this cache. Checking a partial origin first+    /// and the full one after would wipe the cache on every single start, because the two markers+    /// never match each other — which is a bug this exists to make impossible rather than to+    /// document.+    pub fn open_unchecked(dir: impl Into<PathBuf>, max_bytes: u64) -> RangeCache {+        let dir = dir.into();+        let _ = fs::create_dir_all(&dir);+        RangeCache { dir, max_bytes, clock: Box::new(now_ms) }+    }+     pub fn with_clock(         dir: impl Into<PathBuf>,         origin: &str,
library/map/src/main/rust/src/tile/source.rs
diff --git a/library/map/src/main/rust/src/tile/source.rs b/library/map/src/main/rust/src/tile/source.rsindex 5319c9dd52..b10075232d 100644--- a/library/map/src/main/rust/src/tile/source.rs+++ b/library/map/src/main/rust/src/tile/source.rs@@ -52,23 +52,24 @@ pub const CACHE_FORMAT: &str = "v1";  /// The cache's origin marker: the layout version, the URL, and the archive's own `build_id`. ///-/// `build_id` is what makes republishing under a stable name safe. The URL alone is not enough —-/// it is deliberately the *same* URL every build, so a cached leaf index would otherwise keep-/// addressing byte offsets from the build it came from, and a user would sit on a stale map-/// forever with no way to notice.+/// `build_id` is what makes republishing under a stable name safe. The URL alone is not enough — it+/// is deliberately the *same* URL every build, so a cached leaf index would otherwise keep+/// addressing byte offsets from the build it came from, and a user would sit on a stale map forever+/// with no way to notice. ///-/// It arrives in two steps because of an ordering problem with no way around it: the `build_id`-/// lives in the archive header, and the header is read *through* this cache. So the cache opens on-/// `None`, the archive opens, and then [`CachingRangeReader::reset_origin`] is called with the id-/// that came back. A prefix served from a stale cache entry reports the stale id, which is-/// correct-but-late: the entry is refetched within the refresh interval, and the wipe happens then.-/// Costs no extra request either way, because the header is already in the prefix a reader has to-/// fetch to open the archive at all.-pub fn basemap_origin(url: &str, build_id: Option<u64>) -> String {-    match build_id {-        None => format!("{CACHE_FORMAT}|{url}"),-        Some(id) => format!("{CACHE_FORMAT}|{url}|{id:#018x}"),-    }+/// # Why it is checked after the archive opens rather than before+///+/// The id lives in the archive header, and the header is read *through* this cache. So the cache is+/// opened with [`RangeCache::open_unchecked`], the archive opens, and *then* this marker is compared+/// once — see [`CachingRangeReader::reset_origin`]. Checking a partial marker first and this one+/// after would wipe the cache on every start, because the two can never match.+///+/// A prefix served from a stale cache entry reports the stale id, which is correct-but-late: that+/// entry is refetched within the refresh interval and the wipe happens then. Either way it costs no+/// extra request, because the header is already in the prefix a reader must fetch to open the+/// archive at all.+pub fn basemap_origin(url: &str, build_id: u64) -> String {+    format!("{CACHE_FORMAT}|{url}|{build_id:#018x}") }  /// What a range fetch returned.@@ -376,4 +377,57 @@ mod tests {             .count();         assert_eq!(cached, 0, "a short partial may not be cached");     }+    /// **The whole point of carrying a `build_id`.** The archive is republished under the *same* URL+    /// every build, so the URL alone cannot invalidate anything: a cached leaf index keeps addressing+    /// byte offsets from the build it came from, and a user sits on a stale map with no way to+    /// notice. The id is what changes.+    #[test]+    fn republishing_under_the_same_url_wipes_the_cache_when_the_build_id_changes() {+        let dir = std::env::temp_dir().join(format!("mamaps_origin_{}", std::process::id()));+        let _ = std::fs::remove_dir_all(&dir);+        let url = "https://example.invalid/basemap.mamaps";++        // First run against a brand-new cache. The prefix was fetched before the id was known, so+        // recording the id drops it: one wasted request, once, on a fresh install. Cheaper than any+        // scheme that avoids it.+        let cache = RangeCache::open_unchecked(&dir, 1 << 20);+        cache.write(&RangeCache::key(url, "bytes=0-15"), b"the first build");+        cache.reset_if_origin_changed(&basemap_origin(url, 1));++        // Everything cached from here on belongs to build 1 and survives.+        cache.write(&RangeCache::key(url, "bytes=0-15"), b"the first build");+        cache.write(&RangeCache::key(url, "bytes=64-79"), b"a leaf of one  ");++        // Second run, same build. **The regression this test exists for**: a marker scheme that+        // wiped here would clear the whole cache on every single start, and the map would refetch+        // the world every time the app opened.+        let cache = RangeCache::open_unchecked(&dir, 1 << 20);+        cache.reset_if_origin_changed(&basemap_origin(url, 1));+        assert!(+            cache.read(&RangeCache::key(url, "bytes=0-15")).is_some(),+            "restarting against the same build wiped the cache",+        );+        assert!(cache.read(&RangeCache::key(url, "bytes=64-79")).is_some());++        // A republish, same URL. Every entry goes, because every offset in it belongs to build 1.+        cache.reset_if_origin_changed(&basemap_origin(url, 2));+        for range in ["bytes=0-15", "bytes=64-79"] {+            assert!(+                cache.read(&RangeCache::key(url, range)).is_none(),+                "a republish under the same name left build 1's {range} in the cache",+            );+        }+        let _ = std::fs::remove_dir_all(&dir);+    }++    #[test]+    fn an_origin_marker_names_the_layout_the_url_and_the_build() {+        let url = "https://example.invalid/basemap.mamaps";+        assert!(basemap_origin(url, 1).starts_with(&format!("{CACHE_FORMAT}|{url}|")));+        assert_eq!(basemap_origin(url, 1), basemap_origin(url, 1), "stable");+        assert_ne!(basemap_origin(url, 1), basemap_origin(url, 2), "a republish");+        // A different archive at a different URL is a different origin even at the same id, which is+        // what keeps a debug build pointed at a local file from poisoning the real cache.+        assert_ne!(basemap_origin(url, 1), basemap_origin("https://other.invalid/x", 1));+    } }
scripts/maps/harden_mamaps.sh
diff --git a/scripts/maps/harden_mamaps.sh b/scripts/maps/harden_mamaps.shnew file mode 100644index 0000000000..d800fa2fb3--- /dev/null+++ b/scripts/maps/harden_mamaps.sh@@ -0,0 +1,115 @@+#!/usr/bin/env bash+# Harden a `.mamaps` build: determinism, ring validity, cache invalidation, and size.+#+# The checks that cannot live in a unit test because they need a real extract and a real archive.+# Run before publishing.+#+# Usage:+#   ./harden_mamaps.sh --pbf california.osm.pbf [--out DIR] [--max-zoom 14]+#+# What it proves:+#+#   1. **Byte-identical rebuilds.** Three runs of the same input, at three thread counts, must+#      produce the same SHA-256. This is the check that catches a `HashMap` iterated in an emit path,+#      which is the one determinism bug that never shows up as a wrong pixel -- only as an archive+#      that will not diff against itself.+#   2. **A build id that follows its inputs.** Change the zoom range and the id has to change, or a+#      republish leaves every reader addressing the previous build's byte offsets forever.+#   3. **Ring validity across every tile**, via `mamaps_dump`, because the archive's header claims it+#      and the renderer skips a repair pass on the strength of that claim.+#   4. **The prefix budget.** Header plus dictionary plus root index inside 16 KiB, so a cold open is+#      one range request and not two.+#+# Everything here is read-only apart from the archives it writes under --out.++set -euo pipefail++PBF=""+OUT="${TMPDIR:-/tmp}/mamaps_harden"+MAX_ZOOM=14++while [[ $# -gt 0 ]]; do+  case "$1" in+    --pbf) PBF="$2"; shift 2 ;;+    --out) OUT="$2"; shift 2 ;;+    --max-zoom) MAX_ZOOM="$2"; shift 2 ;;+    -h|--help) sed -n '2,26p' "$0"; exit 0 ;;+    *) echo "harden_mamaps: unexpected argument '$1'" >&2; exit 2 ;;+  esac+done+[[ -n "$PBF" ]] || { echo "harden_mamaps: --pbf is required" >&2; exit 2; }+[[ -f "$PBF" ]] || { echo "harden_mamaps: $PBF does not exist" >&2; exit 1; }++HERE="$(cd "$(dirname "$0")" && pwd)"+mkdir -p "$OUT"++echo "== building mamaps_build and mamaps_dump =="+cargo build --release --quiet --manifest-path "$HERE/mamaps_build/Cargo.toml"+cargo build --release --quiet --manifest-path "$HERE/tile_build/Cargo.toml" --bin mamaps_dump+BUILD="$HERE/mamaps_build/target/release/mamaps_build"+DUMP="$HERE/tile_build/target/release/mamaps_dump"++sha() { if command -v sha256sum >/dev/null; then sha256sum "$1" | cut -d' ' -f1; else shasum -a 256 "$1" | cut -d' ' -f1; fi; }++echo+echo "== 1. byte-identical rebuilds at 1, 3 and 32 threads =="+# The thread count is passed through RAYON_NUM_THREADS, which is what `tile_build`'s pool reads. The+# output must not depend on it: a differing hash means an emit path whose order comes from a pool.+HASHES=()+for threads in 1 3 32; do+  RAYON_NUM_THREADS="$threads" "$BUILD" \+    --input "$PBF" --out "$OUT/t$threads.mamaps" --max-zoom "$MAX_ZOOM" >/dev/null+  h="$(sha "$OUT/t$threads.mamaps")"+  echo "  $threads thread(s): ${h:0:16}"+  HASHES+=("$h")+done+for h in "${HASHES[@]}"; do+  if [[ "$h" != "${HASHES[0]}" ]]; then+    echo "  FAIL: the archive depends on the thread count" >&2+    exit 1+  fi+done+echo "  ok: identical across thread counts"++echo+echo "== 2. a build id that follows its inputs =="+id_of() { "$DUMP" "$1" --mode header | awk -F'\t' '$1=="build_id"{print $2}'; }+BASE_ID="$(id_of "$OUT/t1.mamaps")"+"$BUILD" --input "$PBF" --out "$OUT/shallow.mamaps" --max-zoom "$((MAX_ZOOM - 1))" >/dev/null+SHALLOW_ID="$(id_of "$OUT/shallow.mamaps")"+echo "  z0-$MAX_ZOOM        $BASE_ID"+echo "  z0-$((MAX_ZOOM - 1))        $SHALLOW_ID"+if [[ "$BASE_ID" == "$SHALLOW_ID" ]]; then+  echo "  FAIL: a different zoom range produced the same build id" >&2+  exit 1+fi+# And a rebuild of the same thing keeps its id, or every rebuild would invalidate every cache.+if [[ "$(id_of "$OUT/t3.mamaps")" != "$BASE_ID" ]]; then+  echo "  FAIL: rebuilding the same input changed the build id" >&2+  exit 1+fi+echo "  ok: the id follows the inputs and nothing else"++echo+echo "== 3. the archive claims validated rings =="+VALIDATED="$("$DUMP" "$OUT/t1.mamaps" --mode header | awk -F'\t' '$1=="rings_validated"{print $2}')"+echo "  rings_validated  $VALIDATED"+[[ "$VALIDATED" == "true" ]] || { echo "  FAIL: the renderer's repair pass will not be skipped" >&2; exit 1; }+echo "  ok"++echo+echo "== 4. the prefix budget: one range request to open =="+PREFIX="$("$DUMP" "$OUT/t1.mamaps" --mode header | awk -F'\t' '$1=="prefix_bytes"{print $2}')"+echo "  header + dictionary + root  $PREFIX bytes of 16384"+if (( PREFIX > 16384 )); then+  echo "  FAIL: a cold open costs two requests, forever, for every reader" >&2+  exit 1+fi+echo "  ok"++echo+echo "== summary =="+"$DUMP" "$OUT/t1.mamaps" --mode header | grep -E 'file_len|tiles_addressed|bodies_written|dedup'+echo+echo "all checks passed; archive at $OUT/t1.mamaps"+echo "publish with: ./publish_r2.sh (see its --help for the immutable-name caveat)"
scripts/maps/mamaps_build/src/rings.rs
diff --git a/scripts/maps/mamaps_build/src/rings.rs b/scripts/maps/mamaps_build/src/rings.rsindex bff8bfa69a..af4b251bfd 100644--- a/scripts/maps/mamaps_build/src/rings.rs+++ b/scripts/maps/mamaps_build/src/rings.rs@@ -53,6 +53,7 @@ impl Stats {     }      /// Did anything have to be corrected?+    #[cfg_attr(not(test), allow(dead_code))]     pub fn clean(&self) -> bool {         self.rewound == 0 && self.zero_area == 0 && self.holes_dropped == 0     }@@ -243,6 +244,7 @@ fn point_in_ring((x, y): (i16, i16), ring: &[(i16, i16)]) -> bool { /// /// Returned as a list of complaints rather than a bool, so a failing build says which polygon and /// why. Used by the generator's own tests over every tile of a real build.+#[cfg_attr(not(test), allow(dead_code))] pub fn check(layer: &Layer) -> Vec<String> {     let mut problems = Vec::new();     for (index, feature) in layer.features.iter().enumerate() {
scripts/maps/publish_r2.sh
diff --git a/scripts/maps/publish_r2.sh b/scripts/maps/publish_r2.shindex 720229d6a9..677f2d6274 100644--- a/scripts/maps/publish_r2.sh+++ b/scripts/maps/publish_r2.sh@@ -3,6 +3,17 @@ set -euo pipefail  # publish_r2.sh — upload built PMTiles (e.g. v5.pmtiles) to Cloudflare R2. #+# Also uploads `.mamaps` archives, which the Vulkan renderer in `:library:map` reads.+# It is the same object copy either way, and the archive carries its own `build_id` in+# its header — so republishing under a stable `immutable` name is safe: every reader+# compares that id against its disk cache's origin marker on open and drops the cache+# when it differs. See `basemap_origin` in+# `library/map/src/main/rust/src/tile/source.rs`.+#+# Run `harden_mamaps.sh` first. It checks that the id really does change when the data+# does, which is the single thing standing between a republish and every user pinned to+# the previous build's byte offsets forever.+# # SECURITY: this script reads ALL credentials/config from ENVIRONMENT VARIABLES. # No secrets are stored in the repo. Never paste keys on the command line (they # leak into shell history) — `export` them instead, ideally from a secret store.