Modern Apps git

← Modern-Apps.git

maps: append tile bodies off the serial archive thread (#perf)

Commit
5d314e8dc755120b063c28cb18d1833186c1bf62
Author
Vayun Mathur <[email protected]>
When
2026-11-11 05:36 UTC (25 days ago)
Parents
bdc7239
What: tilecodec's StreamWriter (the .mamaps archive writer) gains
append_stored_owned(), and its body scratch (Spill) a background
writer; mamaps_build hands each encoded tile body over whole.

Why / root cause: on the Nov 10 planet build the tiler's append ran
95 s, all on the one thread that must take tiles in order (dedup
decisions depend on every earlier body). Per tile it copied the
stored body into a 1 MiB buffer, copied it again into last_body,
wrote the buffer with a seek+write, and every 200k distinct bodies
swept the whole dedup map with HashMap::retain (millions of keys at
z13/z14). ~34 GB of bodies went through those copies.

How:
- Offsets are a running sum of body lengths, known at append time,
  so the appender keeps doing the order-dependent bookkeeping (run
  length, dedup lookup, index entry) and passes the body (an Arc,
  no copy) to a writer thread that writes 8 MiB batches with pwrite
  at those offsets, in order. Bodies not yet written stay in memory
  (released every 8 MiB batch as the writer confirms progress) so a
  dedup compare against them never reads
  the file; older candidates are pread. last_body is an Arc.
- The dedup sweep pops an insertion-ordered list of (offset, key)
  instead of retain over the whole map: offsets ascend, so the front
  is exactly what retain(at >= floor) dropped.
- The dedup map's keys are already FNV hashes: a multiply-rotate
  mixer replaces SipHash.
- Options::spill_file_hook lets mamaps_build mark the body scratch
  NOCOW (already-DEFLATEd bodies; btrfs compress-force would zstd
  them again).

Same dedup decisions, offsets and bytes. Verified: tilecodec unit
test background_appends_write_the_same_section (offsets, in-memory
and on-disk compares, mixed buffered appends); CA and US West
archives sha256-identical to baseline-bin (see the series' last
commit for the run table).

Diff

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 4db2e3e919..99dfab8388 100644--- a/library/tilecodec/src/main/rust/src/mamaps/write/options.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/write/options.rs@@ -41,6 +41,11 @@ pub struct Options {     /// parallelism. Speed only: every leaf's frame is a pure function of the leaf, so the     /// archive is the same at any count.     pub threads: usize,+    /// Called on the body scratch file right after it is created, before anything is written:+    /// lets a host tool mark the scratch for its filesystem (e.g. uncompressed on a+    /// `compress-force` btrfs, where the already-DEFLATEd bodies would be zstd'd again at+    /// writeback). Never observable in the archive.+    pub spill_file_hook: Option<fn(&std::fs::File)>, }  impl Default for Options {@@ -59,6 +64,7 @@ impl Default for Options {             max_lon_e7: 1_800_000_000,             max_lat_e7: 850_511_287,             threads: 0,+            spill_file_hook: None,         }     } }
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 a73a6e918f..bbeea721a8 100644--- a/library/tilecodec/src/main/rust/src/mamaps/write/spill.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/write/spill.rs@@ -27,10 +27,42 @@ pub(crate) struct Spill {     pub(crate) confirms: u64,     pub(crate) confirms_from_file: u64,     pub(crate) bytes_from_file: u64,+    /// The background writer, once [`Self::append_shared`] has started one. See [`BodyWriter`].+    bg: Option<BodyWriter>,+}++/// Bytes of bodies batched per hand-off to the background writer.+const BG_BATCH_BYTES: usize = 8 << 20;++/// A thread that writes appended bodies into the scratch file, in append order, at the offsets+/// the appender already gave them; the appender keeps every body not yet known written in+/// memory (`inflight`) so a dedup compare against it never touches the file.+///+/// What it removes from the serial append path is the copy of every stored body into the+/// buffer and the write itself -- ~34 GB of bodies on a planet build, all on the one thread+/// that also does the order-dependent dedup bookkeeping. Offsets are a running sum of body+/// lengths, known at append time, so the data section's bytes and every index entry are+/// exactly what the buffered path produced.+struct BodyWriter {+    tx: Option<std::sync::mpsc::SyncSender<Vec<std::sync::Arc<Vec<u8>>>>>,+    handle: Option<std::thread::JoinHandle<()>>,+    progress: std::sync::Arc<(std::sync::Mutex<BgProgress>, std::sync::Condvar)>,+    /// Logical length: every body appended, written or not.+    logical: u64,+    outgoing: Vec<std::sync::Arc<Vec<u8>>>,+    outgoing_bytes: usize,+    /// `(offset, body)` for every body not yet known written, ascending.+    inflight: std::collections::VecDeque<(u64, std::sync::Arc<Vec<u8>>)>,+}++struct BgProgress {+    /// Bytes known written: a body ending at or before this is in the file.+    written: u64,+    failed: Option<String>, }  impl Spill {-    pub(crate) fn create(dir: Option<&Path>) -> Result<Spill> {+    pub(crate) fn create(dir: Option<&Path>, hook: Option<fn(&File)>) -> Result<Spill> {         /// Two writers in one process — which the test suite has, and a planet build may — must not         /// share a scratch file.         static NEXT: AtomicU64 = AtomicU64::new(0);@@ -50,6 +82,9 @@ impl Spill {             .truncate(true)             .open(&path)             .map_err(|e| scratch_error(&path, "create", e))?;+        if let Some(hook) = hook {+            hook(&file);+        }         Ok(Spill {             path,             file,@@ -59,15 +94,161 @@ impl Spill {             confirms: 0,             confirms_from_file: 0,             bytes_from_file: 0,+            bg: None,         })     }      /// Bytes appended so far, buffered or not — which is the offset the next body will land at.     pub(crate) fn len(&self) -> u64 {-        self.flushed + self.buffer.len() as u64+        match &self.bg {+            Some(bg) => bg.logical,+            None => self.flushed + self.buffer.len() as u64,+        }+    }++    /// Append a body the caller hands over whole, through the background writer (started on+    /// first use). Same offset, same bytes as [`Self::append`]; the body is written later, in+    /// order, and kept in memory until it is.+    pub(crate) fn append_shared(&mut self, body: std::sync::Arc<Vec<u8>>) -> Result<()> {+        if self.bg.is_none() {+            self.flush()?;+            self.start_bg()?;+        }+        let bg = self.bg.as_mut().expect("started above");+        let at = bg.logical;+        bg.logical += body.len() as u64;+        bg.outgoing_bytes += body.len();+        bg.inflight.push_back((at, std::sync::Arc::clone(&body)));+        bg.outgoing.push(body);+        if bg.outgoing_bytes >= BG_BATCH_BYTES {+            self.send_outgoing()?;+            // Drop the in-memory copies of everything the writer has finished: without this the+            // bodies would stay resident until a dedup compare happened to prune them -- the whole+            // data section (~53 GB on a planet) in the worst case.+            self.bg_written()?;+        }+        Ok(())+    }++    fn start_bg(&mut self) -> Result<()> {+        let file = self.file.try_clone().map_err(|e| scratch_error(&self.path, "reopen", e))?;+        let path = self.path.clone();+        let progress = std::sync::Arc::new((+            std::sync::Mutex::new(BgProgress { written: self.flushed, failed: None }),+            std::sync::Condvar::new(),+        ));+        let (tx, rx) = std::sync::mpsc::sync_channel::<Vec<std::sync::Arc<Vec<u8>>>>(4);+        let shared = std::sync::Arc::clone(&progress);+        let mut cursor = self.flushed;+        let handle = std::thread::Builder::new()+            .name("mamaps-bodies".to_string())+            .spawn(move || {+                let mut joined: Vec<u8> = Vec::with_capacity(BG_BATCH_BYTES * 2);+                for batch in rx {+                    joined.clear();+                    for body in &batch {+                        joined.extend_from_slice(body);+                    }+                    let wrote = pwrite_all(&file, cursor, &joined);+                    let (lock, cv) = &*shared;+                    let mut p = lock.lock().expect("the body writer's progress");+                    match wrote {+                        Ok(()) => {+                            cursor += joined.len() as u64;+                            p.written = cursor;+                        }+                        Err(e) => {+                            p.failed = Some(scratch_error(&path, "write to", e).0);+                            cv.notify_all();+                            return;+                        }+                    }+                    cv.notify_all();+                }+            })+            .map_err(|e| crate::proto::Error(format!("cannot start the body writer: {e}")))?;+        self.bg = Some(BodyWriter {+            tx: Some(tx),+            handle: Some(handle),+            progress,+            logical: self.flushed,+            outgoing: Vec::new(),+            outgoing_bytes: 0,+            inflight: std::collections::VecDeque::new(),+        });+        Ok(())+    }++    fn send_outgoing(&mut self) -> Result<()> {+        let bg = self.bg.as_mut().expect("only with a writer");+        if bg.outgoing.is_empty() {+            return Ok(());+        }+        let batch = std::mem::take(&mut bg.outgoing);+        bg.outgoing_bytes = 0;+        if bg.tx.as_ref().expect("open until finished").send(batch).is_err() {+            return Err(self.bg_failure());+        }+        Ok(())+    }++    fn bg_failure(&self) -> crate::proto::Error {+        let bg = self.bg.as_ref().expect("only with a writer");+        let p = bg.progress.0.lock().expect("the body writer's progress");+        crate::proto::Error(+            p.failed.clone().unwrap_or_else(|| "the body writer stopped early".to_string()),+        )+    }++    /// Bytes known written, after dropping the in-memory copies of everything below it.+    fn bg_written(&mut self) -> Result<u64> {+        let bg = self.bg.as_mut().expect("only with a writer");+        let written = {+            let p = bg.progress.0.lock().expect("the body writer's progress");+            if let Some(e) = &p.failed {+                return Err(crate::proto::Error(e.clone()));+            }+            p.written+        };+        while let Some((at, body)) = bg.inflight.front() {+            if at + body.len() as u64 > written {+                break;+            }+            bg.inflight.pop_front();+        }+        Ok(written)+    }++    /// Send everything and wait until it is all in the file, then fold the writer back into the+    /// buffered state (`flushed` = the whole section) and stop it.+    fn finish_bg(&mut self) -> Result<()> {+        if self.bg.is_none() {+            return Ok(());+        }+        self.send_outgoing()?;+        let mut bg = self.bg.take().expect("checked above");+        drop(bg.tx.take());+        if let Some(h) = bg.handle.take() {+            h.join().map_err(|_| crate::proto::Error("the body writer panicked".to_string()))?;+        }+        let p = bg.progress.0.lock().expect("the body writer's progress");+        if let Some(e) = &p.failed {+            return Err(crate::proto::Error(e.clone()));+        }+        if p.written != bg.logical {+            return Err(crate::proto::Error(format!(+                "the body writer stopped at {} of {} bytes",+                p.written, bg.logical,+            )));+        }+        self.flushed = bg.logical;+        Ok(())     }      pub(crate) fn append(&mut self, bytes: &[u8]) -> Result<()> {+        if self.bg.is_some() {+            return self.append_shared(std::sync::Arc::new(bytes.to_vec()));+        }         if self.buffer.len() + bytes.len() > BUFFER_BYTES {             self.flush()?;         }@@ -92,6 +273,27 @@ impl Spill {         let end = start + candidate.len() as u64;         debug_assert!(end <= self.len(), "a dedup candidate past the end of the data section");         self.confirms += 1;+        if self.bg.is_some() {+            let written = self.bg_written()?;+            if end > written {+                // Not known written: in memory. Dedup candidates are whole earlier bodies, so the+                // offset names one exactly; anything else waits for the writer and reads.+                let bg = self.bg.as_ref().expect("checked above");+                let i = bg.inflight.partition_point(|(at, _)| *at < start);+                if let Some((at, body)) = bg.inflight.get(i) {+                    if *at == start && body.len() == candidate.len() {+                        return Ok(body[..] == *candidate);+                    }+                }+                self.finish_bg()?;+            }+            self.confirms_from_file += 1;+            self.bytes_from_file += candidate.len() as u64;+            let Spill { file, path, scratch, .. } = self;+            scratch.resize(candidate.len(), 0);+            pread_exact(file, start, scratch).map_err(|e| scratch_error(path, "read back from", e))?;+            return Ok(scratch[..] == *candidate);+        }         if start >= self.flushed {             let at = (start - self.flushed) as usize;             return Ok(self.buffer[at..at + candidate.len()] == *candidate);@@ -120,6 +322,9 @@ impl Spill {     }      pub(crate) fn flush(&mut self) -> Result<()> {+        if self.bg.is_some() {+            return self.finish_bg();+        }         if self.buffer.is_empty() {             return Ok(());         }@@ -172,6 +377,15 @@ impl Spill {     } } +impl Drop for BodyWriter {+    fn drop(&mut self) {+        drop(self.tx.take());+        if let Some(h) = self.handle.take() {+            let _ = h.join();+        }+    }+}+ impl Drop for Spill {     /// So a build that dies part way through cannot strand a copy of its data section — 652 MB for     /// California and tens of gigabytes for a planet, which is why `tile_build::spill` does the@@ -199,9 +413,92 @@ pub(crate) fn read_exact_at(file: &mut File, path: &Path, offset: u64, into: &mu     file.read_exact(into).map_err(|e| scratch_error(path, "read back from", e)) } +/// A positional write that never moves the shared file cursor (the appender's reads and the+/// writer's writes share one file description).+fn pwrite_all(file: &File, mut offset: u64, mut bytes: &[u8]) -> std::io::Result<()> {+    while !bytes.is_empty() {+        #[cfg(unix)]+        let n = std::os::unix::fs::FileExt::write_at(file, bytes, offset)?;+        #[cfg(windows)]+        let n = std::os::windows::fs::FileExt::seek_write(file, bytes, offset)?;+        if n == 0 {+            return Err(std::io::Error::new(std::io::ErrorKind::WriteZero, "the scratch took nothing"));+        }+        bytes = &bytes[n..];+        offset += n as u64;+    }+    Ok(())+}++/// The read twin of [`pwrite_all`].+fn pread_exact(file: &File, mut offset: u64, mut into: &mut [u8]) -> std::io::Result<()> {+    while !into.is_empty() {+        #[cfg(unix)]+        let n = std::os::unix::fs::FileExt::read_at(file, into, offset)?;+        #[cfg(windows)]+        let n = std::os::windows::fs::FileExt::seek_read(file, into, offset)?;+        if n == 0 {+            return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "the scratch ended early"));+        }+        into = &mut into[n..];+        offset += n as u64;+    }+    Ok(())+}+ pub(crate) fn scratch_error(path: &Path, doing: &str, e: std::io::Error) -> crate::proto::Error {     crate::proto::Error(format!(         "cannot {doing} the .mamaps body scratch file {}: {e}",         path.display(),     )) }++#[cfg(test)]+mod bg_tests {+    use super::*;++    /// Bodies appended through the background writer land at the offsets `len()` promised, in+    /// order, byte for byte; dedup compares answer the same whether the body is still in memory+    /// or already in the file; and the buffered path can be mixed in.+    #[test]+    fn background_appends_write_the_same_section() {+        let mut spill = Spill::create(None, None).unwrap();+        let mut want: Vec<u8> = Vec::new();+        let mut offsets = Vec::new();+        spill.append(b"buffered-prefix").unwrap();+        want.extend_from_slice(b"buffered-prefix");+        let mut state = 0x9E37_79B9_7F4A_7C15u64;+        for i in 0..3000usize {+            state ^= state << 13;+            state ^= state >> 7;+            state ^= state << 17;+            let len = (state % 20_000) as usize + 1;+            let body: Vec<u8> = (0..len).map(|k| (k as u64 ^ state ^ i as u64) as u8).collect();+            assert_eq!(spill.len(), want.len() as u64);+            offsets.push((want.len() as u64, body.clone()));+            want.extend_from_slice(&body);+            spill.append_shared(std::sync::Arc::new(body)).unwrap();+            if i % 97 == 0 {+                // A compare against an early body (on disk by now, or still in flight) and the+                // latest one (certainly in flight); a wrong candidate must not match.+                let (at, b) = &offsets[i / 3];+                assert!(spill.matches_at(*at, b).unwrap());+                let (at, b) = offsets.last().unwrap();+                assert!(spill.matches_at(*at, b).unwrap());+                let mut wrong = b.clone();+                wrong[0] ^= 1;+                assert!(!spill.matches_at(*at, &wrong).unwrap());+            }+            if i == 1500 {+                spill.append(b"mixed").unwrap();+                want.extend_from_slice(b"mixed");+            }+        }+        // In-flight copies are released as the writer catches up, not held to the end.+        let held: usize = spill.bg.as_ref().map_or(0, |bg| bg.inflight.iter().map(|(_, b)| b.len()).sum());+        assert!(held < 64 << 20, "{held} bytes still held in memory");+        let mut out = Vec::new();+        spill.copy_to_vec(&mut out).unwrap();+        assert_eq!(out, want);+    }+}
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 59ae2611e7..ed48dfa958 100644--- a/library/tilecodec/src/main/rust/src/mamaps/write/writer.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/write/writer.rs@@ -6,6 +6,32 @@ use crate::mamaps::header::MAX_ZOOM; use crate::mamaps::index::{LeafEntry, RootEntry, self}; use crate::proto::{Result, err}; use std::collections::HashMap;++/// 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.+type SeenMap = HashMap<(u64, u32), Vec<u64>, std::hash::BuildHasherDefault<KeyHasher>>;++/// A multiply-rotate mixer for [`SeenMap`]'s already-hashed keys.+#[derive(Default)]+struct KeyHasher(u64);++impl std::hash::Hasher for KeyHasher {+    fn finish(&self) -> u64 {+        self.0+    }+    fn write(&mut self, bytes: &[u8]) {+        for &b in bytes {+            self.write_u64(b as u64);+        }+    }+    fn write_u64(&mut self, v: u64) {+        self.0 = (self.0.rotate_left(5) ^ v).wrapping_mul(0x51_7c_c1_b7_27_22_0a_95);+    }+    fn write_u32(&mut self, v: u32) {+        self.write_u64(v as u64);+    }+} use std::fs::File; use std::io::Write; use std::path::Path;@@ -27,7 +53,10 @@ pub struct StreamWriter {     pub(crate) entries: Vec<Pending>,     /// `(hash, stored length) -> offsets already written`. Several per key only on a collision,     /// which is why it is a list. Probed, never iterated.-    seen: HashMap<(u64, u32), Vec<u64>>,+    seen: SeenMap,+    /// Every offset in `seen`, in the order it was added (which is ascending), with its key: what+    /// [`Self::sweep_dedup`] pops from instead of walking the whole map.+    seen_order: std::collections::VecDeque<(u64, (u64, u32))>,     last_id: Option<u64>,     /// The stored bytes of the body `entries.last()` points at, which is what a run-length compare     /// is against.@@ -37,7 +66,7 @@ pub struct StreamWriter {     /// whatever those bytes are. A `debug_assert` in [`Self::append_encoded`] checks it against the     /// 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: Vec<u8>,+    last_body: std::sync::Arc<Vec<u8>>,     /// 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,@@ -112,14 +141,15 @@ impl StreamWriter {         }         // After the option checks, so a build with an impossible zoom range fails without having         // created a file to clean up.-        let data = Spill::create(options.spill_dir.as_deref())?;+        let data = Spill::create(options.spill_dir.as_deref(), options.spill_file_hook)?;         Ok(StreamWriter {             options,             data,             entries: Vec::new(),-            seen: HashMap::new(),+            seen: SeenMap::default(),+            seen_order: std::collections::VecDeque::new(),             last_id: None,-            last_body: Vec::new(),+            last_body: Default::default(),             distinct_since_sweep: 0,             tiles_addressed: 0,             distinct: 0,@@ -226,6 +256,24 @@ impl StreamWriter {     /// anyway (see `MAX_DEDUP_REACH`). Byte-identity on small archives holds because the sweep     /// never fires there.     fn push(&mut self, tile_id: u64, stored: &[u8], hash: u64) -> Result<()> {+        self.push_shared(tile_id, std::sync::Arc::new(stored.to_vec()), hash)+    }++    /// [`Self::append_stored_with_hash`] for a body the caller hands over whole: the same dedup+    /// decisions, offsets and index entries, with the body's bytes going to the background writer+    /// ([`Spill::append_shared`]) instead of being copied on this thread.+    pub fn append_stored_owned(&mut self, tile_id: u64, stored: Vec<u8>, hash: u64) -> Result<()> {+        if !self.options.compress {+            return err(+                "append_stored was given a compressed body but this archive stores them raw"+                    .to_string(),+            );+        }+        Body::raw_len(&stored)?;+        self.push_shared(tile_id, std::sync::Arc::new(stored), hash)+    }++    fn push_shared(&mut self, tile_id: u64, stored: std::sync::Arc<Vec<u8>>, hash: u64) -> Result<()> {         let (z, _, _) = crate::pmtiles::tile_zxy(tile_id);         if z < self.options.min_zoom || z > self.options.max_zoom {             return err(format!(@@ -257,7 +305,7 @@ impl StreamWriter {             );             if previous.length == length                 && previous.tile_id + previous.run_length as u64 == tile_id-                && self.last_body == stored+                && *self.last_body == *stored             {                 previous.run_length += 1;                 self.runs_used = true;@@ -268,7 +316,7 @@ impl StreamWriter {         let key = (hash, length);         // `seen` and `data` are borrowed apart because confirming a candidate may read the spill,         // which needs `&mut`, while the bucket being walked lives in the map.-        let StreamWriter { seen, data, distinct, .. } = &mut *self;+        let StreamWriter { seen, seen_order, data, distinct, .. } = &mut *self;         let bucket = seen.entry(key).or_default();         let mut hit = None;         let head = data.len();@@ -287,8 +335,9 @@ impl StreamWriter {             Some(at) => at,             None => {                 let at = data.len();-                data.append(&stored)?;+                data.append_shared(std::sync::Arc::clone(&stored))?;                 bucket.push(at);+                seen_order.push_back((at, key));                 *distinct += 1;                 // Counted here -- not in the caller -- so the sweep below sees every new                 // distinct body exactly once, wherever the dedup miss happened.@@ -309,8 +358,7 @@ impl StreamWriter {             }         }         self.entries.push(Pending { tile_id, offset, run_length: 1, length });-        self.last_body.clear();-        self.last_body.extend_from_slice(stored);+        self.last_body = stored;         Ok(())     } @@ -333,10 +381,24 @@ impl StreamWriter {     /// older bodies, so entries past it were dead weight -- buckets walked, never hit.     fn sweep_dedup(&mut self, head: u64) {         let floor = head.saturating_sub(DEDUP_KEEP_REACH);-        self.seen.retain(|_, bucket| {-            bucket.retain(|&at| at >= floor);-            !bucket.is_empty()-        });+        // Popped from the insertion-ordered list rather than `retain` over the whole map: the+        // map holds ~2 GiB of bodies' worth of keys (millions on a planet z14) and the sweep+        // fires every `DEDUP_SWEEP_DISTINCT` new bodies, so walking all of it each time was a+        // large share of the serial append. Offsets were pushed in ascending order, so the+        // front of the list is exactly the set `retain(at >= floor)` removed: the same entries+        // go, the same stay.+        while let Some(&(at, key)) = self.seen_order.front() {+            if at >= floor {+                break;+            }+            self.seen_order.pop_front();+            if let Some(bucket) = self.seen.get_mut(&key) {+                bucket.retain(|&b| b != at);+                if bucket.is_empty() {+                    self.seen.remove(&key);+                }+            }+        }         self.distinct_since_sweep = 0;     } @@ -483,11 +545,12 @@ impl StreamWriter {     ) -> Result<Option<Split>> {         let w = StreamWriter {             options: Options::default(),-            data: Spill::create(None).expect("spill"),+            data: Spill::create(None, None).expect("spill"),             entries: entries.to_vec(),-            seen: std::collections::HashMap::new(),+            seen: SeenMap::default(),+            seen_order: std::collections::VecDeque::new(),             last_id: None,-            last_body: Vec::new(),+            last_body: Default::default(),             distinct_since_sweep: 0,             tiles_addressed: entries.len() as u64,             distinct: entries.len() as u64,
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 2cc93dc912..48eca529da 100644--- a/scripts/maps/mamaps_build/src/tiler_part1.rs+++ b/scripts/maps/mamaps_build/src/tiler_part1.rs@@ -64,6 +64,9 @@ fn writer_for(store: &Store, settings: &Settings) -> Result<StreamWriter> {         spill_dir: settings.scratch.parent().map(std::path::Path::to_path_buf),         // Leaf compression at finish runs on the build's own thread budget.         threads: par::threads(),+        // The body scratch holds already-DEFLATEd bodies (~53 GB on a planet): keep btrfs+        // `compress-force` from zstd'ing them again at writeback.+        spill_file_hook: Some(osm_ingest::mem::mark_scratch_uncompressed),         ..Options::default()     }) }@@ -354,7 +357,9 @@ fn consume_merged(                             // Uncompressed, as this column has always meant.                             stats.bytes += raw_len as u64;                             stats.tiles += 1;-                            writer.append_stored_with_hash(id, &stored, hash)?;+                            // Handed over whole: the writer's background thread copies and+                            // writes the body, this thread only does the dedup bookkeeping.+                            writer.append_stored_owned(id, stored, hash)?;                             written += 1;                             // Every 25k tiles: often enough to look alive on a continent, rare                             // enough that the write itself is never the cost.