Modern Apps git

← Modern-Apps.git

maps: content-based archive build_id, no path or mtime (#perf)

Commit
21cbeba8bc915f1ef38f28d5af966ff1d643613c
Author
Vayun Mathur <[email protected]>
When
2026-11-11 22:05 UTC (24 days ago)
Parents
33b9128
Bug: a world.mamaps built on a vast.ai box differed from the devvm
build (sha 9f810344... vs 73e488ee..., same size 81,331,811,296 B)
from the same code and byte-identical graph, POI and transit inputs.
mamaps_build's derive_build_id hashed the input pbf's absolute path
and mtime. The header build_id (0xe80b0bceb26fb216 vs
0x2ab5ba5833e54438) moved, and the archive bytes moved with it.

New derivation (documented on derive_build_id and content_build_id):

  header build_id = content_build_id(seed, tile digest)
  content_build_id(s, d) = mix64(mix64(s ^ K) ^ d), where mix64 is
    SplitMix64's finaliser and K is a constant
  tile digest = fold over every appended tile, in append order
    (repeats and dedup hits included), of tile id, stored length
    and FNV-1a 64 of the stored body (the dedup key the encoder
    already computes): d = mix64(d ^ id); d = mix64(d ^ len<<<32);
    d = mix64(d ^ body_hash)
  seed = FNV-1a 64 over, in order:
    "mamaps_build/18" (tool revision, bumped from 17)
    the archive FORMAT_VERSION
    the region name
    content fingerprints of all five inputs
      (osm_ingest::fingerprint, length + first/last 4 MiB):
      - the .osm.pbf; its first blob is the OSMHeader block with the
        replication timestamp and sequence, always inside the first
        4 MiB
      - the coastline .shp (the only shapefile part read)
      - the graph dir: every regular file by relative name, which
        includes the overlay outputs and blob_kinds.bin; dot-files
        skipped
      - the transit routes
      - the DEM
    layer flags, zoom range, simplification factor, stage-A
    feature count, schema kind count
    body encoding: "bodies/v10", or "bodies/v8" under --v8-bodies

Identical inputs and code give an identical id on any machine or
path. Any changed input changes the seed, and any changed tile byte
changes the digest. Readers key caches on this id, so both halves
err on the side of changing it.

Implementation:
- tilecodec Options::build_id_from_content (default off, so other
  writers are unchanged). StreamWriter keeps the running digest in
  push. prefix() writes header_build_id(). content_build_id is
  public.
- mamaps_build: input_digests() + the new derive_build_id; the writer
  sets build_id_from_content. The final log line prints the header id
  read back from the archive, plus the seed.
- MAMAPS_V8, an environment variable that changed output bytes,
  becomes the --v8-bodies flag and is folded into the seed.

App and overlay check (maps/planet4): the app treats build_id as
opaque. It is used in the tile cache origin marker
(CACHE_FORMAT|URL|build_id) and in MapOverlay's base pin, where the
manifest's base.build_id must equal the base file's header bytes
16..24 and base.len its length. Neither assumes how the id is
derived. tile_build's overlay and mamaps_pack derive their own ids
from the header ids (unified_build_id), so they inherit content
determinism. Effect: the next planet gets a new id, so overlay
manifests pinned to today's base stop matching it, as with any new
base. Rebuilds with identical content now keep their id, so caches
stay valid instead of being invalidated by a path or mtime.

Proof (all heavy runs under flock + MemoryMax=60G scope):
- The full planet_build tool chain (road_graph, road_overlay,
  transit_shapes, poi_extract, mamaps_build, mamaps_pack) was run
  twice from reflinked input copies. A: ~/planet-opt/runs/repro/...
  with mtime now. B: ~/planet-opt/runs/repro-alt/some/other/place/...
  with mtime 2001-02-03.
  - CA (--region california): all 19 output files identical (graph/*
    incl. blob_kinds.bin, poi/*, routes, tiles.mamaps, world.mamaps,
    .sha256). build_id 0x7a83a258b099c75c both.
  - US West (--region world, MAPS_FORCE_FILE_SPILL=1): all 19
    identical, build_id 0xd634c020354418c6 both.
  - The same CA pair with main's binaries: blob_kinds.bin,
    tiles.mamaps, world.mamaps and its .sha256 differ (build_id
    0xf03087c26e687e5c vs 0xdc26513747494c4f). No other output
    differed, so these were the only environment leaks.
  - road_graph, road_overlay and poi_extract at MAPS_THREADS=8 match
    the default thread count (15 files).
- Tests: a_build_id_follows_the_inputs_that_decide_the_output
  (stable; the same bytes elsewhere and later give the same digests;
  each of the five inputs and each parameter changes the id; the tile
  digest changes the header id) and a_content_build_id_follows_the_
  tiles (tilecodec).
- Suites: mamaps_build 292, osm_ingest 313, tile_build 199,
  gtfs_ingest 108 passed. tilecodec 187 passed, plus the same 4
  failures that are on main.

Diff

library/tilecodec/src/main/rust/src/mamaps/write.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/write.rs b/library/tilecodec/src/main/rust/src/mamaps/write.rsindex f95db94b05..f8ede99efa 100644--- a/library/tilecodec/src/main/rust/src/mamaps/write.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/write.rs@@ -62,5 +62,5 @@ pub use codec::{compress_body, compress_body_with, hash64}; #[cfg(feature = "write")] pub use codec::compress_body_zstd; pub use options::Options;-pub use writer::StreamWriter;+pub use writer::{content_build_id, StreamWriter}; pub(crate) use writer::Pending;
library/tilecodec/src/main/rust/src/mamaps/write/options.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/write/options.rs b/library/tilecodec/src/main/rust/src/mamaps/write/options.rsindex 99dfab8388..fd0c1009f5 100644--- a/library/tilecodec/src/main/rust/src/mamaps/write/options.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/write/options.rs@@ -13,6 +13,11 @@ pub struct Options {     /// The writer does not compute it: only the generator knows those inputs. It does carry it, and     /// a reader's cache marker is `CACHE_FORMAT | URL | build_id`.     pub build_id: u64,+    /// Fold the archive's own tile content into the header's build id: when set, the id written+    /// is [`content_build_id`](super::content_build_id)`(build_id, digest)`, where the digest runs+    /// over every appended tile in order (tile id, stored length, stored-body hash). Identical+    /// tiles and seed give an identical id on any machine; any changed tile byte changes it.+    pub build_id_from_content: bool,     pub compress: bool,     /// Store each leaf as one raw-DEFLATE frame rather than raw fixed-stride entries.     ///@@ -54,6 +59,7 @@ impl Default for Options {             min_zoom: 0,             max_zoom: 14,             build_id: 0,+            build_id_from_content: false,             compress: true,             compress_leaves: true,             rings_validated: false,
library/tilecodec/src/main/rust/src/mamaps/write/tests.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/write/tests.rs b/library/tilecodec/src/main/rust/src/mamaps/write/tests.rsindex f7099e6dd3..8a9503b8dc 100644--- a/library/tilecodec/src/main/rust/src/mamaps/write/tests.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/write/tests.rs@@ -28,3 +28,27 @@ use crate::mamaps::body::Body;         assert_eq!(bytes[7], crate::mamaps::header::FORMAT_VERSION_V9, "a build is version byte 9");         assert_eq!(header.wire_len(), 128);     }++    /// `build_id_from_content`: the header id is the seed folded with the digest of every tile.+    /// The same tiles give the same id; one changed tile, or another seed, changes it; and with the+    /// option off the seed is written as given.+    #[test]+    fn a_content_build_id_follows_the_tiles() {+        let id_of = |seed: u64, extent: u16, from_content: bool| {+            let mut w = StreamWriter::new(Options {+                build_id: seed,+                build_id_from_content: from_content,+                ..Options::default()+            })+            .expect("options");+            w.append(tile_id(0, 0, 0), &tiny_body()).expect("append");+            w.append(tile_id(1, 0, 0), &Body::new(extent)).expect("append");+            let bytes = w.finish().expect("finish");+            Header::parse(&bytes).expect("header").build_id+        };+        let base = id_of(42, 4096, true);+        assert_eq!(base, id_of(42, 4096, true), "stable");+        assert_ne!(base, id_of(42, 2048, true), "a changed tile must change the id");+        assert_ne!(base, id_of(43, 4096, true), "a changed seed must change the id");+        assert_eq!(id_of(42, 4096, false), 42, "off: the seed as given");+    }
library/tilecodec/src/main/rust/src/mamaps/write/writer.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/write/writer.rs b/library/tilecodec/src/main/rust/src/mamaps/write/writer.rsindex ed48dfa958..eea264e3ec 100644--- a/library/tilecodec/src/main/rust/src/mamaps/write/writer.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/write/writer.rs@@ -7,6 +7,30 @@ use crate::mamaps::index::{LeafEntry, RootEntry, self}; use crate::proto::{Result, err}; use std::collections::HashMap; +/// Start value of the running tile digest.+const CONTENT_DIGEST_SEED: u64 = 0x6d61_6d61_7073_2f31; // "mamaps/1"++/// SplitMix64's finaliser: a full-avalanche 64-bit mix.+fn mix64(mut z: u64) -> u64 {+    z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);+    z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);+    z ^ (z >> 31)+}++/// One tile into the running content digest: order-dependent, every field avalanched.+fn digest_step(digest: u64, tile_id: u64, stored_len: u64, body_hash: u64) -> u64 {+    let d = mix64(digest ^ tile_id);+    let d = mix64(d ^ stored_len.rotate_left(32));+    mix64(d ^ body_hash)+}++/// The header build id for [`Options::build_id_from_content`]: the generator's seed (its inputs+/// and parameters) mixed with the digest of every tile the archive holds. Public so a tool can+/// document and test the derivation.+pub fn content_build_id(seed: u64, content_digest: u64) -> u64 {+    mix64(mix64(seed ^ 0x6275_696c_645f_6964) ^ content_digest)+}+ /// The dedup index's map: keyed by `(FNV-1a hash, length)`, which is already well mixed, so the /// default SipHash only costs time on a lookup made for every appended tile. Never iterated for /// output, so the hasher cannot move a byte.@@ -67,6 +91,8 @@ pub struct StreamWriter {     /// spill on every append, which is how the shortcut is held to the file's answer rather than     /// trusted to stay in step with it.     last_body: std::sync::Arc<Vec<u8>>,+    /// Running digest of every appended tile, for [`Options::build_id_from_content`].+    content: u64,     /// Distinct bodies appended since the last [`Self::sweep_dedup`] pass. Bounds how stale the     /// dedup index may get between sweeps; see the sweep for why staleness is memory.     distinct_since_sweep: u64,@@ -150,6 +176,7 @@ impl StreamWriter {             seen_order: std::collections::VecDeque::new(),             last_id: None,             last_body: Default::default(),+            content: CONTENT_DIGEST_SEED,             distinct_since_sweep: 0,             tiles_addressed: 0,             distinct: 0,@@ -274,6 +301,8 @@ impl StreamWriter {     }      fn push_shared(&mut self, tile_id: u64, stored: std::sync::Arc<Vec<u8>>, hash: u64) -> Result<()> {+        // Every tile, repeats and dedup hits included, in append order: the archive's content.+        self.content = digest_step(self.content, tile_id, stored.len() as u64, hash);         let (z, _, _) = crate::pmtiles::tile_zxy(tile_id);         if z < self.options.min_zoom || z > self.options.max_zoom {             return err(format!(@@ -551,6 +580,7 @@ impl StreamWriter {             seen_order: std::collections::VecDeque::new(),             last_id: None,             last_body: Default::default(),+            content: CONTENT_DIGEST_SEED,             distinct_since_sweep: 0,             tiles_addressed: entries.len() as u64,             distinct: entries.len() as u64,@@ -559,3 +589,15 @@ impl StreamWriter {         w.partition(capacity)     } }++impl StreamWriter {+    /// The build id the header carries: the generator's id, or, with+    /// [`Options::build_id_from_content`], [`content_build_id`] of it and the tile digest.+    pub fn header_build_id(&self) -> u64 {+        if self.options.build_id_from_content {+            content_build_id(self.options.build_id, self.content)+        } else {+            self.options.build_id+        }+    }+}
library/tilecodec/src/main/rust/src/mamaps/write/writer_extra.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/write/writer_extra.rs b/library/tilecodec/src/main/rust/src/mamaps/write/writer_extra.rsindex e7b2101712..ba0faa4eba 100644--- a/library/tilecodec/src/main/rust/src/mamaps/write/writer_extra.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/write/writer_extra.rs@@ -143,7 +143,7 @@ impl StreamWriter {             layer_count: dict::LAYERS.len() as u8,             min_zoom: self.options.min_zoom,             max_zoom: self.options.max_zoom,-            build_id: self.options.build_id,+            build_id: self.header_build_id(),             // The file is exactly header/dictionary/root/leaves/data.             file_len: data_offset + data_len,             dict_offset,
scripts/maps/mamaps_build/src/main.rs
diff --git a/scripts/maps/mamaps_build/src/main.rs b/scripts/maps/mamaps_build/src/main.rsindex 4700095036..b500be2ce9 100644--- a/scripts/maps/mamaps_build/src/main.rs+++ b/scripts/maps/mamaps_build/src/main.rs@@ -128,6 +128,7 @@ fn main() -> ExitCode {     let mut build_graph_to: Option<PathBuf> = None;     let mut build_poi_to: Option<PathBuf> = None;     let mut graph_ready_file: Option<PathBuf> = None;+    let mut v8_bodies = false;      let mut i = 1;     while i < args.len() {@@ -175,6 +176,12 @@ fn main() -> ExitCode {                 graph_ready_file = Some(PathBuf::from(v));                 2             }),+            // Dense v8 bodies instead of the v10 default (was the `MAMAPS_V8` environment+            // variable; a flag, so no environment value can change an output byte).+            "--v8-bodies" => {+                v8_bodies = true;+                Ok(1)+            }             "-h" | "--help" => {                 usage();                 return ExitCode::SUCCESS;@@ -220,6 +227,7 @@ fn main() -> ExitCode {         build_graph_to,         build_poi_to,         graph_ready_file,+        v8_bodies,     };     match run(&input, &out, &settings) {         Ok(()) => ExitCode::SUCCESS,@@ -255,6 +263,8 @@ struct RunSettings {     /// `--graph-ready-file`: start before the routing graph exists and wait for this file to     /// appear before the first stage that reads `--graph`. See [`GraphGate`].     graph_ready_file: Option<PathBuf>,+    /// `--v8-bodies`: encode dense v8 tile bodies instead of the v10 default. In the build id.+    v8_bodies: bool, }  include!("main_part1.rs");
scripts/maps/mamaps_build/src/main_part1.rs
diff --git a/scripts/maps/mamaps_build/src/main_part1.rs b/scripts/maps/mamaps_build/src/main_part1.rsindex 1983f6db04..ed17c22023 100644--- a/scripts/maps/mamaps_build/src/main_part1.rs+++ b/scripts/maps/mamaps_build/src/main_part1.rs@@ -175,14 +175,17 @@ fn run(     // cache. Derived rather than asked for, so a forgotten input cannot silently republish     // under the old one. The region is part of the id: a california and a world     // build from the same pbf are different archives.+    tiler::V8_BODIES.store(run.v8_bodies, std::sync::atomic::Ordering::Relaxed);+    let digests = input_digests(input, &run.coastline, &graph_dir, &run.transit_routes, &run.dem)?;     let build_id = derive_build_id(-        input,+        &digests,         layers,         min_zoom,         max_zoom,         simplification,         stats.features,         run.region.name(),+        run.v8_bodies,     );      // The DEM heightmap dataset. Loaded here (this is where I/O belongs) and@@ -311,8 +314,10 @@ fn run(     let archive_len = std::fs::metadata(out)         .map(|m| m.len())         .map_err(|e| format!("cannot stat {}: {e}", out.display()))?;+    // The header's id: the seed above folded with the archive's tile digest by the writer.+    let header_id = read_header_build_id(out)?;     println!(-        "\nwrote {} ({archive_len} bytes, build_id {build_id:#018x})",+        "\nwrote {} ({archive_len} bytes, build_id {header_id:#018x}, seed {build_id:#018x})",         out.display(),     );     Ok(())@@ -329,47 +334,101 @@ fn scratch_path(out: &std::path::Path) -> PathBuf {     PathBuf::from(p) } -/// Hash the inputs that decide what an archive contains.+/// The build id in a finished archive's header.+fn read_header_build_id(out: &std::path::Path) -> Result<u64, String> {+    use std::io::Read;+    let mut head = vec![0u8; tilecodec::mamaps::header::HEADER_LEN];+    std::fs::File::open(out)+        .and_then(|mut f| f.read_exact(&mut head))+        .map_err(|e| format!("cannot read back {}: {e}", out.display()))?;+    tilecodec::mamaps::header::Header::parse(&head)+        .map(|h| h.build_id)+        .map_err(|e| format!("cannot parse {}: {e}", out.display()))+}++/// Content fingerprints of every file the archive is built from ([`input_digests`]).+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) struct InputDigests {+    pub pbf: u64,+    pub coastline: u64,+    pub graph: u64,+    pub transit_routes: u64,+    pub dem: u64,+}++/// Fingerprint every input by content ([`osm_ingest::fingerprint`]): never a path or an mtime. ///-/// The input's **length and modification time** rather than its bytes: digesting 1.3 GB to decide a-/// cache key would double the build's I/O for a number that only has to change when the data does.-/// A rebuild from an unchanged file therefore keeps its id, which is what makes a byte-identical-/// rebuild byte-identical.+/// - `.osm.pbf`: length + first and last 4 MiB. The first blob is the `OSMHeader` block (with the+///   replication timestamp and sequence number), always well inside the first 4 MiB.+/// - coastline: the `.shp` (the only part of the shapefile read).+/// - graph: every regular file in the directory, by relative name (dot-files such as+///   `planet_build.sh`'s `.ready` signal skipped) -- metadata, nodes, edges, lanes, names, the+///   overlay outputs and `blob_kinds.bin`.+/// - transit routes and DEM: length + first and last 4 MiB.+pub(crate) fn input_digests(+    pbf: &std::path::Path,+    coastline: &std::path::Path,+    graph: &std::path::Path,+    transit_routes: &std::path::Path,+    dem: &std::path::Path,+) -> Result<InputDigests, String> {+    use osm_ingest::fingerprint::{dir_fingerprint, file_fingerprint};+    let file = |p: &std::path::Path| {+        file_fingerprint(p).map_err(|e| format!("cannot fingerprint {}: {e}", p.display()))+    };+    Ok(InputDigests {+        pbf: file(pbf)?,+        coastline: file(coastline)?,+        graph: dir_fingerprint(graph)+            .map_err(|e| format!("cannot fingerprint {}: {e}", graph.display()))?,+        transit_routes: file(transit_routes)?,+        dem: file(dem)?,+    })+}++/// The generator's build id: the seed the archive writer then mixes with the digest of every tile+/// it holds (`Options::build_id_from_content`, `tilecodec::mamaps::write::content_build_id`), so+/// the header's id is ///-/// The leading generator revision has to be bumped whenever this crate changes what it *puts* in an-/// archive for the same input, because readers cache byte ranges under `(url, build_id)` and the-/// URL is deliberately stable across republishes. A device with a warm cache would otherwise keep-/// serving the old archive's bytes forever. See `library/map/.../tile/source.rs`.-fn derive_build_id(-    input: &std::path::Path,+/// ```text+/// header build_id = content_build_id(derive_build_id(..), tile digest)+/// tile digest     = fold over every appended tile, in order, of (tile id, stored length,+///                   FNV-1a 64 of the stored body)+/// ```+///+/// The seed is FNV-1a 64 over, in order: the tool revision tag `mamaps_build/18`; the archive+/// format version; the region name; the five input fingerprints ([`InputDigests`]: pbf,+/// coastline, graph, transit routes, DEM); the layer flags and zoom range; the simplification+/// factor; the stage-A feature count; the schema table's kind count; and the body encoding (v10,+/// or v8 under `--v8-bodies`).+///+/// Nothing environmental goes in -- no path, mtime, host, user or clock -- so identical inputs and+/// identical code give an identical id on any machine; a changed input changes the seed, and any+/// changed tile changes the digest. Readers key caches on this id, so both halves err on the side+/// of changing it.+#[allow(clippy::too_many_arguments)]+pub(crate) fn derive_build_id(+    inputs: &InputDigests,     layers: schema::Layers,     min_zoom: u8,     max_zoom: u8,     simplification: f64,     features: u64,     region: &str,+    v8_bodies: bool, ) -> u64 {-    let mut h = 0xcbf2_9ce4_8422_2325u64;-    let mut eat = |bytes: &[u8]| {-        for &b in bytes {-            h ^= b as u64;-            h = h.wrapping_mul(0x100_0000_01b3);-        }-    };-    // Revision 17 fixes the missing lane byte in mixed landtype Road records (#821).-    // The corrected rebuild must invalidate cached ranges from the malformed archive.-    eat(b"mamaps_build/17");-    eat(region.as_bytes());-    eat(input.to_string_lossy().as_bytes());-    if let Ok(meta) = std::fs::metadata(input) {-        eat(&meta.len().to_le_bytes());-        if let Ok(time) = meta.modified() {-            if let Ok(since) = time.duration_since(std::time::UNIX_EPOCH) {-                eat(&since.as_secs().to_le_bytes());-            }-        }+    let mut h = osm_ingest::fingerprint::Fnv::default();+    // Revision 17 fixed the missing lane byte in mixed landtype Road records (#821).+    // Revision 18: the id is content-derived (input fingerprints + tile digest), no longer the+    // input's path and mtime.+    h.eat(b"mamaps_build/18");+    h.eat(&[tilecodec::mamaps::header::FORMAT_VERSION]);+    h.eat(region.as_bytes());+    h.eat(&[0]);+    for digest in [inputs.pbf, inputs.coastline, inputs.graph, inputs.transit_routes, inputs.dem] {+        h.eat_u64(digest);     }-    eat(&[+    h.eat(&[         u8::from(layers.landtype),         u8::from(layers.buildings),         u8::from(layers.roads),@@ -382,10 +441,11 @@ fn derive_build_id(         min_zoom,         max_zoom,     ]);-    eat(&simplification.to_le_bytes());-    eat(&features.to_le_bytes());+    h.eat(&simplification.to_le_bytes());+    h.eat_u64(features);     // The schema table's own version, so a remapped kind invalidates every cache even when the     // input has not moved.-    eat(&(tilecodec::mamaps::dict::KINDS.len() as u64).to_le_bytes());-    h+    h.eat_u64(tilecodec::mamaps::dict::KINDS.len() as u64);+    h.eat(if v8_bodies { b"bodies/v8" } else { b"bodies/v10" });+    h.finish() }
scripts/maps/mamaps_build/src/main_part2.rs
diff --git a/scripts/maps/mamaps_build/src/main_part2.rs b/scripts/maps/mamaps_build/src/main_part2.rsindex 2b6c803998..a1476a5ce9 100644--- a/scripts/maps/mamaps_build/src/main_part2.rs+++ b/scripts/maps/mamaps_build/src/main_part2.rs@@ -73,7 +73,7 @@ fn usage() {         \x20                   --dem HEIGHTMAPS.mdem\n\         \x20                   [--region california|world]\n\         \x20                   [--build-graph-to DIR] [--build-poi-to DIR]\n\-        \x20                   [--graph-ready-file PATH]\n\+        \x20                   [--graph-ready-file PATH] [--v8-bodies]\n\         \n\         \x20All six flags are required. Every build carries all 9 layers at\n\         \x20z0-14 as FORMAT_VERSION 8. --region filters roads/pois/buildings\n\@@ -300,29 +300,73 @@ mod tests {         );     } -    /// The id has to change when the data would, and not otherwise. A rebuild from an unchanged file-    /// keeps its id, which is what makes a byte-identical rebuild byte-identical.+    /// The id has to change when the data would, and not otherwise. A rebuild from unchanged+    /// inputs keeps its id -- wherever the inputs live and whenever they were touched -- which is+    /// what makes a byte-identical rebuild byte-identical.     #[test]     fn a_build_id_follows_the_inputs_that_decide_the_output() {-        let path = std::path::Path::new("nonexistent.osm.pbf");+        let dir = |name: &str| {+            let d = std::env::temp_dir().join(format!("mamaps_bid_{}_{name}", std::process::id()));+            let _ = std::fs::remove_dir_all(&d);+            std::fs::create_dir_all(d.join("graph")).unwrap();+            for (f, bytes) in [+                ("in.osm.pbf", &b"pbf bytes"[..]),+                ("coast.shp", b"shp bytes"),+                ("routes.geojsonseq", b"routes"),+                ("world.mdem", b"dem bytes"),+                ("graph/metadata.bin", b"graph meta"),+                ("graph/edges.bin", b"edges"),+            ] {+                std::fs::write(d.join(f), bytes).unwrap();+            }+            d+        };+        let digests = |d: &std::path::Path| {+            input_digests(+                &d.join("in.osm.pbf"),+                &d.join("coast.shp"),+                &d.join("graph"),+                &d.join("routes.geojsonseq"),+                &d.join("world.mdem"),+            )+            .unwrap()+        };         let all = schema::Layers::all();-        let base = derive_build_id(path, all, 0, 14, 1.0, 100, "world");-        assert_eq!(base, derive_build_id(path, all, 0, 14, 1.0, 100, "world"), "stable");-        for other in [-            derive_build_id(path, all, 0, 14, 2.0, 100, "world"),-            derive_build_id(path, all, 0, 14, 1.0, 101, "world"),-            derive_build_id(path, all, 0, 14, 1.0, 100, "california"),-            derive_build_id(-                std::path::Path::new("other.osm.pbf"),-                all,-                0,-                14,-                1.0,-                100,-                "world",-            ),-        ] {-            assert_ne!(base, other, "a changed input should change the id");+        let a = dir("a");+        let inputs = digests(&a);+        let base = derive_build_id(&inputs, all, 0, 14, 1.0, 100, "world", false);+        assert_eq!(base, derive_build_id(&inputs, all, 0, 14, 1.0, 100, "world", false), "stable");+        // The same bytes at another path, written later, with a `.ready` signal in the graph dir:+        // the same id.+        std::thread::sleep(std::time::Duration::from_millis(20));+        let b = dir("b");+        std::fs::write(b.join("graph/.ready"), b"").unwrap();+        assert_eq!(digests(&b), inputs, "place or time leaked into an input digest");+        // Every input's content and every parameter moves it.+        let mut others = vec![+            derive_build_id(&inputs, all, 0, 14, 2.0, 100, "world", false),+            derive_build_id(&inputs, all, 0, 14, 1.0, 101, "world", false),+            derive_build_id(&inputs, all, 0, 14, 1.0, 100, "california", false),+            derive_build_id(&inputs, all, 0, 13, 1.0, 100, "world", false),+            derive_build_id(&inputs, all, 0, 14, 1.0, 100, "world", true),+        ];+        for f in ["in.osm.pbf", "coast.shp", "routes.geojsonseq", "world.mdem", "graph/edges.bin"] {+            let c = dir("c");+            std::fs::write(c.join(f), b"changed content").unwrap();+            others.push(derive_build_id(&digests(&c), all, 0, 14, 1.0, 100, "world", false));+        }+        for (i, other) in others.iter().enumerate() {+            assert_ne!(base, *other, "change #{i} should change the id");+        }+        // The header id folds in the tile digest: same seed, different tiles, different id.+        use tilecodec::mamaps::write::content_build_id;+        assert_eq!(content_build_id(base, 1), content_build_id(base, 1));+        assert_ne!(content_build_id(base, 1), content_build_id(base, 2));+        assert_ne!(content_build_id(base, 1), content_build_id(base ^ 1, 1));+        for d in ["a", "b", "c"] {+            let _ = std::fs::remove_dir_all(+                std::env::temp_dir().join(format!("mamaps_bid_{}_{d}", std::process::id())),+            );         }     } 
scripts/maps/mamaps_build/src/tiler.rs
diff --git a/scripts/maps/mamaps_build/src/tiler.rs b/scripts/maps/mamaps_build/src/tiler.rsindex 3719505b69..f1fb4b23ee 100644--- a/scripts/maps/mamaps_build/src/tiler.rs+++ b/scripts/maps/mamaps_build/src/tiler.rs@@ -329,6 +329,9 @@ pub struct ZoomStats {     pub append_ms: u64, } +/// `--v8-bodies`: encode dense v8 bodies (set once by `main` before tiling).+pub static V8_BODIES: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);+ pub struct Settings {     pub build_id: u64,     /// Where one zoom's chunks go while they wait for the merge. See [`crate::tilespill`].
scripts/maps/mamaps_build/src/tiler_part1.rs
diff --git a/scripts/maps/mamaps_build/src/tiler_part1.rs b/scripts/maps/mamaps_build/src/tiler_part1.rsindex 48eca529da..94226e18a7 100644--- a/scripts/maps/mamaps_build/src/tiler_part1.rs+++ b/scripts/maps/mamaps_build/src/tiler_part1.rs@@ -52,6 +52,9 @@ fn writer_for(store: &Store, settings: &Settings) -> Result<StreamWriter> {         min_zoom: 0,         max_zoom: crate::DEFAULT_MAX_ZOOM,         build_id: settings.build_id,+        // The header carries the seed folded with the digest of every tile written: identical+        // tiles from identical inputs give an identical id anywhere (see `derive_build_id`).+        build_id_from_content: true,         compress: true,         // Stage C runs on every tile below, so the claim is true. It is what lets the renderer         // skip its repair pass โ€” and the renderer still keeps that pass, gated, because a claim is
scripts/maps/mamaps_build/src/tiler_part5.rs
diff --git a/scripts/maps/mamaps_build/src/tiler_part5.rs b/scripts/maps/mamaps_build/src/tiler_part5.rsindex b324f58be4..2b8f13b848 100644--- a/scripts/maps/mamaps_build/src/tiler_part5.rs+++ b/scripts/maps/mamaps_build/src/tiler_part5.rs@@ -299,8 +299,9 @@ fn encode_tile(     // v10 narrowed records + sparse side tables are the default: same     // geometry either way โ€” only the fixed records shrink โ€” so this     // changes bytes, never shapes. `MAMAPS_V8=1` opts back out to the-    // dense v8 bodies (escape hatch for bisecting a suspect build).-    let encoded_body = if std::env::var("MAMAPS_V8").is_ok() {+    // dense v8 bodies (escape hatch for bisecting a suspect build). A command-line flag+    // (`--v8-bodies`), never the environment, and part of the build id.+    let encoded_body = if crate::tiler::V8_BODIES.load(std::sync::atomic::Ordering::Relaxed) {         tilecodec::mamaps::body::serialize_into(&body, scratch)     } else {         tilecodec::mamaps::body::serialize_into_v10(&body, scratch)