Modern Apps git

← Modern-Apps.git

maps: blob-kinds sidecar guarded by content, not the pbf's mtime (#perf)

Commit
33b9128ee95a49c9136022ed4e61e390cda04d88
Author
Vayun Mathur <[email protected]>
When
2026-11-11 22:05 UTC (24 days ago)
Parents
bee3668
Bug: the same planet built on two machines produced different
outputs although every input was byte-identical. One of the two
causes was road_graph's graph/blob_kinds.bin, whose header carried
the input .osm.pbf's mtime (seconds and nanoseconds) as a staleness
guard. A copied or re-downloaded pbf changed the graph directory's
bytes, and mamaps_build then rejected the sidecar and scanned every
blob.

What changed:
- New osm_ingest::fingerprint module. file_fingerprint is FNV-1a 64
  over the file's length plus its first and last 4 MiB (or the whole
  file if it is no larger than 8 MiB). dir_fingerprint covers a
  directory's regular files by relative name, in name order; dot-files
  such as planet_build's .ready signal are skipped. Never a path, an
  mtime, an inode, a host or a user.
- blob_kinds.bin is now format MBK2 (MBK1 sidecars are rejected and
  fall back to a full scan). Its header is magic, blob count, source
  length, and a guard: FNV-1a 64 of the pbf's file_fingerprint plus
  every blob's (offset, size) from the blob index pass 1 already
  holds. An edit anywhere that resizes a blob, or any change in the
  first or last 4 MiB, invalidates it. A copy of the same bytes at
  another path, touched at another time, still matches, and the
  sidecar's bytes depend only on the pbf's bytes.
- mamaps_build logs whether the sidecar matched (and how many blobs
  pass 1 skipped), so a silent fallback is visible.

Audit across scripts/maps (road_graph, road_overlay, transit_shapes,
poi_extract, mamaps_build, mamaps_pack) and the tilecodec writers,
for paths, mtimes, clocks, pids, hosts, users and environment
variables that reach an output byte:
- blob_kinds.bin mtime: fixed here.
- mamaps_build's build_id hashed the input's absolute path and mtime:
  fixed in the next commit.
- MAMAPS_V8 (an env var that switched the body encoding): replaced by
  a flag in the next commit.
- Nothing else found. SystemTime/process::id appear only in tests and
  scratch-file names; file sizes feed spill-budget decisions only,
  which are byte-neutral; MAPS_THREADS/RAYON_NUM_THREADS/
  MAPS_PREFETCH_LANES/MAPS_ANON_SPILL/MAPS_FORCE_FILE_SPILL/
  MAPS_SCRATCH_DIR only change scheduling or scratch placement;
  TRANSIT_BUNDLE_DEBUG only prints. mamaps_pack's .sha256 line names
  the archive by the file name given on the command line, not by its
  location.

Verified, see the next commit for the end-to-end proof:
- Test fingerprints_follow_content_not_place_or_time.
- The extended blob-kinds round-trip test: a copy at another path
  with another mtime loads, and writes a byte-identical sidecar;
  same-length different bytes and a resized blob are rejected.
- A graph built from one copy of the CA pbf served its sidecar to a
  mamaps_build reading another copy (other path, mtime 2001): "20996
  blobs skipped", archive identical.
- osm_ingest tests: 313 passed.

Diff

