maps: unlink mamaps_build scratch files as soon as they are open (#perf)
- Commit
d4515afaf0ed79b440c2cc21eacf42860ee3df98- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-11 06:50 UTC (25 days ago)
- Parents
29090c0
Bug: an oomd-killed mamaps_build left /tmp/osm_nodeloc_<pid>_0.bin (83.2 GB, the pass-3 coordinate table) behind. The table lived in std::env::temp_dir() on the build's disk and was only deleted in Drop, which a killed process never runs; the orphan made the next planet run fail planet_build's 240 GB phase-4 disk gate. What changed: - osm_ingest::mem gains scratch_dir()/set_scratch_dir() (default: the system temp dir; MAPS_SCRATCH_DIR overrides) and unlink_open_scratch(), which removes the name of a file the caller keeps open or mapped (Unix; a no-op returning false on Windows, where an open file cannot be deleted). - nodeloc's coordinate table is created in scratch_dir() and unlinked right after it is mapped. mamaps_build sets scratch_dir() to the directory of its spills (next to --out), so the table no longer lands in /tmp. - The same unlink-at-creation for every scratch file that is only ever accessed through its one handle: tilecodec's archive body scratch (mamaps_bodies_*.tmp), the tile-chunk spill, and the lane-inheritance partition files (lanefill*.tmp), which now read back through their own handles instead of reopening by path. ChunkSpill::check_books stats the handle, not the path. - Drop deletes the path only where the unlink did not happen. The per-zoom chunk spills share one path, so a late Drop must not delete the next zoom's file. Not changed: the feature spill (tiles.features.tmp) and the ways spill (tiles.features.ways.tmp) are reopened by path by their readers, so they keep their names. planet_build.sh already deletes both before phase 4. Verified: - New tests: the_coordinate_scratch_is_unlinked_while_mapped, the_body_scratch_leaves_no_name_behind, the_chunk_scratch_leaves_no_name_behind and partitions_leave_no_names_behind check that the directory is empty while each file is live and that reads still work. The existing drop tests now expect no name during life on Unix. - CA archive sha256 identical to baseline-bin (94cb7eef4c760742). - SIGKILLed CA builds during pass 3, during lane inheritance and during the z13 map left only tiles.features.tmp: nothing in /tmp and no nodeloc, body, chunk or lanefill files. - mamaps_build, tile_build and osm_ingest tests pass. tilecodec has the same 4 failures as before.
Diff
library/tilecodec/src/main/rust/src/mamaps/tests.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/tests.rs b/library/tilecodec/src/main/rust/src/mamaps/tests.rsindex a8bb13ff93..0f82b24b3b 100644--- a/library/tilecodec/src/main/rust/src/mamaps/tests.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/tests.rs@@ -371,7 +371,10 @@ fn the_body_scratch_file_is_removed_however_the_build_ends() { { let mut writer = StreamWriter::new(scratch.options()).expect("options"); writer.append(tile_id(0, 0, 0), &body_for(1)).expect("append");- assert_eq!(scratch.files().len(), 1, "a writer holding bodies has a scratch file");+ // Unlinked as soon as it is created on Unix, so even a killed build leaves nothing; named+ // until drop elsewhere.+ let named = if cfg!(unix) { 0 } else { 1 };+ assert_eq!(scratch.files().len(), named, "the body scratch's name while the writer lives"); } assert!(scratch.files().is_empty(), "dropping the writer took its scratch with it");
library/tilecodec/src/main/rust/src/mamaps/write/spill.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/write/spill.rs b/library/tilecodec/src/main/rust/src/mamaps/write/spill.rsindex bbeea721a8..19e2efc081 100644--- a/library/tilecodec/src/main/rust/src/mamaps/write/spill.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/write/spill.rs@@ -13,6 +13,9 @@ const BUFFER_BYTES: usize = 1 << 20; /// and a read for anything already on disk, but a slice compare for anything still in the buffer, /// and the bodies most recently written are the ones a repeat is likeliest to match. pub(crate) struct Spill {+ /// The name was removed right after creation (Unix): the handle is the file, and `Drop`+ /// must not delete whatever may have reused the path since.+ unlinked: bool, pub(crate) path: PathBuf, /// Opened for reading as well as writing, because a content-dedup compare reads back a body /// this same handle wrote.@@ -85,7 +88,15 @@ impl Spill { if let Some(hook) = hook { hook(&file); }+ // Everything after this goes through the one handle (appends, dedup reads, the copy into+ // the archive), so on Unix the name can go now: a build killed mid-way then leaves no+ // body scratch behind (tens of GB on a planet). Elsewhere `Drop` deletes it as before.+ #[cfg(unix)]+ let unlinked = std::fs::remove_file(&path).is_ok();+ #[cfg(not(unix))]+ let unlinked = false; Ok(Spill {+ unlinked, path, file, buffer: Vec::with_capacity(BUFFER_BYTES),@@ -394,7 +405,9 @@ impl Drop for Spill { /// The error is dropped on purpose. Scratch that outlives the process is untidy; panicking in a /// `Drop` while a real failure is unwinding would replace its diagnostic with this one. fn drop(&mut self) {- let _ = std::fs::remove_file(&self.path);+ if !self.unlinked {+ let _ = std::fs::remove_file(&self.path);+ } } } @@ -501,4 +514,24 @@ mod bg_tests { spill.copy_to_vec(&mut out).unwrap(); assert_eq!(out, want); }++ /// The body scratch is unlinked at creation on Unix: its directory is empty while the spill+ /// is live and written to, and reading it back still works.+ #[test]+ fn the_body_scratch_leaves_no_name_behind() {+ let dir = std::env::temp_dir().join(format!("mamaps_bodies_unlink_{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let mut spill = Spill::create(Some(&dir), None).unwrap();+ spill.append(b"abc").unwrap();+ spill.append_shared(std::sync::Arc::new(vec![7u8; 100_000])).unwrap();+ #[cfg(unix)]+ assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "a body scratch name was left");+ assert!(spill.matches_at(0, b"abc").unwrap());+ let mut out = Vec::new();+ spill.copy_to_vec(&mut out).unwrap();+ assert_eq!(out.len(), 100_003);+ drop(spill);+ assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0);+ std::fs::remove_dir(&dir).unwrap();+ } }
scripts/maps/mamaps_build/src/lanefill.rs
diff --git a/scripts/maps/mamaps_build/src/lanefill.rs b/scripts/maps/mamaps_build/src/lanefill.rsindex 2ab6df7b5c..1f48deb2da 100644--- a/scripts/maps/mamaps_build/src/lanefill.rs+++ b/scripts/maps/mamaps_build/src/lanefill.rs@@ -346,6 +346,9 @@ pub fn prepare_lazy( pub struct Collector { files: Vec<BufWriter<File>>, paths: Vec<PathBuf>,+ /// Whether the partition names were unlinked at creation (Unix); if not, `finish` and drop+ /// delete them.+ unlinked: bool, } impl Collector {@@ -355,14 +358,25 @@ impl Collector { let mut paths = Vec::with_capacity(PARTITIONS); for i in 0..PARTITIONS { let path = stem.with_extension(format!("lanefill{i:03}.tmp"));- let file = File::create(&path)+ // Read and write on one handle, so `finish` reads the partition back through it and+ // the name can be unlinked straight away: a build killed mid-scan leaves nothing.+ let file = std::fs::OpenOptions::new()+ .read(true)+ .write(true)+ .create(true)+ .truncate(true)+ .open(&path) .map_err(|e| Error(format!("cannot create {}: {e}", path.display())))?; // Small buffers: there are `PARTITIONS` of them held open at once, and each takes a // steady trickle rather than a burst. files.push(BufWriter::with_capacity(1 << 14, file)); paths.push(path); }- Ok(Collector { files, paths })+ let mut unlinked = true;+ for path in &paths {+ unlinked &= osm_ingest::mem::unlink_open_scratch(path);+ }+ Ok(Collector { files, paths, unlinked }) } /// Offer one way to the join. Ways that cannot take part are dropped here.@@ -390,10 +404,13 @@ impl Collector { /// Ways whose inherited count equals the default they would have had anyway are left out, the /// same way [`crate::corridor::promote`] leaves out ways its corridor does not move. pub fn finish(mut self) -> Result<Vec<(i64, u8)>> {- for file in &mut self.files {- file.flush().map_err(|e| Error(format!("cannot flush a lanefill partition: {e}")))?;+ let mut files: Vec<File> = Vec::with_capacity(self.files.len());+ for file in std::mem::take(&mut self.files) {+ files.push(+ file.into_inner()+ .map_err(|e| Error(format!("cannot flush a lanefill partition: {e}")))?,+ ); }- drop(self.files); // `(way, end, donor lanes, one-way)`. The only state that outlives a partition, because a // way's two endpoints hash to two different files and the "donor at both ends" condition@@ -405,11 +422,12 @@ impl Collector { // concatenation order never reaches the output: the resolution stays independent of both // the write order and the partition order. let per_partition: Vec<Vec<(i64, u8, u8, bool)>> = par::install(|| {- self.paths- .par_iter()- .map(|path| -> Result<Vec<(i64, u8, u8, bool)>> {+ files+ .par_iter_mut()+ .zip(self.paths.par_iter())+ .map(|(file, path)| -> Result<Vec<(i64, u8, u8, bool)>> { let mut records: Vec<Record> = Vec::new();- read_partition(path, &mut records)?;+ read_partition(file, path, &mut records)?; let mut local: Vec<(i64, u8, u8, bool)> = Vec::new(); if !records.is_empty() { // Sorted rather than hashed, for the reason `corridor::promote` gives: a@@ -426,8 +444,11 @@ impl Collector { .collect::<Result<Vec<_>>>() })?; let mut found: Vec<(i64, u8, u8, bool)> = per_partition.into_iter().flatten().collect();- for path in &self.paths {- let _ = std::fs::remove_file(path);+ drop(files);+ if !self.unlinked {+ for path in &self.paths {+ let _ = std::fs::remove_file(path);+ } } found.sort_unstable();@@ -448,6 +469,19 @@ impl Collector { } } +impl Drop for Collector {+ /// Only where the names could not be unlinked at creation: a collector dropped on an error+ /// path must not leave its partitions behind.+ fn drop(&mut self) {+ if !self.unlinked {+ self.files.clear();+ for path in &self.paths {+ let _ = std::fs::remove_file(path);+ }+ }+ }+}+ /// Every recipient in `run` against every donor, appending the pairs that survive the conditions. fn pair_up(run: &[Record], found: &mut Vec<(i64, u8, u8, bool)>) { for recipient in run.iter().filter(|r| r.lanes == 0) {@@ -467,10 +501,9 @@ fn pair_up(run: &[Record], found: &mut Vec<(i64, u8, u8, bool)>) { } } -fn read_partition(path: &Path, out: &mut Vec<Record>) -> Result<()> {+fn read_partition(file: &mut File, path: &Path, out: &mut Vec<Record>) -> Result<()> { out.clear();- let mut file =- File::open(path).map_err(|e| Error(format!("cannot open {}: {e}", path.display())))?;+ std::io::Seek::rewind(file).map_err(|e| Error(format!("cannot rewind {}: {e}", path.display())))?; let mut bytes = Vec::new(); file.read_to_end(&mut bytes) .map_err(|e| Error(format!("cannot read {}: {e}", path.display())))?;@@ -598,4 +631,21 @@ mod lazy_tests { } } }++ /// The partition files are unlinked at creation on Unix: their directory is empty while the+ /// collector is live, and `finish` still reads every record back through the handles.+ #[test]+ fn partitions_leave_no_names_behind() {+ let dir = std::env::temp_dir().join(format!("mamaps_lanefill_unlink_{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let mut c = Collector::create(&dir.join("tiles.features.tmp")).unwrap();+ let line = [(-122.0, 37.0), (-122.0, 37.0001)];+ let a = Segment { id: 1, name: "A St", lanes: 0, oneway: false, nodes: &[10, 11], line: &line };+ c.push(&a).unwrap();+ #[cfg(unix)]+ assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "a partition name was left");+ let _ = c.finish().unwrap();+ assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0);+ std::fs::remove_dir(&dir).unwrap();+ } }
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 8d2a91d972..1983f6db04 100644--- a/scripts/maps/mamaps_build/src/main_part1.rs+++ b/scripts/maps/mamaps_build/src/main_part1.rs@@ -10,6 +10,12 @@ fn run( // Features are spilled here rather than held: it was 4.9 GB of a measured 10.03 GB California // peak, and nothing reads them until the tiler does. let spill = out.with_extension("features.tmp");+ // Named scratch (the pass-3 coordinate table: 83 GB on a planet) goes next to the spills,+ // not in the system temp dir; `MAPS_SCRATCH_DIR` overrides. Such files are unlinked as soon+ // as they are open, so a killed build leaves none of them behind.+ osm_ingest::mem::set_scratch_dir(spill.parent().map(|p| {+ if p.as_os_str().is_empty() { std::path::PathBuf::from(".") } else { p.to_path_buf() }+ })); check_required(&run.coastline, "--coastline")?; check_required(&run.transit_routes, "--transit-routes")?; check_required(&run.dem, "--dem")?;
scripts/maps/mamaps_build/src/tilespill.rs
diff --git a/scripts/maps/mamaps_build/src/tilespill.rs b/scripts/maps/mamaps_build/src/tilespill.rsindex e0ab8b0dc8..dd974a003e 100644--- a/scripts/maps/mamaps_build/src/tilespill.rs+++ b/scripts/maps/mamaps_build/src/tilespill.rs@@ -174,6 +174,8 @@ pub struct ChunkRef { /// pagefile-backed memory. Same offsets, same bytes, no /// file. The merge reads through the same [`ChunkReader`] either way. pub struct ChunkSpill {+ /// The scratch file's name was removed right after creation (Unix): see [`Self::create`].+ unlinked: bool, /// `None` only while dropping, where the handle has to close before the file can be unlinked or /// Windows refuses the delete. Always `None` on the anon path (no handle at all). file: Option<File>,@@ -232,7 +234,11 @@ impl ChunkSpill { // Uncompressed on a `compress-force` btrfs: every zoom's clipped geometry passes through // here (hundreds of GB over a planet build), written once, read back by the merge. osm_ingest::mem::mark_scratch_uncompressed(&file);+ // Every read and write goes through this one handle, so the name can go now: a build+ // killed mid-zoom leaves no tile-chunk scratch behind (tens of GB at planet z14).+ let unlinked = osm_ingest::mem::unlink_open_scratch(&path); Ok(ChunkSpill {+ unlinked, file: Some(file), anon: None, path,@@ -262,6 +268,7 @@ impl ChunkSpill { pub fn create_planned(path: impl Into<PathBuf>, plan: osm_ingest::mem::SpillPlan) -> Result<ChunkSpill> { match plan { osm_ingest::mem::SpillPlan::Anon => Ok(ChunkSpill {+ unlinked: false, file: None, anon: Some(std::sync::Mutex::new(tile_build::anon::AnonStore::new())), path: path.into(),@@ -440,7 +447,9 @@ impl ChunkSpill { )); } let staged = match (&self.file, &self.anon) {- (Some(_), None) => std::fs::metadata(&self.path)+ // Through the handle: the name is unlinked at creation.+ (Some(f), None) => f+ .metadata() .map_err(|e| Error(format!("cannot stat {}: {e}", self.path.display())))? .len(), (None, Some(a)) => a.lock().expect("the anon tile chunk spill").len(),@@ -476,7 +485,9 @@ impl Drop for ChunkSpill { // The handle first, or Windows refuses the delete. Anon path holds no // handle and no file: nothing to do, the mapping frees with the store. self.file = None;- if self.anon.is_none() {+ // Not when the name was unlinked at creation: per-zoom spills share one path, so the+ // name may by now belong to the next zoom's file.+ if self.anon.is_none() && !self.unlinked { let _ = std::fs::remove_file(&self.path); } }
scripts/maps/mamaps_build/src/tilespill_part3.rs
diff --git a/scripts/maps/mamaps_build/src/tilespill_part3.rs b/scripts/maps/mamaps_build/src/tilespill_part3.rsindex 70999b97f8..235d20894b 100644--- a/scripts/maps/mamaps_build/src/tilespill_part3.rs+++ b/scripts/maps/mamaps_build/src/tilespill_part3.rs@@ -13,6 +13,24 @@ mod tests { )) } + /// The tile-chunk scratch is unlinked at creation on Unix: nothing named is left in its+ /// directory while chunks are written and read back, and the books still balance.+ #[test]+ fn the_chunk_scratch_leaves_no_name_behind() {+ let dir = tmp("unlinkdir");+ std::fs::create_dir_all(&dir).unwrap();+ let spill = ChunkSpill::create(dir.join("tiles.chunks.tmp")).unwrap();+ let chunk = spill.write_chunk(std::collections::BTreeMap::new()).unwrap();+ #[cfg(unix)]+ assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "a chunk scratch name was left");+ let mut reader = spill.reader(&chunk, 4096);+ assert!(reader.next().unwrap().is_none());+ spill.check_books().unwrap();+ drop(spill);+ assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0);+ std::fs::remove_dir(&dir).unwrap();+ }+ pub(super) fn feature(kind: u16, detail: u16, geom: u8, flags: u8, at: u32, n: u32) -> BodyFeature { BodyFeature { kind,
scripts/maps/mamaps_build/src/tilespill_part4.rs
diff --git a/scripts/maps/mamaps_build/src/tilespill_part4.rs b/scripts/maps/mamaps_build/src/tilespill_part4.rsindex 309256b35e..b7fe181b2d 100644--- a/scripts/maps/mamaps_build/src/tilespill_part4.rs+++ b/scripts/maps/mamaps_build/src/tilespill_part4.rs@@ -40,7 +40,9 @@ mod tests_extra { { let spill = ChunkSpill::create(&path).expect("create"); spill.write_chunk(every_layer().into_iter().collect()).expect("write");- assert!(path.exists());+ // Unlinked at creation on Unix (a killed build leaves nothing); named until drop+ // elsewhere.+ assert_eq!(path.exists(), cfg!(not(unix))); } assert!(!path.exists(), "the scratch file outlived its spill"); }
scripts/maps/osm_ingest/src/mem.rs
diff --git a/scripts/maps/osm_ingest/src/mem.rs b/scripts/maps/osm_ingest/src/mem.rsindex 0bc331bd95..1d0eec7e78 100644--- a/scripts/maps/osm_ingest/src/mem.rs+++ b/scripts/maps/osm_ingest/src/mem.rs@@ -438,6 +438,43 @@ mod platform { /// /// Bytes read back are identical either way; this changes only how the filesystem stores /// them.+/// Where named scratch files go: `MAPS_SCRATCH_DIR` if set, else the directory a tool set with+/// [`set_scratch_dir`] (mamaps_build: the build's own scratch directory, next to its spills),+/// else the system temp dir. Path only: nothing written there is observable in any output.+pub fn scratch_dir() -> std::path::PathBuf {+ if let Some(dir) = std::env::var_os("MAPS_SCRATCH_DIR").filter(|d| !d.is_empty()) {+ return std::path::PathBuf::from(dir);+ }+ SCRATCH_DIR+ .lock()+ .expect("the scratch dir setting")+ .clone()+ .unwrap_or_else(std::env::temp_dir)+}++/// Set the default for [`scratch_dir`] (the `MAPS_SCRATCH_DIR` override still wins).+pub fn set_scratch_dir(dir: Option<std::path::PathBuf>) {+ *SCRATCH_DIR.lock().expect("the scratch dir setting") = dir;+}++static SCRATCH_DIR: std::sync::Mutex<Option<std::path::PathBuf>> = std::sync::Mutex::new(None);++/// Unlink a scratch file the caller keeps open (and possibly mapped), so the kernel frees its+/// blocks when the last handle closes -- on any exit, a kill included -- instead of leaving it on+/// disk. Returns whether the name is gone; on platforms that cannot delete an open file (Windows)+/// it does nothing and returns `false`, and the caller keeps deleting the file on drop.+pub fn unlink_open_scratch(path: &std::path::Path) -> bool {+ #[cfg(unix)]+ {+ std::fs::remove_file(path).is_ok()+ }+ #[cfg(not(unix))]+ {+ let _ = path;+ false+ }+}+ pub fn mark_scratch_uncompressed(file: &std::fs::File) { #[cfg(target_os = "linux")] {
scripts/maps/osm_ingest/src/nodeloc.rs
diff --git a/scripts/maps/osm_ingest/src/nodeloc.rs b/scripts/maps/osm_ingest/src/nodeloc.rsindex c9319b22f6..7e839df162 100644--- a/scripts/maps/osm_ingest/src/nodeloc.rs+++ b/scripts/maps/osm_ingest/src/nodeloc.rs@@ -57,17 +57,23 @@ struct Locs { map: Option<memmap2::MmapMut>, /// One bit per node, set when a coordinate has been written. resolved: Vec<u64>,- /// Deleted on drop. Scratch, and large enough that leaving it behind would matter.+ /// Deleted on drop where it could not be unlinked at creation (Windows). Scratch, and large+ /// enough that leaving it behind matters: 83 GB on a planet. path: Option<PathBuf>, len: usize, } impl Locs { fn new(len: usize) -> Result<Locs> {+ Self::new_in(&crate::mem::scratch_dir(), len)+ }++ /// [`new`](Self::new) with the scratch file in `dir`.+ fn new_in(dir: &std::path::Path, len: usize) -> Result<Locs> { if len == 0 { return Ok(Locs { map: None, resolved: Vec::new(), path: None, len: 0 }); }- let path = std::env::temp_dir().join(format!(+ let path = dir.join(format!( "osm_nodeloc_{}_{}.bin", std::process::id(), // Distinct per table, so two in one process cannot share a file.@@ -94,10 +100,14 @@ impl Locs { // mapping is live, which is the one thing that would make the slice dangle. let map = unsafe { memmap2::MmapMut::map_mut(&file) } .map_err(|e| Error(format!("cannot map {}: {e}", path.display())))?;+ // The mapping keeps the file alive; its name can go now, so a process that dies -- an+ // OOM kill, a SIGKILL -- leaves nothing behind (an orphaned 83 GB table in /tmp once+ // failed the next planet build's disk gate). Where that is impossible, drop deletes it.+ let path = if crate::mem::unlink_open_scratch(&path) { None } else { Some(path) }; Ok(Locs { map: Some(map), resolved: vec![0u64; len.div_ceil(64)],- path: Some(path),+ path, len, }) }@@ -490,4 +500,26 @@ impl NodeLocations { } include!("nodeloc_part1.rs");-include!("nodeloc_part2.rs");\ No newline at end of file+include!("nodeloc_part2.rs");++#[cfg(test)]+mod scratch_tests {+ use super::*;++ /// The coordinate table's scratch file is unlinked as soon as it is mapped: nothing is left+ /// in the scratch dir even while the table is live, and the table still works.+ #[test]+ fn the_coordinate_scratch_is_unlinked_while_mapped() {+ let dir = std::env::temp_dir().join(format!("osm_nodeloc_unlink_{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let mut locs = Locs::new_in(&dir, 1000).unwrap();+ locs.set(7, 123, -456);+ let left: Vec<_> = std::fs::read_dir(&dir).unwrap().collect();+ #[cfg(unix)]+ assert!(left.is_empty(), "scratch left in {}: {left:?}", dir.display());+ assert_eq!(locs.get(7), Some((123, -456)));+ drop(locs);+ assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0);+ std::fs::remove_dir(&dir).unwrap();+ }+}