impl ChunkSpill { /// Create the scratch file, truncating whatever a killed run left at the path. /// /// Read *and* write on one handle, because that is the whole shape of this module: the workers /// write positionally through it and the merge reads positionally through it, and a second /// handle would be a second file description with nothing to gain. pub fn create(path: impl Into) -> Result { let path = path.into(); 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())))?; // 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, at: Mutex::new(0), write: Mutex::new(()), written: AtomicU64::new(0), written_entries: AtomicU64::new(0), read: AtomicU64::new(0), read_entries: AtomicU64::new(0), runs: Mutex::new(Vec::new()), }) } /// Create with an explicit staging plan. See [`osm_ingest::mem::SpillPlan::decide`]: the /// budget gate picks `File` when anon commit does not fit, and `File` stages through the /// scratch path (truncated like [`create`](Self::create), removed on drop). Same chunks, /// same offsets, same bytes -- the backend never changes a hash. pub fn create_planned( path: impl Into, plan: osm_ingest::mem::SpillPlan, ) -> Result { 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(), at: Mutex::new(0), write: Mutex::new(()), written: AtomicU64::new(0), written_entries: AtomicU64::new(0), read: AtomicU64::new(0), read_entries: AtomicU64::new(0), runs: Mutex::new(Vec::new()), }), osm_ingest::mem::SpillPlan::File => Self::create(path), } } /// Write one finished chunk and say where it went. /// /// 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. /// /// 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 { let entries = map.len() as u64; let mut len = 0u64; // The chunk's tile runs, offsets relative to the chunk start. `None` once a field would // not fit its `u32` (never in practice), which leaves the chunk unindexed. let mut runs: Option> = Some(Vec::new()); for (n, ((tile, layer_id), entry)) in map.iter().enumerate() { let cost = entry.layer.features.len() as u64 + entry.layer.coords.len() as u64; if let Some(list) = runs.as_mut() { let fits = |v: u64| u32::try_from(v).ok(); let ok = match list.last_mut() { Some(run) if run.tile == *tile => { fits(run.cost as u64 + cost).map(|c| run.cost = c).is_some() } _ => match (fits(cost), fits(len), fits(n as u64)) { (Some(cost), Some(rel_offset), Some(before)) => { list.push(TileRun { tile: *tile, cost, rel_offset, before }); true } _ => false, }, }; if !ok { runs = None; } } if *layer_id != entry.layer.layer_id { // The merge keys its heap on the map key and reads `layer_id` off the layer it // yields, so the two disagreeing would mean the round trip had to preserve both. It // is one field on disk because in this generator they are one field. return err(format!( "a tile chunk entry is keyed on layer {layer_id} but carries layer {}", entry.layer.layer_id )); } 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 = 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; *next += len; at }; let cursor = at + self.flush(&mut buf, at)?; if cursor != at + len { return err(format!("a tile chunk reserved {len} byte(s) and wrote {}", cursor - at)); } self.written.fetch_add(len, Ordering::Relaxed); self.written_entries.fetch_add(entries, Ordering::Relaxed); drop(_commit); // An empty chunk is never indexed: it has nothing to plan, and its start is the next // chunk's start, so a run list keyed on the offset alone could be handed to the wrong one // (which is what sent US West's z14 merge reading past chunk ends). The key carries the // length too, so even a zero-length key cannot meet a real chunk's. if let (Some(runs), true) = (runs, entries > 0) { self.runs.lock().expect("the tile chunk spill's run index").push(((at, len), runs)); } Ok(ChunkRef { at, len, entries }) } /// Write `buf` at `offset` and clear it. Returns what it wrote. fn flush(&self, buf: &mut Vec, offset: u64) -> Result { if buf.is_empty() { return Ok(0); } match (&self.file, &self.anon) { (Some(f), None) => write_all_at(f, buf, offset) .map_err(|e| Error(format!("writing {}: {e}", self.path.display())))?, (None, Some(a)) => { let mut store = a.lock().expect("the anon tile chunk spill"); // Positional: the cursor reservation above hands each chunk a // back-to-back range, flushed here in pieces. `write_at` // refuses gaps (a lost chunk) but accepts piece-wise fills. store .write_at(offset, buf) .map_err(|e| Error(format!("staging anon tile chunk: {e}")))?; } _ => return err("a tile chunk spill has no backend".to_string()), } let n = buf.len() as u64; buf.clear(); Ok(n) } /// The tile runs `write_chunk` recorded for every chunk, keyed by chunk start offset. Empty /// for a chunk written some other way (tests building chunks by hand), which the planner /// answers by skip-walking that chunk as it always did. pub fn take_runs(&self) -> std::collections::HashMap<(u64, u64), Vec> { std::mem::take(&mut *self.runs.lock().expect("the tile chunk spill's run index")) .into_iter() .collect() } /// A forward cursor over one chunk, buffering `window` bytes at a time. pub fn reader(&self, chunk: &ChunkRef, window: usize) -> ChunkReader<'_> { ChunkReader { spill: self, at: chunk.at, end: chunk.at + chunk.len, left: chunk.entries, buf: Vec::new(), used: 0, window: window.max(ENTRY_HEADER_BYTES), spare: None, exact_end: true, } } /// Reserved, written, on disk and read back must all agree. /// /// `tile_build::spill::BucketSet::seal`'s triple entry, for the same reason: a chunk that /// quietly lost entries would produce an archive with holes in it and nothing downstream could /// tell. Called once the merge has drained every reader. On the anon path "on disk" is the /// store's committed length — same check, no file. pub fn check_books(&self) -> Result<()> { let reserved = *self.at.lock().expect("the tile chunk spill's cursor"); let written = self.written.load(Ordering::Relaxed); if reserved != written { return err(format!( "{} reserved {reserved} byte(s) and wrote {written}", self.path.display() )); } let staged = match (&self.file, &self.anon) { // 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(), _ => return err("a tile chunk spill has no backend".to_string()), }; if staged != written { return err(format!( "{} stages {staged} byte(s) but {written} were written to it", self.path.display() )); } let read = self.read.load(Ordering::Relaxed); if read != written { return err(format!( "{} wrote {written} byte(s) and read back {read}", self.path.display() )); } let pushed = self.written_entries.load(Ordering::Relaxed); let pulled = self.read_entries.load(Ordering::Relaxed); if pushed != pulled { return err(format!( "{} wrote {pushed} entr(ies) and read back {pulled}", self.path.display() )); } Ok(()) } } impl Drop for ChunkSpill { fn drop(&mut self) { // 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; // 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); } } } /// A forward-only cursor over one chunk's byte range. /// /// Reads through `&ChunkSpill`, so every cursor in a merge shares one file handle. pub struct ChunkReader<'a> { spill: &'a ChunkSpill, /// Disk offset of the first byte not yet in `buf`. at: u64, /// One past the chunk's last byte. end: u64, /// Entries the header said were written and this cursor has not yielded. left: u64, buf: Vec, /// How much of `buf` has been yielded. used: usize, window: usize, /// A recycled entry's emptied arenas, handed back by the merge after it drains an entry into /// its accumulator. `decode` reuses these buffers instead of allocating four fresh `Vec`s per /// entry — the decode is on the serial merge thread, so its allocator churn is Amdahl time. /// `None` until the merge returns one; a decoded entry is byte-identical whether it was built /// from a recycled arena or a fresh one, because the contents are written the same way. spare: Option, /// Whether this cursor runs to the chunk's last byte. A range worker's /// segment ends mid-chunk (the next range owns what follows), so only a /// cursor that does reach the end enforces the no-trailing-bytes check — /// any other segment legitimately stops with unread bytes after it. exact_end: bool, }