Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / tile_build / src / spill_part5.rs
spill_part5.rs410 lines · 18.1 KiBRaw
| 1 | pub struct NormalizedWriter { |
| 2 | /// `None` while a background writer owns it (see [`BgWriter`]); back by `finish`. |
| 3 | out: Option<WriterSink>, |
| 4 | /// The thread staging compressed frames, started at the first batch. |
| 5 | bg: Option<BgWriter>, |
| 6 | path: PathBuf, |
| 7 | summary: NormalizedSummary, |
| 8 | rec: Vec<u8>, |
| 9 | /// The current chunk's raw records, accumulating until [`NORM_CHUNK_FEATURES`] are held. |
| 10 | /// Buffered rather than written per record because a frame is compressed as a unit: flushing |
| 11 | /// per record would be per-record frames (worse ratio, 1.9 B x 15 inflates). One chunk is |
| 12 | /// ~9 KB raw, noise next to every other peak in the build. |
| 13 | pending: Vec<u8>, |
| 14 | /// Records in `pending`. Counted rather than derived because records are variable-length. |
| 15 | pending_count: u64, |
| 16 | /// Sealed-but-not-yet-compressed frames (raw records), oldest first. Compressed on the pool |
| 17 | /// [`SEAL_BATCH`] at a time by [`drain_frames`](Self::drain_frames) and staged in order, so |
| 18 | /// DEFLATE leaves the serial push path while the bytes, offsets and chunk index stay exactly |
| 19 | /// what sealing one frame at a time produced. |
| 20 | queued: Vec<FrameSrc>, |
| 21 | /// Bytes written so far, which is the next frame's offset. Tracks *compressed* bytes: the |
| 22 | /// chunk index addresses frames, not records. |
| 23 | at: u64, |
| 24 | } |
| 25 | |
| 26 | /// DEFLATE level for spill frames. See [`NormalizedWriter::seal_frame`]. |
| 27 | const SPILL_DEFLATE_LEVEL: u8 = 1; |
| 28 | |
| 29 | /// Frames compressed per batch by [`NormalizedWriter::drain_frames`]. ~9 KB raw each on |
| 30 | /// California, so a batch is tens of MB in flight and one multi-MB write; large enough that |
| 31 | /// the pool hand-off is noise next to the DEFLATE it parallelises. |
| 32 | const SEAL_BATCH: usize = 4096; |
| 33 | |
| 34 | impl NormalizedWriter { |
| 35 | pub fn create(path: impl Into<PathBuf>) -> Result<NormalizedWriter> { |
| 36 | let path = path.into(); |
| 37 | if let Some(dir) = path.parent() { |
| 38 | if !dir.as_os_str().is_empty() { |
| 39 | std::fs::create_dir_all(dir) |
| 40 | .map_err(|e| Error(format!("cannot create {}: {e}", dir.display())))?; |
| 41 | } |
| 42 | } |
| 43 | let f = File::create(&path) |
| 44 | .map_err(|e| Error(format!("cannot create {}: {e}", path.display())))?; |
| 45 | let mut w = NormalizedWriter { |
| 46 | out: Some(WriterSink::File(BufWriter::with_capacity(8 << 20, f))), |
| 47 | bg: None, |
| 48 | path, |
| 49 | summary: NormalizedSummary::default(), |
| 50 | rec: Vec::new(), |
| 51 | pending: Vec::new(), |
| 52 | pending_count: 0, |
| 53 | queued: Vec::new(), |
| 54 | // The first frame starts past the file header; the chunk index's first offset |
| 55 | // records exactly this, so readers never special-case it. |
| 56 | at: NORM_FILE_HEADER_BYTES as u64, |
| 57 | }; |
| 58 | w.write_file_header()?; |
| 59 | Ok(w) |
| 60 | } |
| 61 | |
| 62 | /// Anonymous twin of [`create`](Self::create): same records and offsets, |
| 63 | /// staged in pagefile-backed memory with no file. `path` names nothing on |
| 64 | /// disk — it only rides along for error messages. Pair with |
| 65 | /// [`NormalizedChunks::open_anon`] on the way back. |
| 66 | pub fn create_anon(path: impl Into<PathBuf>) -> Result<NormalizedWriter> { |
| 67 | let mut w = NormalizedWriter { |
| 68 | out: Some(WriterSink::Anon(crate::anon::AnonStore::new())), |
| 69 | bg: None, |
| 70 | path: path.into(), |
| 71 | summary: NormalizedSummary::default(), |
| 72 | rec: Vec::new(), |
| 73 | pending: Vec::new(), |
| 74 | pending_count: 0, |
| 75 | queued: Vec::new(), |
| 76 | at: NORM_FILE_HEADER_BYTES as u64, |
| 77 | }; |
| 78 | w.write_file_header()?; |
| 79 | Ok(w) |
| 80 | } |
| 81 | |
| 82 | /// The 8-byte file header: magic, version, reserved zero. Written once, before the first |
| 83 | /// frame, on both backends -- so anon and file bytes are identical and every reader parses |
| 84 | /// one layout. |
| 85 | fn write_file_header(&mut self) -> Result<()> { |
| 86 | let mut head = [0u8; NORM_FILE_HEADER_BYTES]; |
| 87 | head[0..4].copy_from_slice(NORM_MAGIC); |
| 88 | head[4] = NORM_VERSION; |
| 89 | match self.out.as_mut().expect("the header is written before any batch") { |
| 90 | WriterSink::File(f) => f |
| 91 | .write_all(&head) |
| 92 | .map_err(|e| Error(format!("writing {}: {e}", self.path.display())))?, |
| 93 | WriterSink::Anon(a) => { |
| 94 | a.push(&head)?; |
| 95 | } |
| 96 | } |
| 97 | Ok(()) |
| 98 | } |
| 99 | |
| 100 | /// A line the caller could not use. Counted here so the summary is the one place |
| 101 | /// the whole pass is described. |
| 102 | pub fn skip(&mut self) { |
| 103 | self.summary.skipped += 1; |
| 104 | } |
| 105 | |
| 106 | pub fn push(&mut self, geometry: &Geometry, props: &[(String, Value)]) -> Result<()> { |
| 107 | self.rec.clear(); |
| 108 | self.rec.resize(NORM_HEADER_BYTES, 0); |
| 109 | encode_geometry(geometry, &mut self.rec)?; |
| 110 | let geom_len = count(self.rec.len() - NORM_HEADER_BYTES)?; |
| 111 | encode_props(props, &mut self.rec)?; |
| 112 | let props_len = count(self.rec.len() - NORM_HEADER_BYTES - geom_len as usize)?; |
| 113 | let rec_len = count(self.rec.len())?; |
| 114 | self.rec[0..4].copy_from_slice(&rec_len.to_le_bytes()); |
| 115 | self.rec[4..8].copy_from_slice(&geom_len.to_le_bytes()); |
| 116 | self.rec[8..12].copy_from_slice(&props_len.to_le_bytes()); |
| 117 | self.rec[12] = GeomKind::of(geometry).tag(); |
| 118 | // Buffered, not written: a frame is one chunk's records compressed as a unit. The index |
| 119 | // entry below still fires on the same 64-feature boundary, so entry `i` still describes |
| 120 | // chunk `i` -- only the bytes behind the offset are frames now. |
| 121 | self.pending.extend_from_slice(&self.rec); |
| 122 | self.pending_count += 1; |
| 123 | // The chunk index entry for this frame is recorded when the frame is staged |
| 124 | // (`drain_frames`), which is when its offset is known: frames are compressed in |
| 125 | // batches, so `at` here still lags the frames queued ahead of this one. |
| 126 | if self.pending_count >= NORM_CHUNK_FEATURES { |
| 127 | self.seal_frame()?; |
| 128 | } |
| 129 | |
| 130 | if self.summary.geom_kind.is_none() { |
| 131 | self.summary.geom_kind = Some(GeomKind::of(geometry)); |
| 132 | } |
| 133 | self.summary.bounds = crate::pyramid::fold_bounds(self.summary.bounds, geometry); |
| 134 | self.summary.count += 1; |
| 135 | Ok(()) |
| 136 | } |
| 137 | |
| 138 | /// [`push`](Self::push) for a geometry encoded off-thread: the same record |
| 139 | /// layout with the geometry bytes supplied instead of encoded here. |
| 140 | /// |
| 141 | /// The materialise drains resolve + encode + region-test each batch on the |
| 142 | /// pool and append the records in order here, so the serial thread does no |
| 143 | /// vertex walk. Byte-identical to `push`: `geom_bytes` must be what |
| 144 | /// [`encode_geometry`](crate::spill::encode_geometry) produced for the same |
| 145 | /// geometry, `kind` its [`GeomKind`], `bounds` its |
| 146 | /// [`bounds`](crate::geom::bounds) — all pure functions, so computing them |
| 147 | /// on the pool changes no byte. Order, chunk index, sealing and the bounds |
| 148 | /// fold are untouched: they happen here, serially, exactly as in `push`. |
| 149 | pub fn push_preencoded( |
| 150 | &mut self, |
| 151 | kind: GeomKind, |
| 152 | geom_bytes: &[u8], |
| 153 | bounds: Option<crate::geom::Rect>, |
| 154 | props: &[(String, Value)], |
| 155 | ) -> Result<()> { |
| 156 | let mut rec = std::mem::take(&mut self.rec); |
| 157 | let built = encode_normalized_record(kind, geom_bytes, props, &mut rec); |
| 158 | let pushed = built.and_then(|()| self.push_record(kind, &rec, bounds)); |
| 159 | self.rec = rec; |
| 160 | pushed |
| 161 | } |
| 162 | |
| 163 | /// Append one record [`encode_normalized_record`] already built (on the pool): the serial half of |
| 164 | /// [`push_preencoded`](Self::push_preencoded), byte-for-byte. `kind` and `bounds` are the |
| 165 | /// record's own, as `push_preencoded` takes them. |
| 166 | pub fn push_record( |
| 167 | &mut self, |
| 168 | kind: GeomKind, |
| 169 | rec: &[u8], |
| 170 | bounds: Option<crate::geom::Rect>, |
| 171 | ) -> Result<()> { |
| 172 | self.pending.extend_from_slice(rec); |
| 173 | self.pending_count += 1; |
| 174 | // The chunk index entry for this frame is recorded when the frame is staged |
| 175 | // (`drain_frames`), which is when its offset is known. |
| 176 | if self.pending_count >= NORM_CHUNK_FEATURES { |
| 177 | self.seal_frame()?; |
| 178 | } |
| 179 | |
| 180 | if self.summary.geom_kind.is_none() { |
| 181 | self.summary.geom_kind = Some(kind); |
| 182 | } |
| 183 | self.summary.bounds = match (self.summary.bounds, bounds) { |
| 184 | (None, b) => b, |
| 185 | (a, None) => a, |
| 186 | (Some(a), Some(b)) => Some(crate::geom::Rect { |
| 187 | min_x: a.min_x.min(b.min_x), |
| 188 | min_y: a.min_y.min(b.min_y), |
| 189 | max_x: a.max_x.max(b.max_x), |
| 190 | max_y: a.max_y.max(b.max_y), |
| 191 | }), |
| 192 | }; |
| 193 | self.summary.count += 1; |
| 194 | Ok(()) |
| 195 | } |
| 196 | |
| 197 | /// Compress the buffered chunk into one frame and stage it. |
| 198 | /// |
| 199 | /// Level 1, not 6: the write happens once (stage A, serial sink) while the reads happen |
| 200 | /// fifteen times (parallel prefetch lanes), which is what argued for 6 — ratio over deflate |
| 201 | /// speed, with level-independent inflate. Measured on California, that argument was wrong: |
| 202 | /// level 6 spends ~27 s of a 61 s `materialise-ways` serial drain in DEFLATE while level 1 |
| 203 | /// spends ~0 s for ~5% more scratch bytes (scratch, deleted on success; the budget gate |
| 204 | /// sizes commit with headroom). The drain is serial and order-critical, so its wall is |
| 205 | /// Amdahl time; the spill size is not. |
| 206 | /// |
| 207 | /// The level is a constant, not a knob: the frame header carries no level mark because |
| 208 | /// inflate is level-independent, so the choice changes only scratch bytes, never the |
| 209 | /// archive — and an operator knob here would trade build minutes for scratch bytes with |
| 210 | /// no content effect either way. Re-measure (drain wall + spill GB) before touching it. |
| 211 | fn seal_frame(&mut self) -> Result<()> { |
| 212 | if self.pending.is_empty() { |
| 213 | return Ok(()); |
| 214 | } |
| 215 | // Queued raw, compressed later in a batch: see `drain_frames`. `take` leaves `pending` |
| 216 | // empty for the next chunk; the frame owns its bytes until it is staged. |
| 217 | self.queued.push(FrameSrc::Owned(std::mem::take(&mut self.pending))); |
| 218 | self.pending_count = 0; |
| 219 | if self.queued.len() >= SEAL_BATCH { |
| 220 | self.drain_frames()?; |
| 221 | } |
| 222 | Ok(()) |
| 223 | } |
| 224 | |
| 225 | /// Compress every queued frame (on the pool when there is more than one) and stage them in |
| 226 | /// queue order, recording each frame's chunk-index offset as it lands. |
| 227 | /// |
| 228 | /// Byte-identical to sealing frames one at a time: DEFLATE is a pure function of a frame's |
| 229 | /// bytes and the level, the frames are staged in the order they were sealed, and each index |
| 230 | /// entry is the offset the frame is written at -- exactly the `at` the per-frame path |
| 231 | /// recorded at the frame's first record, since every frame starts on a |
| 232 | /// `NORM_CHUNK_FEATURES` boundary and the frames before it were staged first. |
| 233 | /// |
| 234 | /// The batch also turns the writes into one large sequential write per batch (megabytes) |
| 235 | /// rather than one per 64-feature frame. |
| 236 | fn drain_frames(&mut self) -> Result<()> { |
| 237 | if self.queued.is_empty() { |
| 238 | return Ok(()); |
| 239 | } |
| 240 | let frames = std::mem::take(&mut self.queued); |
| 241 | let compressed: Vec<Vec<u8>> = if frames.len() == 1 { |
| 242 | vec![miniz_oxide::deflate::compress_to_vec(frames[0].bytes(), SPILL_DEFLATE_LEVEL)] |
| 243 | } else { |
| 244 | use rayon::prelude::*; |
| 245 | crate::par::install(|| { |
| 246 | frames |
| 247 | .par_iter() |
| 248 | .map(|raw| miniz_oxide::deflate::compress_to_vec(raw.bytes(), SPILL_DEFLATE_LEVEL)) |
| 249 | .collect() |
| 250 | }) |
| 251 | }; |
| 252 | drop(frames); |
| 253 | // Each frame's offset is known here, from the sizes alone (a prefix sum from `at`), so |
| 254 | // the chunk index is complete before a byte is written; the bytes themselves go to the |
| 255 | // background writer, which stages them in this same order. The serial pusher no longer |
| 256 | // waits on the copy into the buffer or on the write. |
| 257 | for frame in &compressed { |
| 258 | u32::try_from(frame.len()) |
| 259 | .map_err(|_| Error("a spill frame is larger than 4 GiB".to_string()))?; |
| 260 | self.summary.chunks.push(self.at); |
| 261 | self.at += 4 + frame.len() as u64; |
| 262 | } |
| 263 | if self.bg.is_none() { |
| 264 | let out = self.out.take().expect("the sink is here until the writer starts"); |
| 265 | self.bg = Some(BgWriter::start(out, self.path.clone())); |
| 266 | } |
| 267 | self.bg.as_ref().expect("started above").send(compressed) |
| 268 | } |
| 269 | |
| 270 | /// Stop the background writer, if one ran, and take the sink back: every frame staged. |
| 271 | fn join_bg(&mut self) -> Result<()> { |
| 272 | if let Some(bg) = self.bg.take() { |
| 273 | self.out = Some(bg.finish()?); |
| 274 | } |
| 275 | Ok(()) |
| 276 | } |
| 277 | |
| 278 | /// Append a run of records the caller encoded off-thread, all at once: what calling |
| 279 | /// [`push_record`](Self::push_record) for each would do, without the per-record work on the |
| 280 | /// serial thread. `ends[i]` is the end offset of record `i` in `bytes`; `first_kind` the |
| 281 | /// first record's kind; `bounds` the fold of every record's bounds. |
| 282 | /// |
| 283 | /// Byte-identical to the per-record path: frames close on the same 64-record boundaries |
| 284 | /// (records topping up the open frame are copied into it, whole frames inside the run are |
| 285 | /// compressed straight out of `bytes`, the tail is copied into the next open frame), the chunk |
| 286 | /// index entries are recorded the same way, and the summary folds are associative. |
| 287 | pub fn push_run( |
| 288 | &mut self, |
| 289 | bytes: Vec<u8>, |
| 290 | ends: &[usize], |
| 291 | first_kind: Option<GeomKind>, |
| 292 | bounds: Option<crate::geom::Rect>, |
| 293 | ) -> Result<()> { |
| 294 | let n = ends.len(); |
| 295 | if n == 0 { |
| 296 | return Ok(()); |
| 297 | } |
| 298 | let bytes = std::sync::Arc::new(bytes); |
| 299 | let start_of = |i: usize| if i == 0 { 0 } else { ends[i - 1] }; |
| 300 | let per = NORM_CHUNK_FEATURES as usize; |
| 301 | let mut i = 0usize; |
| 302 | if self.pending_count > 0 { |
| 303 | let k = (per - self.pending_count as usize).min(n); |
| 304 | self.pending.extend_from_slice(&bytes[..start_of(k)]); |
| 305 | self.pending_count += k as u64; |
| 306 | i = k; |
| 307 | if self.pending_count >= NORM_CHUNK_FEATURES { |
| 308 | self.seal_frame()?; |
| 309 | } |
| 310 | } |
| 311 | while n - i >= per { |
| 312 | self.queued.push(FrameSrc::Shared(std::sync::Arc::clone(&bytes), start_of(i)..start_of(i + per))); |
| 313 | i += per; |
| 314 | if self.queued.len() >= SEAL_BATCH { |
| 315 | self.drain_frames()?; |
| 316 | } |
| 317 | } |
| 318 | if i < n { |
| 319 | self.pending.extend_from_slice(&bytes[start_of(i)..]); |
| 320 | self.pending_count += (n - i) as u64; |
| 321 | } |
| 322 | if self.summary.geom_kind.is_none() { |
| 323 | self.summary.geom_kind = first_kind; |
| 324 | } |
| 325 | self.summary.bounds = match (self.summary.bounds, bounds) { |
| 326 | (None, b) => b, |
| 327 | (a, None) => a, |
| 328 | (Some(a), Some(b)) => Some(crate::geom::Rect { |
| 329 | min_x: a.min_x.min(b.min_x), |
| 330 | min_y: a.min_y.min(b.min_y), |
| 331 | max_x: a.max_x.max(b.max_x), |
| 332 | max_y: a.max_y.max(b.max_y), |
| 333 | }), |
| 334 | }; |
| 335 | self.summary.count += n as u64; |
| 336 | Ok(()) |
| 337 | } |
| 338 | |
| 339 | /// Compressed bytes staged so far (frames plus file header). For spill-size |
| 340 | /// measurement: the budget calibrator (`SPILL_BYTES_PER_FEATURE`) is tuned |
| 341 | /// per deflate level, so level experiments report this alongside the wall. |
| 342 | /// Lags by the frames still queued for batch compression until `finish`. |
| 343 | pub fn staged_bytes(&self) -> u64 { |
| 344 | self.at |
| 345 | } |
| 346 | |
| 347 | /// Flush, and hand back what the pass learned. |
| 348 | pub fn finish(mut self) -> Result<NormalizedSummary> { |
| 349 | // The last chunk is usually partial and still needs its frame -- without this its |
| 350 | // records would be buffered and never staged. |
| 351 | self.seal_frame()?; |
| 352 | self.drain_frames()?; |
| 353 | self.join_bg()?; |
| 354 | self.flush_out()?; |
| 355 | // Close the last chunk. Without this the final partial chunk has no end, and |
| 356 | // `chunk_count` would also over-report by one. |
| 357 | if !self.summary.chunks.is_empty() { |
| 358 | self.summary.chunks.push(self.at); |
| 359 | } |
| 360 | Ok(self.summary) |
| 361 | } |
| 362 | |
| 363 | /// Flush, and hand back what the pass learned plus whatever backend holds the bytes. |
| 364 | /// |
| 365 | /// Unifies [`finish`](Self::finish) and [`finish_anon`](Self::finish_anon): callers that pick |
| 366 | /// the backend by budget ([`osm_ingest::mem::SpillPlan`]) seal without knowing which one they |
| 367 | /// chose. A file backend yields no store -- its bytes live at the path it was created with, |
| 368 | /// and readers open that path. |
| 369 | pub fn finish_either(mut self) -> Result<(NormalizedSummary, Option<crate::anon::AnonStore>)> { |
| 370 | self.seal_frame()?; |
| 371 | self.drain_frames()?; |
| 372 | self.join_bg()?; |
| 373 | self.flush_out()?; |
| 374 | if !self.summary.chunks.is_empty() { |
| 375 | self.summary.chunks.push(self.at); |
| 376 | } |
| 377 | match self.out.take().expect("joined above") { |
| 378 | WriterSink::Anon(a) => Ok((self.summary, Some(a))), |
| 379 | WriterSink::File(_) => Ok((self.summary, None)), |
| 380 | } |
| 381 | } |
| 382 | |
| 383 | /// Anonymous twin of [`finish`](Self::finish): flush, hand back the summary |
| 384 | /// AND the staged store for [`NormalizedChunks::open_anon`]. Errors when |
| 385 | /// this writer is file-backed (a programming bug, not a runtime one). |
| 386 | pub fn finish_anon(mut self) -> Result<(NormalizedSummary, crate::anon::AnonStore)> { |
| 387 | self.seal_frame()?; |
| 388 | self.drain_frames()?; |
| 389 | self.join_bg()?; |
| 390 | self.flush_out()?; |
| 391 | if !self.summary.chunks.is_empty() { |
| 392 | self.summary.chunks.push(self.at); |
| 393 | } |
| 394 | match self.out.take().expect("joined above") { |
| 395 | WriterSink::Anon(a) => Ok((self.summary, a)), |
| 396 | WriterSink::File(_) => err("finish_anon on a file-backed writer".to_string()), |
| 397 | } |
| 398 | } |
| 399 | |
| 400 | fn flush_out(&mut self) -> Result<()> { |
| 401 | match self.out.as_mut().expect("joined before flushing") { |
| 402 | WriterSink::File(f) => f |
| 403 | .flush() |
| 404 | .map_err(|e| Error(format!("flushing {}: {e}", self.path.display())))?, |
| 405 | WriterSink::Anon(a) => a.finish(), |
| 406 | } |
| 407 | Ok(()) |
| 408 | } |
| 409 | } |
| 410 |