Modern Apps git

← Modern-Apps.git

mamaps: sequential spill writes, fix random-write slowdowns

Commit
b031c8c77f0b33e42ea52c39f7e085d7967e3570
Author
vayun-mathur <[email protected]>
When
2026-10-06 00:30 UTC (2 months ago)
Parents
af7e3d8

Diff

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 56a8bb5d63..a73a6e918f 100644--- a/library/tilecodec/src/main/rust/src/mamaps/write/spill.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/write/spill.rs@@ -97,12 +97,22 @@ impl Spill {             return Ok(self.buffer[at..at + candidate.len()] == *candidate);         }         self.confirms_from_file += 1;-        self.bytes_from_file += candidate.len() as u64;-        // A body straddling the boundary is one the buffer holds only the tail of. Flushing is-        // simpler than stitching two compares together, and can only happen once per body.+        // A body straddling the flush boundary lives half in the file, half in the buffer.+        // Compare the two halves in place instead of flushing: a flush here would push a whole+        // megabyte to disk just to answer one compare, and can only happen once per body.+        // Byte-identical to the flush-then-compare it replaces: same bytes, same answer.         if end > self.flushed {-            self.flush()?;+            let file_len = (self.flushed - start) as usize;+            self.bytes_from_file += file_len as u64;+            let Spill { file, path, scratch, buffer, .. } = self;+            scratch.resize(file_len, 0);+            read_exact_at(file, path, start, scratch)?;+            if scratch[..] != candidate[..file_len] {+                return Ok(false);+            }+            return Ok(buffer[..candidate.len() - file_len] == candidate[file_len..]);         }+        self.bytes_from_file += candidate.len() as u64;         let Spill { file, path, scratch, .. } = self;         scratch.resize(candidate.len(), 0);         read_exact_at(file, path, start, scratch)?;
scripts/maps/mamaps_build/src/store_part3.rs
diff --git a/scripts/maps/mamaps_build/src/store_part3.rs b/scripts/maps/mamaps_build/src/store_part3.rsindex 3200a59870..1411fded35 100644--- a/scripts/maps/mamaps_build/src/store_part3.rs+++ b/scripts/maps/mamaps_build/src/store_part3.rs@@ -407,9 +407,16 @@ impl WaySink {             }             None => put_uvarint(&mut self.record, 0),         }-        self.out_write(&self.record.clone()).map_err(|e| {+        // Moved out rather than cloned: `out_write` takes `&mut self`, so `&self.record`+        // cannot borrow across the call, and a per-way clone is a memcpy per record over+        // millions of records. The buffer is restored below with its capacity intact, so the+        // `clear` at the top of the next `push` still reuses the allocation.+        let record = std::mem::take(&mut self.record);+        let result = self.out_write(&record).map_err(|e| {             Error(format!("cannot write the ways spill: {e}"))-        })?;+        });+        self.record = record;+        result?;         self.last_id = id;         self.count += 1;         self.refs += refs.len() as u64;
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 bfcd2b1232..91a9b11eea 100644--- a/scripts/maps/mamaps_build/src/tilespill.rs+++ b/scripts/maps/mamaps_build/src/tilespill.rs@@ -107,11 +107,6 @@ const BUILDING_BYTES: usize = 17; /// features by the body format, so the largest plausible entry is orders of magnitude below this. const MAX_ENTRY_BYTES: u64 = 1 << 30; -/// Encoded bytes a worker buffers before it writes. Large enough that a chunk of a few thousand-/// small entries is one or two writes, small enough that the buffer is noise next to the chunk map-/// it is draining.-const FLUSH_BYTES: usize = 1 << 20;- /// Bytes the whole merge may hold in read windows, divided across its streams. /// /// Small against the old 256 MiB on purpose: the merge holds one cursor per chunk (~27 k at a@@ -184,10 +179,14 @@ pub struct ChunkSpill {     file: Option<File>,     anon: Option<std::sync::Mutex<tile_build::anon::AnonStore>>,     path: PathBuf,-    /// The next free byte, and so also the total reserved. Held for one integer add per chunk and-    /// never across I/O: a worker must not queue behind another worker's write with a finished chunk-    /// in hand.+    /// The next free byte, and so also the total reserved. Reserved under the commit lock+    /// ([`Self::write`], always `write` before `at`), so reservation order is completion order+    /// and the file offset advances monotonically — one sequential chunk after another.     at: Mutex<u64>,+    /// Serialises whole-chunk commits (reserve + write) so the file offset advances+    /// monotonically: reservation order == completion order, one large sequential write+    /// per chunk, no interleaved 1 MB pieces from N workers. Always taken before `at`.+    write: Mutex<()>,     written: AtomicU64,     written_entries: AtomicU64,     read: AtomicU64,@@ -214,6 +213,7 @@ impl ChunkSpill {             anon: None,             path,             at: Mutex::new(0),+            write: Mutex::new(()),             written: AtomicU64::new(0),             written_entries: AtomicU64::new(0),             read: AtomicU64::new(0),@@ -221,6 +221,8 @@ impl ChunkSpill {         })     } +    /// Anonymous twin+     /// Anonymous twin of [`create`](Self::create): same chunks and offsets in     /// pagefile-backed memory, no file. `path` names nothing — it only rides     /// along for error messages and the `check_books` accounting.@@ -239,6 +241,7 @@ impl ChunkSpill {                 anon: Some(std::sync::Mutex::new(tile_build::anon::AnonStore::new())),                 path: path.into(),                 at: Mutex::new(0),+                write: Mutex::new(()),                 written: AtomicU64::new(0),                 written_entries: AtomicU64::new(0),                 read: AtomicU64::new(0),@@ -259,12 +262,16 @@ impl ChunkSpill {      /// Write one finished chunk and say where it went.     ///-    /// Takes the map **by value** and encodes out of `into_iter`, flushing every [`FLUSH_BYTES`], so-    /// the map shrinks as it is written instead of being copied whole into a buffer beside itself.+    /// Takes the map **by value** and encodes out of `into_iter`, so the map shrinks as it is+    /// written instead of being copied whole into a buffer beside itself.     ///-    /// The byte range is reserved under the cursor lock and written outside it. That ordering is the-    /// point: the lock covers an integer add, so a worker that has just finished a chunk is never-    /// waiting on another worker's disk.+    /// Encode happens outside any lock, in parallel across workers. The commit — reserving the+    /// byte range and writing it — holds the `write` lock for one sequential write per chunk.+    /// Reservation order is therefore completion order and the file offset advances+    /// monotonically: no interleaved 1 MB pieces from N workers sharing one file offset space,+    /// which is what turned N parallel positional fills into random-write interleaving on+    /// spinning disks (and page-cache churn everywhere). The merge sorts chunks by their read+    /// index, never by file position, so the layout change is not observable in the archive.     pub fn write_chunk(&self, map: BTreeMap<(u64, u8), ChunkEntry>) -> Result<ChunkRef> {         let entries = map.len() as u64;         let mut len = 0u64;@@ -281,6 +288,18 @@ impl ChunkSpill {             len += entry_bytes(entry)?;         } +        // Encoded before the commit lock, so N workers still clip and encode in parallel and+        // only the disk write itself is serial. Sized exactly: `len` above is the encoded+        // length, so this is one allocation per chunk rather than a growing buffer.+        let mut buf: Vec<u8> = Vec::with_capacity(len as usize);+        for ((tile, layer_id), layer) in map {+            encode_entry(tile, layer_id, &layer, &mut buf);+        }+        debug_assert_eq!(buf.len() as u64, len, "the encoded chunk must match its reservation");++        // One commit per chunk: reserve and write under the same lock, so the file sees whole+        // sequential chunks in reservation order. Always `write` before `at`.+        let _commit = self.write.lock().expect("the tile chunk spill's commit lock");         let at = {             let mut next = self.at.lock().expect("the tile chunk spill's cursor");             let at = *next;@@ -288,15 +307,7 @@ impl ChunkSpill {             at         }; -        let mut buf: Vec<u8> = Vec::new();-        let mut cursor = at;-        for ((tile, layer_id), layer) in map {-            encode_entry(tile, layer_id, &layer, &mut buf);-            if buf.len() >= FLUSH_BYTES {-                cursor += self.flush(&mut buf, cursor)?;-            }-        }-        cursor += self.flush(&mut buf, cursor)?;+        let cursor = at + self.flush(&mut buf, at)?;          if cursor != at + len {             return err(format!(
scripts/maps/osm_ingest/src/nodeloc_part1.rs
diff --git a/scripts/maps/osm_ingest/src/nodeloc_part1.rs b/scripts/maps/osm_ingest/src/nodeloc_part1.rsindex a9c84dfe19..4f492a890c 100644--- a/scripts/maps/osm_ingest/src/nodeloc_part1.rs+++ b/scripts/maps/osm_ingest/src/nodeloc_part1.rs@@ -123,6 +123,16 @@ where         },         |(coords, items)| {             let at = on.then(std::time::Instant::now);+            // Sorted by table index before the stores, so the mmap writes walk forward+            // instead of scattering: a chunk's ids arrive in block order (ascending within+            // a block, but blocks interleave across the chunk), and 8-byte stores to+            // 1.23 GB touch one page per store when they jump. Ascending stores fault+            // pages in order and reuse the TLB entry. Byte-identical: the table holds+            // one coordinate per index and the bitset is order-independent, so write+            // order is not observable. `items` (the classification drain) keeps its+            // own order — only the coordinate writes are reordered.+            let mut coords = coords;+            coords.sort_unstable_by_key(|c| c.0);             for (idx, lat, lon) in coords {                 locs.set(idx as usize, lat, lon);             }