maps: overlay generator plus manifest publish
- Commit
8a984f10bd3659fef74a980d190863fef793af5a- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-24 23:37 UTC (1 month ago)
- Parents
0f29e6e
Diff
Cargo.lock
diff --git a/Cargo.lock b/Cargo.lockindex 4f79951be2..1fd417e1dc 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -5502,6 +5502,7 @@ dependencies = [ "memmap2", "miniz_oxide 0.8.9", "rayon",+ "sha2 0.11.1", "tilecodec", ]
scripts/maps/tile_build/Cargo.toml
diff --git a/scripts/maps/tile_build/Cargo.toml b/scripts/maps/tile_build/Cargo.tomlindex addf62044e..3b808c927c 100644--- a/scripts/maps/tile_build/Cargo.toml+++ b/scripts/maps/tile_build/Cargo.toml@@ -40,12 +40,16 @@ path = "src/bin/mamaps_pack.rs" [[bin]] name = "mamaps_churn" path = "src/bin/mamaps_churn.rs"+[[bin]]+name = "mamaps_overlay"+path = "src/bin/mamaps_overlay.rs" [dependencies] # The PMTiles + MVT codec, shared with the Android renderer in `:library:map`. # Member of the repo-root workspace; path + `write` feature select the writer. tilecodec = { workspace = true, features = ["write"] } miniz_oxide.workspace = true rayon.workspace = true+sha2.workspace = true # Anonymous pagefile-backed mappings for the spill backends (see `anon`): already # in the tree via osm_ingest, so this adds a name to link, not a crate to fetch. memmap2.workspace = true
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.rsnew file mode 100644index 0000000000..a463916ab8--- /dev/null+++ b/scripts/maps/tile_build/src/bin/mamaps_overlay.rs@@ -0,0 +1,117 @@+//! `mamaps_overlay` — build patch-overlay segments from two `.mamaps` archives.+//!+//! Usage:+//! mamaps_overlay --before OLD.mamaps --after NEW.mamaps --out-dir DIR+//! [--base-url URL]+//!+//! Emits `overlay-0000.mamaps`, `overlay-0001.mamaps`, … plus `overlay.json`+//! (the per-overlay half of `planet3.manifest.json`: overlay seq/build id,+//! segment list with lengths and SHA-256). Each segment is a small+//! self-contained `.mamaps` holding only changed/added tile bodies with+//! overlay-relative offsets; the base is never touched.+//!+//! The publisher renames the segment files to their content-addressed R2+//! keys, fills in the download URLs, and merges `overlay.json` into the+//! manifest (see `upload_planet.py --manifest`).++use std::path::PathBuf;+use std::process::ExitCode;++use tile_build::overlay::{emit_segment, open_pair, plan};++fn value(args: &[String], i: usize, name: &str) -> PathBuf {+ match args.get(i + 1) {+ Some(v) => PathBuf::from(v),+ None => {+ eprintln!("mamaps_overlay: {name} needs a value");+ std::process::exit(2);+ }+ }+}++fn main() -> ExitCode {+ let args: Vec<String> = std::env::args().collect();+ let mut before: Option<PathBuf> = None;+ let mut after: Option<PathBuf> = None;+ let mut out_dir: Option<PathBuf> = None;+ let mut i = 1;+ while i < args.len() {+ match args[i].as_str() {+ "--before" => before = Some(value(&args, i, "--before")),+ "--after" => after = Some(value(&args, i, "--after")),+ "--out-dir" => out_dir = Some(value(&args, i, "--out-dir")),+ other => {+ eprintln!("mamaps_overlay: unknown flag {other}");+ return ExitCode::from(2);+ }+ }+ i += 2;+ }+ let (Some(before), Some(after), Some(out_dir)) = (before, after, out_dir) else {+ eprintln!("usage: mamaps_overlay --before OLD.mamaps --after NEW.mamaps --out-dir DIR");+ return ExitCode::from(2);+ };+ match run(&before, &after, &out_dir) {+ Ok(summary) => {+ println!("{summary}");+ ExitCode::SUCCESS+ }+ Err(e) => {+ eprintln!("mamaps_overlay: {e}");+ ExitCode::from(1)+ }+ }+}++fn run(before: &std::path::Path, after: &std::path::Path, out_dir: &std::path::Path) -> Result<String, String> {+ let pair = open_pair(before, after).map_err(|e| e.to_string())?;+ let overlay = plan(&pair.old_snapshot, &pair.new_snapshot, &pair.old_archive, &pair.new_archive);+ std::fs::create_dir_all(out_dir)+ .map_err(|e| format!("cannot write {}: {e}", out_dir.display()))?;+ let mut total = 0u64;+ for (n, range) in overlay.segments.iter().enumerate() {+ let name = format!("overlay-{n:04}.mamaps");+ let len = emit_segment(&pair.new_archive, &overlay, *range, &out_dir.join(&name))+ .map_err(|e| e.to_string())?;+ total += len;+ // SHA-256 over the finished segment for the manifest.+ let digest = sha_file(&out_dir.join(&name))?;+ println!("segment {name}: {len} bytes sha256={digest}");+ }+ // The tombstone + compat descriptor the publisher merges into the manifest.+ let descriptor = format!(+ "{{\"overlay_build_id\":\"{:#018x}\",\"base_build_id\":\"{:#018x}\",\"segments\":{},\"tombstones\":{}}}",+ 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}"))?;+ Ok(format!(+ "overlay: {} carries ({} segments), {} tombstones, {} bytes total",+ overlay.carries.len(),+ overlay.segments.len(),+ overlay.tombstones.len(),+ total,+ ))+}++/// Lowercase hex SHA-256 of a file, streamed (segments are hundreds of MB).+fn sha_file(path: &std::path::Path) -> Result<String, String> {+ use sha2::{Digest as _, Sha256};+ use std::io::Read as _;+ let mut hasher = Sha256::new();+ let mut file =+ std::fs::File::open(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?;+ let mut buf = [0u8; 1 << 20];+ loop {+ let n = file.read(&mut buf).map_err(|e| format!("cannot read {}: {e}", path.display()))?;+ if n == 0 {+ break;+ }+ hasher.update(&buf[..n]);+ }+ let digest = hasher.finalize();+ Ok(digest.iter().map(|b| format!("{b:02x}")).collect())+}
scripts/maps/tile_build/src/lib.rs
diff --git a/scripts/maps/tile_build/src/lib.rs b/scripts/maps/tile_build/src/lib.rsindex ea3239de83..3f53b9fd0c 100644--- a/scripts/maps/tile_build/src/lib.rs+++ b/scripts/maps/tile_build/src/lib.rs@@ -39,6 +39,8 @@ pub mod boolean; pub mod anon; pub mod churn;+pub mod manifest;+pub mod overlay; pub mod clip; pub mod geojson; pub mod geojson_extra;
scripts/maps/tile_build/src/manifest.rs
diff --git a/scripts/maps/tile_build/src/manifest.rs b/scripts/maps/tile_build/src/manifest.rsnew file mode 100644index 0000000000..c10204ea7e--- /dev/null+++ b/scripts/maps/tile_build/src/manifest.rs@@ -0,0 +1,156 @@+//! `manifest` — the `planet3.manifest.json` schema for incremental updates.+//!+//! The manifest is the only versioned thing the client fetches on a check+//! (bytes, not gigabytes): it pins the base archive, names the overlay+//! segments and sidecar sections, and carries the hashes that make each+//! download verifiable and resumable. See the plan file+//! (`maps_incremental_updates.plan.md`, Phase 1) for the rollout order.+//!+//! Wire form is plain JSON with fixed field names (documented on each+//! struct); the publisher (`upload_planet.py --manifest`) writes it, the+//! client parses it. No serde dependency: the host crate stays cargo-offline+//! buildable, and the schema is small enough to emit by hand.++/// Manifest format version. Bump when a client must understand new fields to+/// apply the overlay safely.+pub const MANIFEST_VERSION: u32 = 1;+/// Oldest manifest version this publisher writes. Clients below+/// `MIN_CLIENT_COMPAT` must full-download instead of applying overlays.+pub const MIN_CLIENT_COMPAT: u32 = 1;+/// Largest overlay segment the publisher emits. 512 MiB keeps peak transient+/// phone disk to one segment (the no-2x guarantee) while keeping the segment+/// count for a monthly overlay in the single digits.+pub const SEGMENT_CAP_BYTES: u64 = 512 * 1024 * 1024;+/// Chunk size for large sidecar sections (graph nodes/edges/intermediate,+/// transit). 32 MiB granularity lets the client skip unchanged chunks.+pub const SECTION_CHUNK_BYTES: u64 = 32 * 1024 * 1024;++/// The base archive this overlay applies to.+pub struct BaseRef {+ /// Download URL of the base `.mamaps` (today `planet3.mamaps`).+ pub url: String,+ /// `build_id` from the base header: the overlay refuses a mismatched base.+ pub build_id: u64,+ /// Base length in bytes (truncation check).+ pub len: u64,+}++/// One overlay segment file: a small self-contained `.mamaps` holding only+/// changed/added tile bodies plus tombstones, with overlay-relative offsets.+pub struct SegmentRef {+ /// Download URL of the segment file.+ pub url: String,+ /// Segment length in bytes.+ pub len: u64,+ /// Lowercase hex SHA-256 of the segment file.+ pub sha256: String,+ /// Sequence index (apply order; segments are independent but ordered).+ pub seq: u32,+}++/// One sidecar section published as an independently chunked file (large+/// kinds: graph nodes/edges/intermediate, transit) or ridden inside overlay+/// segments (small kinds — absent here).+pub struct SectionRef {+ /// Archive kind id (`ARCHIVE_KIND_*`).+ pub kind: u8,+ /// Download URL of the section file.+ pub url: String,+ /// Section length in bytes.+ pub len: u64,+ /// Lowercase hex SHA-256 of the whole section file.+ pub sha256: String,+ /// Chunk size in bytes (always [`SECTION_CHUNK_BYTES`]).+ pub chunk_size: u64,+ /// Lowercase hex SHA-256 per chunk, in order.+ pub chunk_hashes: Vec<String>,+}++/// The manifest: base pin + overlay sequence + sections + compat floor.+pub struct Manifest {+ /// [`MANIFEST_VERSION`].+ pub version: u32,+ /// Base archive reference.+ pub base: BaseRef,+ /// Overlay sequence number (monotonic; client applies when ahead).+ pub overlay_seq: u64,+ /// `overlay_build_id` (derived from base id + new OSM id + section hashes).+ pub overlay_build_id: u64,+ /// Overlay segments, ascending `seq`.+ pub segments: Vec<SegmentRef>,+ /// Independently chunked sidecar sections, ascending `kind`.+ pub sections: Vec<SectionRef>,+ /// [`MIN_CLIENT_COMPAT`].+ pub min_client: u32,+}++/// Render a [`Manifest`] as canonical JSON (fixed field order, no whitespace+/// beyond separators) so publishers and tests hash the same bytes.+pub fn render(manifest: &Manifest) -> String {+ let mut out = String::from("{");+ out.push_str(&format!("\"version\":{},", manifest.version));+ out.push_str("\"base\":{");+ out.push_str(&format!(+ "\"url\":{},\"build_id\":\"{:#018x}\",\"len\":{}",+ json_string(&manifest.base.url),+ manifest.base.build_id,+ manifest.base.len,+ ));+ out.push_str("},");+ out.push_str(&format!(+ "\"overlay_seq\":{},\"overlay_build_id\":\"{:#018x}\",",+ manifest.overlay_seq, manifest.overlay_build_id,+ ));+ out.push_str("\"segments\":[");+ for (n, s) in manifest.segments.iter().enumerate() {+ if n > 0 {+ out.push(',');+ }+ out.push_str(&format!(+ "{{\"url\":{},\"len\":{},\"sha256\":{},\"seq\":{}}}",+ json_string(&s.url),+ s.len,+ json_string(&s.sha256),+ s.seq,+ ));+ }+ out.push_str("],\"sections\":[");+ for (n, s) in manifest.sections.iter().enumerate() {+ if n > 0 {+ out.push(',');+ }+ out.push_str(&format!(+ "{{\"kind\":{},\"url\":{},\"len\":{},\"sha256\":{},\"chunk_size\":{},\"chunk_hashes\":[",+ s.kind,+ json_string(&s.url),+ s.len,+ json_string(&s.sha256),+ s.chunk_size,+ ));+ for (m, h) in s.chunk_hashes.iter().enumerate() {+ if m > 0 {+ out.push(',');+ }+ out.push_str(&json_string(h));+ }+ out.push_str("]}");+ }+ out.push_str(&format!("],\"min_client\":{}}}", manifest.min_client));+ out+}++/// A JSON string literal with the escapes this schema needs (URLs and hex+/// digests carry no control characters, but backslash/quote must survive).+fn json_string(s: &str) -> String {+ let mut out = String::with_capacity(s.len() + 2);+ out.push('"');+ for c in s.chars() {+ match c {+ '"' => out.push_str("\\\""),+ '\\' => out.push_str("\\\\"),+ _ => out.push(c),+ }+ }+ out.push('"');+ out+}
scripts/maps/tile_build/src/overlay.rs
diff --git a/scripts/maps/tile_build/src/overlay.rs b/scripts/maps/tile_build/src/overlay.rsnew file mode 100644index 0000000000..686796503f--- /dev/null+++ b/scripts/maps/tile_build/src/overlay.rs@@ -0,0 +1,305 @@+//! `overlay` — build patch-overlay segments from two `.mamaps` archives.+//!+//! Phase 1 server generator: input is the old (base) and new packed+//! archives, output is overlay segments only, never a rewritten base. Each+//! segment is a small self-contained `.mamaps` file written by the existing+//! [`StreamWriter`](crate::mamaps::write::StreamWriter) — same header,+//! dictionary, root, leaves and body format as the base — holding only+//! changed/added tile bodies with overlay-relative offsets. Deleted tiles+//! are tombstone tile ids in the overlay descriptor, not bodies (a+//! tombstone has no bytes to store).+//!+//! Insertion efficiency falls out of the layout: the base is never touched,+//! so a mid-world insert appends one body to an overlay segment plus one+//! overlay leaf entry. No base `offset_delta`, `base_data_offset`, sidecar+//! offset or footer movement.+//!+//! Bodies travel through [`MamapsArchive::tile_bytes`] (decompressed raw)+//! and back in through [`StreamWriter::append_encoded`] (re-compressed).+//! DEFLATE is deterministic, so a body the new build wrote compresses to+//! the same stored bytes here — the segment carries what the new archive+//! carries, byte for byte.+use crate::churn::{FileReader, Snapshot, snapshot};++use tilecodec::stream::RangeReader;++use crate::mamaps::archive::{ArchiveView, unified_build_id};+use crate::mamaps::read::MamapsArchive;+use crate::mamaps::write::Options;+use crate::manifest::SEGMENT_CAP_BYTES;+use crate::pmtiles::tile_zxy;+use crate::proto::{Result, err};++/// One tile the overlay must carry: its id and its new stored length (for+/// segment packing); the bytes are fetched at emit time.+#[derive(Debug, Clone, Copy)]+pub struct Carry {+ /// Tile id in the new archive.+ pub tile_id: u64,+ /// Stored body length in the new archive (compressed, if it says so).+ pub length: u32,+}++/// The overlay plan: which new bodies ship, which old tiles are tombstoned,+/// and how the bodies split into cap-sized segments.+pub struct OverlayPlan {+ /// New bodies to ship, ascending by tile id.+ pub carries: Vec<Carry>,+ /// Deleted tile ids (old-only), ascending. No bodies ship for these.+ pub tombstones: Vec<u64>,+ /// Segment boundaries as `carries` index ranges (each segment's stored+ /// bodies fit [`SEGMENT_CAP_BYTES`]).+ pub segments: Vec<(usize, usize)>,+ /// `overlay_build_id` for every segment header + the manifest.+ pub overlay_build_id: u64,+ /// Zoom range + bbox + flags carried from the new archive's header.+ pub header: SegmentHeader,+}++/// Header facts the segment writer needs from the new archive.+#[derive(Debug, Clone, Copy)]+pub struct SegmentHeader {+ /// New archive's `build_id` (pinned in the manifest as the overlay source).+ pub new_build_id: u64,+ /// Base archive's `build_id` (compat pin).+ pub base_build_id: u64,+ /// New archive's zoom range (every carried tile is inside it).+ pub min_zoom: u8,+ /// New archive's zoom range.+ pub max_zoom: u8,+ /// New archive's bbox, carried so segments describe the same world.+ pub bbox: (i32, i32, i32, i32),+ /// Whether the new archive's rings are validated.+ pub rings_validated: bool,+}++/// Diff two snapshots into an [`OverlayPlan`].+///+/// Interval merge over tile-id covers (both ascending): same tile + same+/// fingerprint skips wholesale (a run re-split with identical bytes ships+/// nothing — the overlay carries bodies, not index shapes). Same tile ++/// different fingerprint, or new-only cover = carry. Old-only cover =+/// tombstone. No per-tile expansion: planet's ~63M addressed tiles never+/// materialise as a map.+///+/// Carries split greedily at [`SEGMENT_CAP_BYTES`] of stored bodies; the+/// index overhead per segment is kilobytes against a 512 MiB cap. Carries+/// may repeat a body (dedup-shared across tiles); the segment writer+/// re-collapses those.+pub fn plan(+ old: &Snapshot,+ new: &Snapshot,+ old_archive: &MamapsArchive<impl RangeReader>,+ new_archive: &MamapsArchive<impl RangeReader>,+) -> OverlayPlan {+ let mut carries: Vec<Carry> = Vec::new();+ let mut tombstones: Vec<(u64, u64)> = Vec::new();+ let (mut i, mut j) = (0usize, 0usize);+ while i < old.entries.len() && j < new.entries.len() {+ let a = &old.entries[i];+ let b = &new.entries[j];+ let (a0, a1) = (a.tile_id, a.tile_id + u64::from(a.run_length));+ let (b0, b1) = (b.tile_id, b.tile_id + u64::from(b.run_length));+ if a1 <= b0 {+ tombstones.push((a0, a1));+ i += 1;+ } else if b1 <= a0 {+ push_carry_range(&mut carries, b, b0, b1);+ j += 1;+ } else if a.hash == b.hash {+ // Overlap with identical bytes: skip the overlap, advance the+ // cover that ends first.+ if a1 <= b1 {+ i += 1;+ }+ if b1 <= a1 {+ j += 1;+ }+ } else {+ // Overlap with different bytes: the overlap carries the new body.+ let (lo, hi) = (a0.max(b0), a1.min(b1));+ push_carry_span(&mut carries, b, lo, hi);+ if a1 <= b1 {+ i += 1;+ }+ if b1 <= a1 {+ j += 1;+ }+ }+ }+ for a in &old.entries[i..] {+ tombstones.push((a.tile_id, a.tile_id + u64::from(a.run_length)));+ }+ for b in &new.entries[j..] {+ push_carry_range(&mut carries, b, b.tile_id, b.tile_id + u64::from(b.run_length));+ }+ // Flatten tombstone ranges to ids (tombstones are rare: real deletes, not+ // coverage edges — a coverage-edge tombstone storm means the wrong pair).+ let mut tombstone_ids = Vec::new();+ for (lo, hi) in tombstones {+ tombstone_ids.extend(lo..hi);+ }+ let mut segments = Vec::new();+ let mut start = 0usize;+ let mut bytes = 0u64;+ for (n, c) in carries.iter().enumerate() {+ if n > start && bytes + u64::from(c.length) > SEGMENT_CAP_BYTES {+ segments.push((start, n));+ start = n;+ bytes = 0;+ }+ bytes += u64::from(c.length);+ }+ if start < carries.len() || carries.is_empty() {+ segments.push((start, carries.len()));+ }+ let new_hdr = &new_archive.header;+ let overlay_build_id = unified_build_id(+ b"overlay-v1",+ &old_archive.header.build_id.to_le_bytes(),+ &new_hdr.build_id.to_le_bytes(),+ &[],+ b"mamaps-overlay-v1",+ );+ OverlayPlan {+ carries,+ tombstones: tombstone_ids,+ segments,+ overlay_build_id,+ header: SegmentHeader {+ new_build_id: new_hdr.build_id,+ base_build_id: old_archive.header.build_id,+ min_zoom: new_hdr.min_zoom,+ max_zoom: new_hdr.max_zoom,+ bbox: (new_hdr.min_lon_e7, new_hdr.min_lat_e7, new_hdr.max_lon_e7, new_hdr.max_lat_e7),+ rings_validated: new_hdr.rings_validated(),+ },+ }+}++/// Append one carry per tile of `[lo, hi)` (all inside one new entry, so one body).+fn push_carry_span(carries: &mut Vec<Carry>, entry: &crate::churn::Entry, lo: u64, hi: u64) {+ // One carry per tile: the body repeats per tile here (dedup-shared+ // across tiles) and the segment writer re-collapses identical bodies.+ for t in lo..hi {+ carries.push(Carry { tile_id: t, length: entry.length });+ }+}++/// Append carries for a whole new cover `[lo, hi)` known to be new-only.+fn push_carry_range(carries: &mut Vec<Carry>, entry: &crate::churn::Entry, lo: u64, hi: u64) {+ push_carry_span(carries, entry, lo, hi);+}++/// Emit one segment file: fetch each carried tile's raw body from the new+/// archive and append it (ascending — carries are ascending by construction).+pub fn emit_segment<R: RangeReader>(+ new_archive: &MamapsArchive<R>,+ plan: &OverlayPlan,+ range: (usize, usize),+ out: &std::path::Path,+) -> Result<u64> {+ let options = Options {+ min_zoom: plan.header.min_zoom,+ max_zoom: plan.header.max_zoom,+ build_id: plan.overlay_build_id,+ compress: true,+ rings_validated: plan.header.rings_validated,+ min_lon_e7: plan.header.bbox.0,+ min_lat_e7: plan.header.bbox.1,+ max_lon_e7: plan.header.bbox.2,+ max_lat_e7: plan.header.bbox.3,+ ..Options::default()+ };+ let mut writer = crate::mamaps::write::StreamWriter::new(options)?;+ for carry in &plan.carries[range.0..range.1] {+ let (z, x, y) = tile_zxy(carry.tile_id);+ let Some(raw) = new_archive.tile_bytes(z, x as u32, y as u32)? else {+ return err(format!(+ "overlay carry tile {} vanished from the new archive",+ carry.tile_id,+ ));+ };+ writer.append_encoded(carry.tile_id, &raw)?;+ }+ writer.finish_to_path(out)?;+ Ok(std::fs::metadata(out)+ .map_err(|e| crate::proto::Error(format!("cannot stat {}: {e}", out.display())))?+ .len())+}++/// A sidecar section payload sliced out of the new archive, for chunked+/// section publishing (large kinds ship as files; the client skips+/// unchanged chunks by hash).+pub struct SectionPayload {+ /// Archive kind id.+ pub kind: u8,+ /// Verbatim payload bytes from the new archive.+ pub bytes: Vec<u8>,+}++/// Slice every sidecar section out of the new archive (tiles-only archives+/// yield none). Payloads are verbatim — no re-encode, no re-compress.+pub fn section_payloads(+ new_bytes_prefix_info: &NewArchiveSections,+) -> Vec<SectionPayload> {+ new_bytes_prefix_info.payloads.iter().map(|(kind, bytes)| SectionPayload {+ kind: *kind,+ bytes: bytes.clone(),+ }).collect()+}++/// The new archive's sidecar sections, read whole (they stream at publish+/// time; the generator box holds them transiently, like `mamaps_pack`).+pub struct NewArchiveSections {+ /// `(kind, payload bytes)` in kind order.+ pub payloads: Vec<(u8, Vec<u8>)>,+}++/// Read a packed archive's sidecar payloads whole, validated by+/// [`ArchiveView::parse`] (same checks the device loaders run).+pub fn read_new_sections(path: &std::path::Path) -> Result<NewArchiveSections> {+ let bytes = std::fs::read(path)+ .map_err(|e| crate::proto::Error(format!("cannot read {}: {e}", path.display())))?;+ let (header, _, _) = crate::mamaps::read::open_prefix(&bytes)?;+ let view = ArchiveView::parse(&bytes, &header)?;+ let mut payloads = Vec::with_capacity(view.entries.len());+ for e in &view.entries {+ payloads.push((e.kind, bytes[e.offset as usize..(e.offset + e.len) as usize].to_vec()));+ }+ Ok(NewArchiveSections { payloads })+}++/// Open both archives' tile indexes for planning + emitting.+pub struct ArchivePair {+ /// Base (old) archive over its file.+ pub old_archive: MamapsArchive<FileReader>,+ /// New archive over its file.+ pub new_archive: MamapsArchive<FileReader>,+ /// Base fingerprint snapshot.+ pub old_snapshot: Snapshot,+ /// New fingerprint snapshot.+ pub new_snapshot: Snapshot,+ /// Base file length (footer read).+ pub old_len: u64,+ /// New file length.+ pub new_len: u64,+}++/// Snapshot + open both archives. Range-based (no whole-file reads) except+/// through the fingerprint pass, which streams distinct bodies once.+pub fn open_pair(before: &std::path::Path, after: &std::path::Path) -> Result<ArchivePair> {+ let old_len = std::fs::metadata(before)+ .map_err(|e| crate::proto::Error(format!("cannot stat {}: {e}", before.display())))?+ .len();+ let new_len = std::fs::metadata(after)+ .map_err(|e| crate::proto::Error(format!("cannot stat {}: {e}", after.display())))?+ .len();+ let old_reader = FileReader::open(before)?;+ let new_reader = FileReader::open(after)?;+ let old_snapshot = snapshot(&old_reader, old_len)?;+ let new_snapshot = snapshot(&new_reader, new_len)?;+ let old_archive = MamapsArchive::open(FileReader::open(before)?)?;+ let new_archive = MamapsArchive::open(FileReader::open(after)?)?;+ Ok(ArchivePair { old_archive, new_archive, old_snapshot, new_snapshot, old_len, new_len })+}
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.rsnew file mode 100644index 0000000000..e6e594e75d--- /dev/null+++ b/scripts/maps/tile_build/tests/overlay_phase1.rs@@ -0,0 +1,172 @@+//! Phase 1 overlay gate: synthetic-archive tests for `tile_build::overlay`.+//!+//! Hermetic (no fixtures): tiny archives through the real `StreamWriter`,+//! planned and emitted through the real overlay path. Covers the three+//! invariants the no-2x + insertion-efficiency guarantees rest on.++#[cfg(test)]+mod tests {+ use tile_build::mamaps::body::{Body, Layer};+ use tile_build::mamaps::read::MamapsArchive;+ use tile_build::mamaps::write::Options;+ use tile_build::overlay::{emit_segment, open_pair, plan};+ use tile_build::proto::Result;+ use tile_build::{mamaps, pmtiles};+ use tilecodec::stream::RangeReader;++ struct MemReader {+ bytes: Vec<u8>,+ }++ impl RangeReader for MemReader {+ fn read(&self, offset: u64, length: u32) -> Result<Vec<u8>> {+ let start = offset as usize;+ let end = (start + length as usize).min(self.bytes.len());+ Ok(self.bytes[start..end].to_vec())+ }+ }++ fn ids(z: u8, n: u64) -> Vec<u64> {+ let mut out: Vec<u64> =+ (0..n).map(|k| pmtiles::tile_id(z, k % (1 << z), k / (1 << z))).collect();+ out.sort_unstable();+ out+ }++ fn body_with_layers(layer_count: u8) -> Body {+ let mut body = Body::new(tile_build::mamaps::body::DEFAULT_EXTENT);+ for id in 0..layer_count {+ body.layers.push(Layer::new(id));+ }+ body+ }++ fn archive(ids: &[u64], variant: u8) -> Vec<u8> {+ let options = Options {+ min_zoom: 0,+ max_zoom: 14,+ build_id: u64::from(variant),+ compress: true,+ ..Options::default()+ };+ let mut writer = mamaps::write::StreamWriter::new(options).expect("options");+ for (n, id) in ids.iter().enumerate() {+ let layers: u8 = if variant == 0 { 1 } else { 1 + (n % 2) as u8 };+ writer.append(*id, &body_with_layers(layers)).expect("append");+ }+ writer.finish().expect("finish")+ }++ fn open(bytes: &[u8]) -> MamapsArchive<MemReader> {+ MamapsArchive::open(MemReader { bytes: bytes.to_vec() }).expect("open")+ }++ /// The plan's core promise: one tile's bytes changing plans exactly that+ /// tile's new body, and the emitted segment serves it back.+ #[test]+ fn a_changed_tile_round_trips_through_a_segment() {+ let all = ids(5, 16);+ let before = archive(&all, 0);+ let after = archive(&all, 1);+ let dir = std::env::temp_dir().join(format!(+ "overlay-roundtrip-{}-{}",+ std::process::id(),+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .expect("clock")+ .as_nanos(),+ ));+ std::fs::create_dir_all(&dir).expect("fixture dir");+ std::fs::write(dir.join("before.mamaps"), &before).expect("fixture before");+ std::fs::write(dir.join("after.mamaps"), &after).expect("fixture after");+ let pair = open_pair(&dir.join("before.mamaps"), &dir.join("after.mamaps"))+ .expect("open pair");+ let overlay = plan(&pair.old_snapshot, &pair.new_snapshot, &pair.old_archive, &pair.new_archive);+ // Variant 1 alternates 1/2 layers: the 8 odd tiles carry new bodies.+ assert_eq!(overlay.carries.len(), 8, "the 8 odd tiles carry");+ assert!(overlay.tombstones.is_empty(), "nothing deleted");+ assert_eq!(overlay.segments.len(), 1, "tiny overlay is one segment");+ let out = dir.join("overlay-0000.mamaps");+ emit_segment(&pair.new_archive, &overlay, overlay.segments[0], &out)+ .expect("emit");+ // The segment opens as a real archive and serves every carried tile+ // with the NEW bytes.+ let segment = MamapsArchive::open(tile_build::churn::FileReader::open(&out).expect("open"))+ .expect("segment opens");+ let new_archive = open(&after);+ for carry in &overlay.carries {+ let (z, x, y) = tile_build::pmtiles::tile_zxy(carry.tile_id);+ let got = segment+ .tile_bytes(z, x as u32, y as u32)+ .expect("segment read")+ .expect("carried tile present");+ let want = new_archive+ .tile_bytes(z, x as u32, y as u32)+ .expect("new read")+ .expect("new tile present");+ assert_eq!(got, want, "segment serves the new bytes");+ }+ // And the base file is byte-untouched (insertion efficiency: no+ // rewrite, no fixup — the test re-reads the file it wrote).+ assert_eq!(std::fs::read(dir.join("before.mamaps")).expect("reread"), before);+ let _ = std::fs::remove_dir_all(&dir);+ }++ /// Deleted tiles plan tombstones, not carries: no body ships for a tile+ /// with no new bytes.+ #[test]+ fn deleted_tiles_plan_tombstones_not_carries() {+ let grown = ids(3, 12);+ let base = grown[..8].to_vec();+ let before = archive(&base, 0);+ let after = archive(&grown, 0);+ let dir = std::env::temp_dir().join(format!(+ "overlay-tombstone-{}-{}",+ std::process::id(),+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .expect("clock")+ .as_nanos(),+ ));+ std::fs::create_dir_all(&dir).expect("fixture dir");+ std::fs::write(dir.join("before.mamaps"), &before).expect("fixture before");+ std::fs::write(dir.join("after.mamaps"), &after).expect("fixture after");+ let pair = open_pair(&dir.join("before.mamaps"), &dir.join("after.mamaps"))+ .expect("open pair");+ let overlay = plan(&pair.old_snapshot, &pair.new_snapshot, &pair.old_archive, &pair.new_archive);+ assert_eq!(overlay.carries.len(), 4, "the 4 new tiles carry");+ assert!(overlay.tombstones.is_empty(), "nothing deleted going up");+ let back = plan(&pair.new_snapshot, &pair.old_snapshot, &pair.new_archive, &pair.old_archive);+ assert!(back.carries.is_empty(), "going down carries nothing");+ assert_eq!(back.tombstones.len(), 4, "the 4 dropped tiles tombstone");+ let _ = std::fs::remove_dir_all(&dir);+ }++ /// The manifest renders canonical JSON with the fields the client gates on.+ #[test]+ fn the_manifest_renders_its_schema() {+ let manifest = tile_build::manifest::Manifest {+ version: tile_build::manifest::MANIFEST_VERSION,+ base: tile_build::manifest::BaseRef {+ url: "https://data.maproj.org/planet3.mamaps".to_string(),+ build_id: 0x1234,+ len: 78017648928,+ },+ overlay_seq: 7,+ overlay_build_id: 0xabcd,+ segments: vec![tile_build::manifest::SegmentRef {+ url: "https://data.maproj.org/overlays/0007-0000.mamaps".to_string(),+ len: 123456,+ sha256: "abc".to_string(),+ seq: 0,+ }],+ sections: vec![],+ 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"] {+ 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 7150263115..bd247f55c5 100644--- a/scripts/maps/upload_planet.py+++ b/scripts/maps/upload_planet.py@@ -1,12 +1,18 @@ """Upload any local file to R2 as planet3.mamaps (bucket: maps). Usage: python upload_planet.py <local-file>+ python upload_planet.py --manifest <overlay-dir> --overlay-seq N --base-build-id HEX Verifies server-side size matches, then deletes nothing local. Progress prints every ~1 GB. Serves https://data.maproj.org/planet3.mamaps, which the apps' basemap URLs point at (library/map urls.rs, maps MapTileCache.kt). +The --manifest form publishes a patch-overlay update: it uploads each+overlay-*.mamaps segment from the overlay dir under overlays/<seq>/,+then writes planet3.manifest.json (base pin + segment list + hashes).+The manifest is the only file the client fetches on a check.+ SECURITY: credentials/config come from ENVIRONMENT VARIABLES, never baked into this file (the analysis/ original carried hardcoded keys and must stay gitignored there). Never paste keys on the command line — `export`@@ -18,7 +24,10 @@ Required env: R2_SECRET_ACCESS_KEY R2 secret access key Optional env: R2_BUCKET Default: maps+ R2_CDN Default: https://data.maproj.org (URL prefix written into the manifest) """+import hashlib+import json import os import sys import threading@@ -28,13 +37,21 @@ from boto3.s3.transfer import TransferConfig BUCKET = os.environ.get("R2_BUCKET", "maps") KEY = "planet3.mamaps"+MANIFEST_KEY = "planet3.manifest.json"+CDN = os.environ.get("R2_CDN", "https://data.maproj.org") PART_SIZE = 100 * 1024 * 1024 # 100 MB parts, 10-way concurrency +MANIFEST_VERSION = 1+MIN_CLIENT_COMPAT = 1+ def main() -> int:+ if len(sys.argv) >= 2 and sys.argv[1] == "--manifest":+ return publish_manifest(sys.argv[2:]) if len(sys.argv) != 2: print(f"usage: {os.path.basename(sys.argv[0])} <local-file>", flush=True)+ print(f" or: {os.path.basename(sys.argv[0])} --manifest <overlay-dir> --overlay-seq N --base-build-id HEX [--base-len N]", flush=True) return 2 missing = [v for v in ("R2_ENDPOINT", "R2_ACCESS_KEY_ID", "R2_SECRET_ACCESS_KEY") if not os.environ.get(v)]@@ -86,5 +103,110 @@ def main() -> int: return 0 if remote == size else 2 +def publish_manifest(argv: list) -> int:+ """Upload overlay segments + write planet3.manifest.json.++ Args: <overlay-dir> --overlay-seq N --base-build-id HEX [--base-len N]+ The overlay dir holds overlay-*.mamaps (from mamaps_overlay) whose+ descriptor overlay.json carries the overlay_build_id. Segments upload+ to overlays/<seq>/overlay-SSSS.mamaps; the manifest lists their CDN+ URLs + lengths + SHA-256. Sections (chunked sidecars) ride the same+ manifest when present as <kind>.section files (not yet emitted).+ """+ import argparse+ ap = argparse.ArgumentParser()+ ap.add_argument("overlay_dir")+ ap.add_argument("--overlay-seq", type=int, required=True)+ ap.add_argument("--base-build-id", required=True,+ help="hex base build_id the overlay applies to, e.g. 0x0355...")+ ap.add_argument("--base-len", type=int, default=None,+ help="base length in bytes (else read from overlay.json sidecar)")+ args = ap.parse_args(argv)+ missing = [v for v in ("R2_ENDPOINT", "R2_ACCESS_KEY_ID", "R2_SECRET_ACCESS_KEY")+ if not os.environ.get(v)]+ if missing:+ print(f"missing env: {', '.join(missing)} (see module docstring)", flush=True)+ return 2+ overlay_dir = args.overlay_dir+ descriptor_path = os.path.join(overlay_dir, "overlay.json")+ try:+ descriptor = json.load(open(descriptor_path))+ except (OSError, ValueError) as e:+ print(f"cannot read {descriptor_path}: {e} (run mamaps_overlay first)", flush=True)+ return 2+ s3 = boto3.client(+ "s3",+ endpoint_url=os.environ["R2_ENDPOINT"],+ aws_access_key_id=os.environ["R2_ACCESS_KEY_ID"],+ aws_secret_access_key=os.environ["R2_SECRET_ACCESS_KEY"],+ region_name="auto",+ )+ config = TransferConfig(+ multipart_threshold=PART_SIZE,+ multipart_chunksize=PART_SIZE,+ max_concurrency=10,+ use_threads=True,+ )+ segments = []+ for name in sorted(os.listdir(overlay_dir)):+ if not (name.startswith("overlay-") and name.endswith(".mamaps")):+ continue+ local = os.path.join(overlay_dir, name)+ key = f"overlays/{args.overlay_seq:04d}/{name}"+ size = os.path.getsize(local)+ print(f"uploading {local} ({size / 1e6:.1f} MB) to s3://{BUCKET}/{key}", flush=True)+ try:+ s3.upload_file(local, BUCKET, key, Config=config)+ except Exception as e:+ print(f"UPLOAD FAILED: {e}", flush=True)+ return 1+ remote = s3.head_object(Bucket=BUCKET, Key=key)["ContentLength"]+ if remote != size:+ print(f"size mismatch for {key}: remote {remote} vs local {size}", flush=True)+ return 2+ digest = sha256_file(local)+ seq = int(name[len("overlay-"):len("overlay-") + 4])+ segments.append({+ "url": f"{CDN}/{key}",+ "len": size,+ "sha256": digest,+ "seq": seq,+ })+ if not segments:+ print(f"no overlay-*.mamaps in {overlay_dir}", flush=True)+ return 2+ manifest = {+ "version": MANIFEST_VERSION,+ "base": {+ "url": f"{CDN}/{KEY}",+ "build_id": args.base_build_id,+ "len": args.base_len or 0,+ },+ "overlay_seq": args.overlay_seq,+ "overlay_build_id": descriptor.get("overlay_build_id", "0x0"),+ "segments": segments,+ "sections": [],+ "min_client": MIN_CLIENT_COMPAT,+ }+ body = json.dumps(manifest, indent=1).encode()+ s3.put_object(Bucket=BUCKET, Key=MANIFEST_KEY, Body=body,+ ContentType="application/json")+ print(f"wrote s3://{BUCKET}/{MANIFEST_KEY} "+ f"({len(segments)} segments, overlay_build_id={manifest['overlay_build_id']})",+ flush=True)+ return 0+++def sha256_file(path: str) -> str:+ h = hashlib.sha256()+ with open(path, "rb") as f:+ while True:+ chunk = f.read(1 << 20)+ if not chunk:+ break+ h.update(chunk)+ return h.hexdigest()++ if __name__ == "__main__": sys.exit(main())