Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
dependencies ▾

Modern-Apps.git / scripts / maps / mamaps_build / src / tilespill_s1.rs

tilespill_s1.rs287 lines · 13.2 KiBRaw
1impl ChunkSpill {
2 /// Create the scratch file, truncating whatever a killed run left at the path.
3 ///
4 /// Read *and* write on one handle, because that is the whole shape of this module: the workers
5 /// write positionally through it and the merge reads positionally through it, and a second
6 /// handle would be a second file description with nothing to gain.
7 pub fn create(path: impl Into<PathBuf>) -> Result<ChunkSpill> {
8 let path = path.into();
9 let file = std::fs::OpenOptions::new()
10 .read(true)
11 .write(true)
12 .create(true)
13 .truncate(true)
14 .open(&path)
15 .map_err(|e| Error(format!("cannot create {}: {e}", path.display())))?;
16 // Uncompressed on a `compress-force` btrfs: every zoom's clipped geometry passes through
17 // here (hundreds of GB over a planet build), written once, read back by the merge.
18 osm_ingest::mem::mark_scratch_uncompressed(&file);
19 // Every read and write goes through this one handle, so the name can go now: a build
20 // killed mid-zoom leaves no tile-chunk scratch behind (tens of GB at planet z14).
21 let unlinked = osm_ingest::mem::unlink_open_scratch(&path);
22 Ok(ChunkSpill {
23 unlinked,
24 file: Some(file),
25 anon: None,
26 path,
27 at: Mutex::new(0),
28 write: Mutex::new(()),
29 written: AtomicU64::new(0),
30 written_entries: AtomicU64::new(0),
31 read: AtomicU64::new(0),
32 read_entries: AtomicU64::new(0),
33 runs: Mutex::new(Vec::new()),
34 })
35 }
36
37 /// Create with an explicit staging plan. See [`osm_ingest::mem::SpillPlan::decide`]: the
38 /// budget gate picks `File` when anon commit does not fit, and `File` stages through the
39 /// scratch path (truncated like [`create`](Self::create), removed on drop). Same chunks,
40 /// same offsets, same bytes -- the backend never changes a hash.
41 pub fn create_planned(
42 path: impl Into<PathBuf>,
43 plan: osm_ingest::mem::SpillPlan,
44 ) -> Result<ChunkSpill> {
45 match plan {
46 osm_ingest::mem::SpillPlan::Anon => Ok(ChunkSpill {
47 unlinked: false,
48 file: None,
49 anon: Some(std::sync::Mutex::new(tile_build::anon::AnonStore::new())),
50 path: path.into(),
51 at: Mutex::new(0),
52 write: Mutex::new(()),
53 written: AtomicU64::new(0),
54 written_entries: AtomicU64::new(0),
55 read: AtomicU64::new(0),
56 read_entries: AtomicU64::new(0),
57 runs: Mutex::new(Vec::new()),
58 }),
59 osm_ingest::mem::SpillPlan::File => Self::create(path),
60 }
61 }
62
63 /// Write one finished chunk and say where it went.
64 ///
65 /// Takes the map **by value** and encodes out of `into_iter`, so the map shrinks as it is
66 /// written instead of being copied whole into a buffer beside itself.
67 ///
68 /// Encode happens outside any lock, in parallel across workers. The commit — reserving the
69 /// byte range and writing it — holds the `write` lock for one sequential write per chunk.
70 /// Reservation order is therefore completion order and the file offset advances
71 /// monotonically: no interleaved 1 MB pieces from N workers sharing one file offset space,
72 /// which is what turned N parallel positional fills into random-write interleaving on
73 /// spinning disks (and page-cache churn everywhere). The merge sorts chunks by their read
74 /// index, never by file position, so the layout change is not observable in the archive.
75 pub fn write_chunk(&self, map: BTreeMap<(u64, u8), ChunkEntry>) -> Result<ChunkRef> {
76 let entries = map.len() as u64;
77 let mut len = 0u64;
78 // The chunk's tile runs, offsets relative to the chunk start. `None` once a field would
79 // not fit its `u32` (never in practice), which leaves the chunk unindexed.
80 let mut runs: Option<Vec<TileRun>> = Some(Vec::new());
81 for (n, ((tile, layer_id), entry)) in map.iter().enumerate() {
82 let cost = entry.layer.features.len() as u64 + entry.layer.coords.len() as u64;
83 if let Some(list) = runs.as_mut() {
84 let fits = |v: u64| u32::try_from(v).ok();
85 let ok = match list.last_mut() {
86 Some(run) if run.tile == *tile => {
87 fits(run.cost as u64 + cost).map(|c| run.cost = c).is_some()
88 }
89 _ => match (fits(cost), fits(len), fits(n as u64)) {
90 (Some(cost), Some(rel_offset), Some(before)) => {
91 list.push(TileRun { tile: *tile, cost, rel_offset, before });
92 true
93 }
94 _ => false,
95 },
96 };
97 if !ok {
98 runs = None;
99 }
100 }
101 if *layer_id != entry.layer.layer_id {
102 // The merge keys its heap on the map key and reads `layer_id` off the layer it
103 // yields, so the two disagreeing would mean the round trip had to preserve both. It
104 // is one field on disk because in this generator they are one field.
105 return err(format!(
106 "a tile chunk entry is keyed on layer {layer_id} but carries layer {}",
107 entry.layer.layer_id
108 ));
109 }
110 len += entry_bytes(entry)?;
111 }
112
113 // Encoded before the commit lock, so N workers still clip and encode in parallel and
114 // only the disk write itself is serial. Sized exactly: `len` above is the encoded
115 // length, so this is one allocation per chunk rather than a growing buffer.
116 let mut buf: Vec<u8> = Vec::with_capacity(len as usize);
117 for ((tile, layer_id), layer) in map {
118 encode_entry(tile, layer_id, &layer, &mut buf);
119 }
120 debug_assert_eq!(buf.len() as u64, len, "the encoded chunk must match its reservation");
121
122 // One commit per chunk: reserve and write under the same lock, so the file sees whole
123 // sequential chunks in reservation order. Always `write` before `at`.
124 let _commit = self.write.lock().expect("the tile chunk spill's commit lock");
125 let at = {
126 let mut next = self.at.lock().expect("the tile chunk spill's cursor");
127 let at = *next;
128 *next += len;
129 at
130 };
131
132 let cursor = at + self.flush(&mut buf, at)?;
133
134 if cursor != at + len {
135 return err(format!("a tile chunk reserved {len} byte(s) and wrote {}", cursor - at));
136 }
137 self.written.fetch_add(len, Ordering::Relaxed);
138 self.written_entries.fetch_add(entries, Ordering::Relaxed);
139 drop(_commit);
140 // An empty chunk is never indexed: it has nothing to plan, and its start is the next
141 // chunk's start, so a run list keyed on the offset alone could be handed to the wrong one
142 // (which is what sent US West's z14 merge reading past chunk ends). The key carries the
143 // length too, so even a zero-length key cannot meet a real chunk's.
144 if let (Some(runs), true) = (runs, entries > 0) {
145 self.runs.lock().expect("the tile chunk spill's run index").push(((at, len), runs));
146 }
147 Ok(ChunkRef { at, len, entries })
148 }
149
150 /// Write `buf` at `offset` and clear it. Returns what it wrote.
151 fn flush(&self, buf: &mut Vec<u8>, offset: u64) -> Result<u64> {
152 if buf.is_empty() {
153 return Ok(0);
154 }
155 match (&self.file, &self.anon) {
156 (Some(f), None) => write_all_at(f, buf, offset)
157 .map_err(|e| Error(format!("writing {}: {e}", self.path.display())))?,
158 (None, Some(a)) => {
159 let mut store = a.lock().expect("the anon tile chunk spill");
160 // Positional: the cursor reservation above hands each chunk a
161 // back-to-back range, flushed here in pieces. `write_at`
162 // refuses gaps (a lost chunk) but accepts piece-wise fills.
163 store
164 .write_at(offset, buf)
165 .map_err(|e| Error(format!("staging anon tile chunk: {e}")))?;
166 }
167 _ => return err("a tile chunk spill has no backend".to_string()),
168 }
169 let n = buf.len() as u64;
170 buf.clear();
171 Ok(n)
172 }
173
174 /// The tile runs `write_chunk` recorded for every chunk, keyed by chunk start offset. Empty
175 /// for a chunk written some other way (tests building chunks by hand), which the planner
176 /// answers by skip-walking that chunk as it always did.
177 pub fn take_runs(&self) -> std::collections::HashMap<(u64, u64), Vec<TileRun>> {
178 std::mem::take(&mut *self.runs.lock().expect("the tile chunk spill's run index"))
179 .into_iter()
180 .collect()
181 }
182
183 /// A forward cursor over one chunk, buffering `window` bytes at a time.
184 pub fn reader(&self, chunk: &ChunkRef, window: usize) -> ChunkReader<'_> {
185 ChunkReader {
186 spill: self,
187 at: chunk.at,
188 end: chunk.at + chunk.len,
189 left: chunk.entries,
190 buf: Vec::new(),
191 used: 0,
192 window: window.max(ENTRY_HEADER_BYTES),
193 spare: None,
194 exact_end: true,
195 }
196 }
197
198 /// Reserved, written, on disk and read back must all agree.
199 ///
200 /// `tile_build::spill::BucketSet::seal`'s triple entry, for the same reason: a chunk that
201 /// quietly lost entries would produce an archive with holes in it and nothing downstream could
202 /// tell. Called once the merge has drained every reader. On the anon path "on disk" is the
203 /// store's committed length — same check, no file.
204 pub fn check_books(&self) -> Result<()> {
205 let reserved = *self.at.lock().expect("the tile chunk spill's cursor");
206 let written = self.written.load(Ordering::Relaxed);
207 if reserved != written {
208 return err(format!(
209 "{} reserved {reserved} byte(s) and wrote {written}",
210 self.path.display()
211 ));
212 }
213 let staged = match (&self.file, &self.anon) {
214 // Through the handle: the name is unlinked at creation.
215 (Some(f), None) => f
216 .metadata()
217 .map_err(|e| Error(format!("cannot stat {}: {e}", self.path.display())))?
218 .len(),
219 (None, Some(a)) => a.lock().expect("the anon tile chunk spill").len(),
220 _ => return err("a tile chunk spill has no backend".to_string()),
221 };
222 if staged != written {
223 return err(format!(
224 "{} stages {staged} byte(s) but {written} were written to it",
225 self.path.display()
226 ));
227 }
228 let read = self.read.load(Ordering::Relaxed);
229 if read != written {
230 return err(format!(
231 "{} wrote {written} byte(s) and read back {read}",
232 self.path.display()
233 ));
234 }
235 let pushed = self.written_entries.load(Ordering::Relaxed);
236 let pulled = self.read_entries.load(Ordering::Relaxed);
237 if pushed != pulled {
238 return err(format!(
239 "{} wrote {pushed} entr(ies) and read back {pulled}",
240 self.path.display()
241 ));
242 }
243 Ok(())
244 }
245}
246
247impl Drop for ChunkSpill {
248 fn drop(&mut self) {
249 // The handle first, or Windows refuses the delete. Anon path holds no
250 // handle and no file: nothing to do, the mapping frees with the store.
251 self.file = None;
252 // Not when the name was unlinked at creation: per-zoom spills share one path, so the
253 // name may by now belong to the next zoom's file.
254 if self.anon.is_none() && !self.unlinked {
255 let _ = std::fs::remove_file(&self.path);
256 }
257 }
258}
259
260/// A forward-only cursor over one chunk's byte range.
261///
262/// Reads through `&ChunkSpill`, so every cursor in a merge shares one file handle.
263pub struct ChunkReader<'a> {
264 spill: &'a ChunkSpill,
265 /// Disk offset of the first byte not yet in `buf`.
266 at: u64,
267 /// One past the chunk's last byte.
268 end: u64,
269 /// Entries the header said were written and this cursor has not yielded.
270 left: u64,
271 buf: Vec<u8>,
272 /// How much of `buf` has been yielded.
273 used: usize,
274 window: usize,
275 /// A recycled entry's emptied arenas, handed back by the merge after it drains an entry into
276 /// its accumulator. `decode` reuses these buffers instead of allocating four fresh `Vec`s per
277 /// entry — the decode is on the serial merge thread, so its allocator churn is Amdahl time.
278 /// `None` until the merge returns one; a decoded entry is byte-identical whether it was built
279 /// from a recycled arena or a fresh one, because the contents are written the same way.
280 spare: Option<ChunkEntry>,
281 /// Whether this cursor runs to the chunk's last byte. A range worker's
282 /// segment ends mid-chunk (the next range owns what follows), so only a
283 /// cursor that does reach the end enforces the no-trailing-bytes check —
284 /// any other segment legitimately stops with unread bytes after it.
285 exact_end: bool,
286}
287