scripts/maps/mamaps_build/src/extract_part1.rs
diff --git a/scripts/maps/mamaps_build/src/extract_part1.rs b/scripts/maps/mamaps_build/src/extract_part1.rsindex 418685f9ab..1fd894452d 100644--- a/scripts/maps/mamaps_build/src/extract_part1.rs+++ b/scripts/maps/mamaps_build/src/extract_part1.rs@@ -31,7 +31,7 @@ pub fn extract(      // A blob-kinds mask cached beside the routing graph -- `road_graph`'s pass 1 wrote it over this     // same `.pbf` -- lets pass 1 skip node blobs outright rather than inflating them to learn they-    // hold no ways or relations. Guarded by blob count, file length and mtime, so a missing or stale+    // hold no ways or relations. Guarded by blob count, file length and a content fingerprint, so a missing or stale     // sidecar simply falls back to a full scan. Byte-neutral either way: the mask `run_pass1` returns     // carries the skipped blobs' kinds, so it is a complete description of the file regardless.     //@@ -48,6 +48,14 @@ pub fn extract(     } else {         None     };+    match &graph_kinds {+        Some(kinds) => println!(+            "pass 1: blob-kinds sidecar matches this pbf ({} blob(s), {} without ways or relations skipped)",+            kinds.len(),+            kinds.iter().filter(|&&k| k & (pbf::KIND_WAYS | pbf::KIND_RELATIONS) == 0).count(),+        ),+        None => println!("pass 1: no matching blob-kinds sidecar beside the graph; scanning every blob"),+    }     if let Some(b) = region.as_ref() {         println!(             "region filter: keeping roads/pois/buildings touching {:.3},{:.3} .. {:.3},{:.3}",
scripts/maps/osm_ingest/src/fingerprint.rs
diff --git a/scripts/maps/osm_ingest/src/fingerprint.rs b/scripts/maps/osm_ingest/src/fingerprint.rsnew file mode 100644index 0000000000..49b540e3b9--- /dev/null+++ b/scripts/maps/osm_ingest/src/fingerprint.rs@@ -0,0 +1,142 @@+//! Content fingerprints of input files: what a tool may key a cache guard or a build id on.+//!+//! Never a path, an mtime, an inode, a host or a user: two copies of the same bytes anywhere, made+//! at any time, fingerprint the same, and the archives built from them come out byte-identical.+//! (The blob-kinds sidecar used to carry the input's mtime, and the archive's build id hashed the+//! input's absolute path and mtime, so the same planet built on two machines differed.)+//!+//! A fingerprint is FNV-1a 64 over the file's length, its first [`SAMPLE_BYTES`] and its last+//! [`SAMPLE_BYTES`] (the whole file when it is no longer than twice that). That is a few MB of+//! reads per input, however large the input. It is a change detector, not a proof of identity:+//! callers that need more mix in what they already know about the content (a `.pbf`'s blob+//! index, the archive's own tile digest).++use std::io::{Read, Seek, SeekFrom};+use std::path::Path;++/// Bytes sampled from each end of a file.+pub const SAMPLE_BYTES: u64 = 4 << 20;++/// FNV-1a 64, the same hash the archive writer uses for its dedup keys: stable, dependency-free,+/// and defined byte by byte so it cannot depend on platform or word size.+#[derive(Debug, Clone, Copy)]+pub struct Fnv(pub u64);++impl Default for Fnv {+    fn default() -> Self {+        Fnv(0xcbf2_9ce4_8422_2325)+    }+}++impl Fnv {+    pub fn eat(&mut self, bytes: &[u8]) {+        for &b in bytes {+            self.0 ^= b as u64;+            self.0 = self.0.wrapping_mul(0x100_0000_01b3);+        }+    }++    pub fn eat_u64(&mut self, v: u64) {+        self.eat(&v.to_le_bytes());+    }++    pub fn finish(&self) -> u64 {+        self.0+    }+}++/// The content fingerprint of one file (see the module docs).+pub fn file_fingerprint(path: &Path) -> std::io::Result<u64> {+    let mut file = std::fs::File::open(path)?;+    let len = file.metadata()?.len();+    let mut h = Fnv::default();+    h.eat(b"file/1");+    h.eat_u64(len);+    let mut buf = Vec::new();+    if len <= 2 * SAMPLE_BYTES {+        file.read_to_end(&mut buf)?;+        h.eat(&buf);+    } else {+        buf.resize(SAMPLE_BYTES as usize, 0);+        file.read_exact(&mut buf)?;+        h.eat(&buf);+        file.seek(SeekFrom::Start(len - SAMPLE_BYTES))?;+        file.read_exact(&mut buf)?;+        h.eat(&buf);+    }+    Ok(h.finish())+}++/// The fingerprint of a directory's regular files: each file's name (relative, so the directory's+/// own location never counts) and [`file_fingerprint`], in name order. Dot-files are skipped:+/// `planet_build.sh` touches `.ready` in the graph dir as a signal, which is not content.+pub fn dir_fingerprint(dir: &Path) -> std::io::Result<u64> {+    let mut names: Vec<std::ffi::OsString> = Vec::new();+    for entry in std::fs::read_dir(dir)? {+        let entry = entry?;+        let name = entry.file_name();+        if name.to_string_lossy().starts_with('.') || !entry.file_type()?.is_file() {+            continue;+        }+        names.push(name);+    }+    names.sort();+    let mut h = Fnv::default();+    h.eat(b"dir/1");+    for name in names {+        h.eat(name.to_string_lossy().as_bytes());+        h.eat(&[0]);+        h.eat_u64(file_fingerprint(&dir.join(&name))?);+    }+    Ok(h.finish())+}++#[cfg(test)]+mod tests {+    use super::*;++    fn scratch(name: &str) -> std::path::PathBuf {+        let d = std::env::temp_dir().join(format!("osm_fp_{}_{name}", std::process::id()));+        let _ = std::fs::remove_dir_all(&d);+        std::fs::create_dir_all(&d).unwrap();+        d+    }++    /// The same bytes fingerprint the same at another path with another mtime; a change at the+    /// head, the tail or the length moves it; small files are hashed whole.+    #[test]+    fn fingerprints_follow_content_not_place_or_time() {+        let a = scratch("a");+        let b = scratch("b");+        let big: Vec<u8> = (0..(SAMPLE_BYTES as usize * 3)).map(|i| (i * 31 % 251) as u8).collect();+        std::fs::write(a.join("x.bin"), &big).unwrap();+        std::thread::sleep(std::time::Duration::from_millis(20));+        std::fs::write(b.join("x.bin"), &big).unwrap();+        let fa = file_fingerprint(&a.join("x.bin")).unwrap();+        assert_eq!(fa, file_fingerprint(&b.join("x.bin")).unwrap());+        assert_eq!(dir_fingerprint(&a).unwrap(), dir_fingerprint(&b).unwrap());+        // Signals are not content.+        std::fs::write(b.join(".ready"), b"").unwrap();+        assert_eq!(dir_fingerprint(&a).unwrap(), dir_fingerprint(&b).unwrap());+        for (at, what) in [(0usize, "head"), (big.len() - 1, "tail")] {+            let mut changed = big.clone();+            changed[at] ^= 1;+            std::fs::write(b.join("x.bin"), &changed).unwrap();+            assert_ne!(fa, file_fingerprint(&b.join("x.bin")).unwrap(), "{what} change missed");+            assert_ne!(dir_fingerprint(&a).unwrap(), dir_fingerprint(&b).unwrap());+        }+        std::fs::write(b.join("x.bin"), &big[1..]).unwrap();+        assert_ne!(fa, file_fingerprint(&b.join("x.bin")).unwrap(), "length change missed");+        // A small file is hashed whole: a change anywhere moves it.+        std::fs::write(a.join("s.bin"), b"0123456789").unwrap();+        let fs = file_fingerprint(&a.join("s.bin")).unwrap();+        std::fs::write(a.join("s.bin"), b"0123x56789").unwrap();+        assert_ne!(fs, file_fingerprint(&a.join("s.bin")).unwrap());+        // A renamed file inside a directory is a different directory.+        std::fs::write(b.join("x.bin"), &big).unwrap();+        std::fs::rename(b.join("x.bin"), b.join("y.bin")).unwrap();+        assert_ne!(dir_fingerprint(&a).unwrap(), dir_fingerprint(&b).unwrap());+        let _ = std::fs::remove_dir_all(&a);+        let _ = std::fs::remove_dir_all(&b);+    }+}
scripts/maps/osm_ingest/src/graph_build_part1.rs
diff --git a/scripts/maps/osm_ingest/src/graph_build_part1.rs b/scripts/maps/osm_ingest/src/graph_build_part1.rsindex de3f179e3b..1e79f45ddf 100644--- a/scripts/maps/osm_ingest/src/graph_build_part1.rs+++ b/scripts/maps/osm_ingest/src/graph_build_part1.rs@@ -166,7 +166,7 @@ pub fn build_with(input: &Path, out_dir: &Path, opts: Options) -> Result<Stats>     // `.pbf` can skip its own full pass-1 scan. This pass inflated every blob with `None`, so the     // mask is complete. Best-effort: a write failure must not fail the graph build, which never     // reads the sidecar itself.-    if let Err(e) = pbf::write_blob_kinds(out_dir, input, &blob_kinds) {+    if let Err(e) = pbf::write_blob_kinds(out_dir, input, &blobs, &blob_kinds) {         eprintln!("WARN: could not write blob-kinds sidecar: {e}");     }     let slots = cap_u32("marked graph node", marked)?;
scripts/maps/osm_ingest/src/lib.rs
diff --git a/scripts/maps/osm_ingest/src/lib.rs b/scripts/maps/osm_ingest/src/lib.rsindex 2369204e66..0edaf01832 100644--- a/scripts/maps/osm_ingest/src/lib.rs+++ b/scripts/maps/osm_ingest/src/lib.rs@@ -22,6 +22,7 @@ pub mod chains; pub mod compact; pub mod dem; pub mod extract;+pub mod fingerprint; pub mod geojson; pub mod geom; pub mod graph_build;
scripts/maps/osm_ingest/src/pbf_extra.rs
diff --git a/scripts/maps/osm_ingest/src/pbf_extra.rs b/scripts/maps/osm_ingest/src/pbf_extra.rsindex 9301b4a572..c7a4264298 100644--- a/scripts/maps/osm_ingest/src/pbf_extra.rs+++ b/scripts/maps/osm_ingest/src/pbf_extra.rs@@ -47,11 +47,32 @@ pub fn probe_compression(path: &Path, blobs: &[BlobLoc]) -> Result<()> { pub const BLOB_KINDS_FILE: &str = "blob_kinds.bin";  /// Magic + version for the blob-kinds sidecar. Bumped if the header or payload layout changes, so an-/// old sidecar is rejected rather than misread.-const BLOB_KINDS_MAGIC: &[u8; 4] = b"MBK1";--/// Header bytes before the per-blob kind payload: magic, blob count, source length, mtime.-const BLOB_KINDS_HEAD: usize = 4 + 8 + 8 + 8 + 4;+/// old sidecar is rejected rather than misread. `MBK2` replaced `MBK1`'s source mtime with a content+/// fingerprint, so the graph directory is byte-identical wherever and whenever the `.pbf` lives.+const BLOB_KINDS_MAGIC: &[u8; 4] = b"MBK2";++/// Header bytes before the per-blob kind payload: magic, blob count, source length, fingerprint.+const BLOB_KINDS_HEAD: usize = 4 + 8 + 8 + 8;++/// What guards a blob-kinds sidecar against a different `.pbf`: the file's content fingerprint+/// (length, first and last 4 MiB -- [`crate::fingerprint::file_fingerprint`]) mixed with the blob+/// index pass 1 already holds (every blob's offset and size), so an edit anywhere that resizes a+/// blob changes it. Never a path or a timestamp: a copy of the same file elsewhere, or touched,+/// still matches, and the sidecar's bytes depend only on the input's bytes.+fn blob_kinds_guard(input: &Path, blobs: &[BlobLoc]) -> Result<u64> {+    let mut h = crate::fingerprint::Fnv::default();+    h.eat(b"blob-kinds/2");+    h.eat_u64(+        crate::fingerprint::file_fingerprint(input)+            .map_err(|e| Error(format!("cannot read {}: {e}", input.display())))?,+    );+    h.eat_u64(blobs.len() as u64);+    for b in blobs {+        h.eat_u64(b.offset);+        h.eat_u64(b.datasize as u64);+    }+    Ok(h.finish())+}  /// Persist a complete per-blob kind mask beside a tool's output, guarded against the source `.pbf` /// it describes.@@ -59,18 +80,18 @@ const BLOB_KINDS_HEAD: usize = 4 + 8 + 8 + 8 + 4; /// A full pass already learns which blobs hold nodes, ways or relations; two tools run back to back /// over the same file (`road_graph` then `mamaps_build`) both want that mask, and the second would /// otherwise pay a full scan to recompute it. Writing it here lets the second load it instead. The-/// guard -- blob count, file length and mtime -- is what makes a stale sidecar a fall-back rather-/// than a wrong answer; see [`load_blob_kinds`].-pub fn write_blob_kinds(dir: &Path, input: &Path, kinds: &[u8]) -> Result<()> {-    let meta = std::fs::metadata(input)-        .map_err(|e| Error(format!("cannot stat {}: {e}", input.display())))?;-    let (secs, nanos) = mtime_parts(&meta);+/// guard -- blob count, file length and a content fingerprint ([`blob_kinds_guard`]) -- is what+/// makes a stale sidecar a fall-back rather than a wrong answer; see [`load_blob_kinds`].+pub fn write_blob_kinds(dir: &Path, input: &Path, blobs: &[BlobLoc], kinds: &[u8]) -> Result<()> {+    let len = std::fs::metadata(input)+        .map_err(|e| Error(format!("cannot stat {}: {e}", input.display())))?+        .len();+    let guard = blob_kinds_guard(input, blobs)?;     let mut out = Vec::with_capacity(BLOB_KINDS_HEAD + kinds.len());     out.extend_from_slice(BLOB_KINDS_MAGIC);     out.extend_from_slice(&(kinds.len() as u64).to_le_bytes());-    out.extend_from_slice(&meta.len().to_le_bytes());-    out.extend_from_slice(&secs.to_le_bytes());-    out.extend_from_slice(&nanos.to_le_bytes());+    out.extend_from_slice(&len.to_le_bytes());+    out.extend_from_slice(&guard.to_le_bytes());     out.extend_from_slice(kinds);     let path = dir.join(BLOB_KINDS_FILE);     std::fs::write(&path, &out)@@ -79,11 +100,11 @@ pub fn write_blob_kinds(dir: &Path, input: &Path, kinds: &[u8]) -> Result<()> {  /// Load a blob-kinds mask written by [`write_blob_kinds`], but only if it still describes `input`. ///-/// `None` on any mismatch or error -- a missing file, wrong magic, a different blob count, a changed-/// length or mtime, a short read -- so the caller falls back to a full scan. `blobs` supplies the-/// count the mask must match; nothing here trusts the file's own count past that check. The returned-/// mask is byte-for-byte what a full pass over `input` would produce, so feeding it to a later pass-/// changes no output.+/// `None` on any mismatch or error -- a missing file, wrong magic (an `MBK1` sidecar included), a+/// different blob count, a changed length or fingerprint, a short read -- so the caller falls back+/// to a full scan. `blobs` supplies the count the mask must match; nothing here trusts the file's+/// own count past that check. The returned mask is byte-for-byte what a full pass over `input`+/// would produce, so feeding it to a later pass changes no output. pub fn load_blob_kinds(dir: &Path, input: &Path, blobs: &[BlobLoc]) -> Option<Vec<u8>> {     let raw = std::fs::read(dir.join(BLOB_KINDS_FILE)).ok()?;     if raw.len() < BLOB_KINDS_HEAD || &raw[0..4] != BLOB_KINDS_MAGIC {@@ -91,30 +112,20 @@ pub fn load_blob_kinds(dir: &Path, input: &Path, blobs: &[BlobLoc]) -> Option<Ve     }     let count = u64::from_le_bytes(raw[4..12].try_into().ok()?);     let file_len = u64::from_le_bytes(raw[12..20].try_into().ok()?);-    let secs = u64::from_le_bytes(raw[20..28].try_into().ok()?);-    let nanos = u32::from_le_bytes(raw[28..32].try_into().ok()?);+    let guard = u64::from_le_bytes(raw[20..28].try_into().ok()?);     // The count must match the file being read now, and the payload must be exactly that many bytes:     // a truncated or padded sidecar is as untrustworthy as a stale one.     if count as usize != blobs.len() || raw.len() != BLOB_KINDS_HEAD + blobs.len() {         return None;     }-    let meta = std::fs::metadata(input).ok()?;-    if meta.len() != file_len || mtime_parts(&meta) != (secs, nanos) {+    if std::fs::metadata(input).ok()?.len() != file_len+        || blob_kinds_guard(input, blobs).ok()? != guard+    {         return None;     }     Some(raw[BLOB_KINDS_HEAD..].to_vec()) } -/// A file's modification time as `(seconds, nanoseconds)` since the Unix epoch, or `(0, 0)` when the-/// platform cannot report one. Split rather than a single `u128` so the sidecar header is fixed-width-/// integers that any reader can parse without a wide type.-fn mtime_parts(meta: &std::fs::Metadata) -> (u64, u32) {-    match meta.modified().ok().and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) {-        Some(d) => (d.as_secs(), d.subsec_nanos()),-        None => (0, 0),-    }-}- #[cfg(test)] mod tests {     use super::*;@@ -472,14 +483,36 @@ mod tests {         let _ = std::fs::remove_dir_all(&dir);         std::fs::create_dir_all(&dir).unwrap();         let input = dir.join("in.osm.pbf");-        std::fs::write(&input, b"a fake pbf, only its length and mtime matter here").unwrap();+        std::fs::write(&input, b"a fake pbf, only its bytes matter here").unwrap(); -        let blobs: Vec<BlobLoc> = (0..5).map(|_| BlobLoc { offset: 0, datasize: 0 }).collect();+        let blobs: Vec<BlobLoc> =+            (0..5).map(|i| BlobLoc { offset: i * 10, datasize: 10 }).collect();         let kinds = vec![KIND_NODES, KIND_NODES | KIND_WAYS, KIND_WAYS, KIND_RELATIONS, 0];-        write_blob_kinds(&dir, &input, &kinds).unwrap();+        write_blob_kinds(&dir, &input, &blobs, &kinds).unwrap();          // Happy path: same file, same blob count.         assert_eq!(load_blob_kinds(&dir, &input, &blobs).as_deref(), Some(kinds.as_slice()));+        // Place and time are not content: the same bytes copied elsewhere and touched later still+        // match, and the sidecar written for the copy is byte-identical.+        let elsewhere = dir.join("moved");+        std::fs::create_dir_all(&elsewhere).unwrap();+        let copy = elsewhere.join("renamed.osm.pbf");+        std::thread::sleep(std::time::Duration::from_millis(20));+        std::fs::copy(&input, &copy).unwrap();+        assert_eq!(load_blob_kinds(&dir, &copy, &blobs).as_deref(), Some(kinds.as_slice()));+        write_blob_kinds(&elsewhere, &copy, &blobs, &kinds).unwrap();+        assert_eq!(+            std::fs::read(dir.join(BLOB_KINDS_FILE)).unwrap(),+            std::fs::read(elsewhere.join(BLOB_KINDS_FILE)).unwrap(),+            "the sidecar depends on the input's path or mtime"+        );+        // Same length, different bytes: the content guard fires.+        std::fs::write(&copy, b"a fake pbf, only its BYTES matter here").unwrap();+        assert!(load_blob_kinds(&dir, &copy, &blobs).is_none(), "content guard did not fire");+        // A resized blob in the index is a different file even with the same bytes sampled.+        let mut moved = blobs.clone();+        moved[2].datasize += 1;+        assert!(load_blob_kinds(&dir, &input, &moved).is_none(), "blob-index guard did not fire");         // A different blob count is a different file to pass 1, whatever the sidecar claims.         let fewer: Vec<BlobLoc> = blobs[..4].to_vec();         assert!(load_blob_kinds(&dir, &input, &fewer).is_none(), "blob-count guard did not fire");