pub struct NormalizedWriter { /// `None` while a background writer owns it (see [`BgWriter`]); back by `finish`. out: Option, /// The thread staging compressed frames, started at the first batch. bg: Option, path: PathBuf, summary: NormalizedSummary, rec: Vec, /// The current chunk's raw records, accumulating until [`NORM_CHUNK_FEATURES`] are held. /// Buffered rather than written per record because a frame is compressed as a unit: flushing /// per record would be per-record frames (worse ratio, 1.9 B x 15 inflates). One chunk is /// ~9 KB raw, noise next to every other peak in the build. pending: Vec, /// Records in `pending`. Counted rather than derived because records are variable-length. pending_count: u64, /// Sealed-but-not-yet-compressed frames (raw records), oldest first. Compressed on the pool /// [`SEAL_BATCH`] at a time by [`drain_frames`](Self::drain_frames) and staged in order, so /// DEFLATE leaves the serial push path while the bytes, offsets and chunk index stay exactly /// what sealing one frame at a time produced. queued: Vec, /// Bytes written so far, which is the next frame's offset. Tracks *compressed* bytes: the /// chunk index addresses frames, not records. at: u64, } /// DEFLATE level for spill frames. See [`NormalizedWriter::seal_frame`]. const SPILL_DEFLATE_LEVEL: u8 = 1; /// Frames compressed per batch by [`NormalizedWriter::drain_frames`]. ~9 KB raw each on /// California, so a batch is tens of MB in flight and one multi-MB write; large enough that /// the pool hand-off is noise next to the DEFLATE it parallelises. const SEAL_BATCH: usize = 4096; impl NormalizedWriter { pub fn create(path: impl Into) -> Result { let path = path.into(); if let Some(dir) = path.parent() { if !dir.as_os_str().is_empty() { std::fs::create_dir_all(dir) .map_err(|e| Error(format!("cannot create {}: {e}", dir.display())))?; } } let f = File::create(&path) .map_err(|e| Error(format!("cannot create {}: {e}", path.display())))?; let mut w = NormalizedWriter { out: Some(WriterSink::File(BufWriter::with_capacity(8 << 20, f))), bg: None, path, summary: NormalizedSummary::default(), rec: Vec::new(), pending: Vec::new(), pending_count: 0, queued: Vec::new(), // The first frame starts past the file header; the chunk index's first offset // records exactly this, so readers never special-case it. at: NORM_FILE_HEADER_BYTES as u64, }; w.write_file_header()?; Ok(w) } /// Anonymous twin of [`create`](Self::create): same records and offsets, /// staged in pagefile-backed memory with no file. `path` names nothing on /// disk — it only rides along for error messages. Pair with /// [`NormalizedChunks::open_anon`] on the way back. pub fn create_anon(path: impl Into) -> Result { let mut w = NormalizedWriter { out: Some(WriterSink::Anon(crate::anon::AnonStore::new())), bg: None, path: path.into(), summary: NormalizedSummary::default(), rec: Vec::new(), pending: Vec::new(), pending_count: 0, queued: Vec::new(), at: NORM_FILE_HEADER_BYTES as u64, }; w.write_file_header()?; Ok(w) } /// The 8-byte file header: magic, version, reserved zero. Written once, before the first /// frame, on both backends -- so anon and file bytes are identical and every reader parses /// one layout. fn write_file_header(&mut self) -> Result<()> { let mut head = [0u8; NORM_FILE_HEADER_BYTES]; head[0..4].copy_from_slice(NORM_MAGIC); head[4] = NORM_VERSION; match self.out.as_mut().expect("the header is written before any batch") { WriterSink::File(f) => f .write_all(&head) .map_err(|e| Error(format!("writing {}: {e}", self.path.display())))?, WriterSink::Anon(a) => { a.push(&head)?; } } Ok(()) } /// A line the caller could not use. Counted here so the summary is the one place /// the whole pass is described. pub fn skip(&mut self) { self.summary.skipped += 1; } pub fn push(&mut self, geometry: &Geometry, props: &[(String, Value)]) -> Result<()> { self.rec.clear(); self.rec.resize(NORM_HEADER_BYTES, 0); encode_geometry(geometry, &mut self.rec)?; let geom_len = count(self.rec.len() - NORM_HEADER_BYTES)?; encode_props(props, &mut self.rec)?; let props_len = count(self.rec.len() - NORM_HEADER_BYTES - geom_len as usize)?; let rec_len = count(self.rec.len())?; self.rec[0..4].copy_from_slice(&rec_len.to_le_bytes()); self.rec[4..8].copy_from_slice(&geom_len.to_le_bytes()); self.rec[8..12].copy_from_slice(&props_len.to_le_bytes()); self.rec[12] = GeomKind::of(geometry).tag(); // Buffered, not written: a frame is one chunk's records compressed as a unit. The index // entry below still fires on the same 64-feature boundary, so entry `i` still describes // chunk `i` -- only the bytes behind the offset are frames now. self.pending.extend_from_slice(&self.rec); self.pending_count += 1; // The chunk index entry for this frame is recorded when the frame is staged // (`drain_frames`), which is when its offset is known: frames are compressed in // batches, so `at` here still lags the frames queued ahead of this one. if self.pending_count >= NORM_CHUNK_FEATURES { self.seal_frame()?; } if self.summary.geom_kind.is_none() { self.summary.geom_kind = Some(GeomKind::of(geometry)); } self.summary.bounds = crate::pyramid::fold_bounds(self.summary.bounds, geometry); self.summary.count += 1; Ok(()) } /// [`push`](Self::push) for a geometry encoded off-thread: the same record /// layout with the geometry bytes supplied instead of encoded here. /// /// The materialise drains resolve + encode + region-test each batch on the /// pool and append the records in order here, so the serial thread does no /// vertex walk. Byte-identical to `push`: `geom_bytes` must be what /// [`encode_geometry`](crate::spill::encode_geometry) produced for the same /// geometry, `kind` its [`GeomKind`], `bounds` its /// [`bounds`](crate::geom::bounds) — all pure functions, so computing them /// on the pool changes no byte. Order, chunk index, sealing and the bounds /// fold are untouched: they happen here, serially, exactly as in `push`. pub fn push_preencoded( &mut self, kind: GeomKind, geom_bytes: &[u8], bounds: Option, props: &[(String, Value)], ) -> Result<()> { let mut rec = std::mem::take(&mut self.rec); let built = encode_normalized_record(kind, geom_bytes, props, &mut rec); let pushed = built.and_then(|()| self.push_record(kind, &rec, bounds)); self.rec = rec; pushed } /// Append one record [`encode_normalized_record`] already built (on the pool): the serial half of /// [`push_preencoded`](Self::push_preencoded), byte-for-byte. `kind` and `bounds` are the /// record's own, as `push_preencoded` takes them. pub fn push_record( &mut self, kind: GeomKind, rec: &[u8], bounds: Option, ) -> Result<()> { self.pending.extend_from_slice(rec); self.pending_count += 1; // The chunk index entry for this frame is recorded when the frame is staged // (`drain_frames`), which is when its offset is known. if self.pending_count >= NORM_CHUNK_FEATURES { self.seal_frame()?; } if self.summary.geom_kind.is_none() { self.summary.geom_kind = Some(kind); } self.summary.bounds = match (self.summary.bounds, bounds) { (None, b) => b, (a, None) => a, (Some(a), Some(b)) => Some(crate::geom::Rect { min_x: a.min_x.min(b.min_x), min_y: a.min_y.min(b.min_y), max_x: a.max_x.max(b.max_x), max_y: a.max_y.max(b.max_y), }), }; self.summary.count += 1; Ok(()) } /// Compress the buffered chunk into one frame and stage it. /// /// Level 1, not 6: the write happens once (stage A, serial sink) while the reads happen /// fifteen times (parallel prefetch lanes), which is what argued for 6 — ratio over deflate /// speed, with level-independent inflate. Measured on California, that argument was wrong: /// level 6 spends ~27 s of a 61 s `materialise-ways` serial drain in DEFLATE while level 1 /// spends ~0 s for ~5% more scratch bytes (scratch, deleted on success; the budget gate /// sizes commit with headroom). The drain is serial and order-critical, so its wall is /// Amdahl time; the spill size is not. /// /// The level is a constant, not a knob: the frame header carries no level mark because /// inflate is level-independent, so the choice changes only scratch bytes, never the /// archive — and an operator knob here would trade build minutes for scratch bytes with /// no content effect either way. Re-measure (drain wall + spill GB) before touching it. fn seal_frame(&mut self) -> Result<()> { if self.pending.is_empty() { return Ok(()); } // Queued raw, compressed later in a batch: see `drain_frames`. `take` leaves `pending` // empty for the next chunk; the frame owns its bytes until it is staged. self.queued.push(FrameSrc::Owned(std::mem::take(&mut self.pending))); self.pending_count = 0; if self.queued.len() >= SEAL_BATCH { self.drain_frames()?; } Ok(()) } /// Compress every queued frame (on the pool when there is more than one) and stage them in /// queue order, recording each frame's chunk-index offset as it lands. /// /// Byte-identical to sealing frames one at a time: DEFLATE is a pure function of a frame's /// bytes and the level, the frames are staged in the order they were sealed, and each index /// entry is the offset the frame is written at -- exactly the `at` the per-frame path /// recorded at the frame's first record, since every frame starts on a /// `NORM_CHUNK_FEATURES` boundary and the frames before it were staged first. /// /// The batch also turns the writes into one large sequential write per batch (megabytes) /// rather than one per 64-feature frame. fn drain_frames(&mut self) -> Result<()> { if self.queued.is_empty() { return Ok(()); } let frames = std::mem::take(&mut self.queued); let compressed: Vec> = if frames.len() == 1 { vec![miniz_oxide::deflate::compress_to_vec(frames[0].bytes(), SPILL_DEFLATE_LEVEL)] } else { use rayon::prelude::*; crate::par::install(|| { frames .par_iter() .map(|raw| miniz_oxide::deflate::compress_to_vec(raw.bytes(), SPILL_DEFLATE_LEVEL)) .collect() }) }; drop(frames); // Each frame's offset is known here, from the sizes alone (a prefix sum from `at`), so // the chunk index is complete before a byte is written; the bytes themselves go to the // background writer, which stages them in this same order. The serial pusher no longer // waits on the copy into the buffer or on the write. for frame in &compressed { u32::try_from(frame.len()) .map_err(|_| Error("a spill frame is larger than 4 GiB".to_string()))?; self.summary.chunks.push(self.at); self.at += 4 + frame.len() as u64; } if self.bg.is_none() { let out = self.out.take().expect("the sink is here until the writer starts"); self.bg = Some(BgWriter::start(out, self.path.clone())); } self.bg.as_ref().expect("started above").send(compressed) } /// Stop the background writer, if one ran, and take the sink back: every frame staged. fn join_bg(&mut self) -> Result<()> { if let Some(bg) = self.bg.take() { self.out = Some(bg.finish()?); } Ok(()) } /// Append a run of records the caller encoded off-thread, all at once: what calling /// [`push_record`](Self::push_record) for each would do, without the per-record work on the /// serial thread. `ends[i]` is the end offset of record `i` in `bytes`; `first_kind` the /// first record's kind; `bounds` the fold of every record's bounds. /// /// Byte-identical to the per-record path: frames close on the same 64-record boundaries /// (records topping up the open frame are copied into it, whole frames inside the run are /// compressed straight out of `bytes`, the tail is copied into the next open frame), the chunk /// index entries are recorded the same way, and the summary folds are associative. pub fn push_run( &mut self, bytes: Vec, ends: &[usize], first_kind: Option, bounds: Option, ) -> Result<()> { let n = ends.len(); if n == 0 { return Ok(()); } let bytes = std::sync::Arc::new(bytes); let start_of = |i: usize| if i == 0 { 0 } else { ends[i - 1] }; let per = NORM_CHUNK_FEATURES as usize; let mut i = 0usize; if self.pending_count > 0 { let k = (per - self.pending_count as usize).min(n); self.pending.extend_from_slice(&bytes[..start_of(k)]); self.pending_count += k as u64; i = k; if self.pending_count >= NORM_CHUNK_FEATURES { self.seal_frame()?; } } while n - i >= per { self.queued.push(FrameSrc::Shared(std::sync::Arc::clone(&bytes), start_of(i)..start_of(i + per))); i += per; if self.queued.len() >= SEAL_BATCH { self.drain_frames()?; } } if i < n { self.pending.extend_from_slice(&bytes[start_of(i)..]); self.pending_count += (n - i) as u64; } if self.summary.geom_kind.is_none() { self.summary.geom_kind = first_kind; } self.summary.bounds = match (self.summary.bounds, bounds) { (None, b) => b, (a, None) => a, (Some(a), Some(b)) => Some(crate::geom::Rect { min_x: a.min_x.min(b.min_x), min_y: a.min_y.min(b.min_y), max_x: a.max_x.max(b.max_x), max_y: a.max_y.max(b.max_y), }), }; self.summary.count += n as u64; Ok(()) } /// Compressed bytes staged so far (frames plus file header). For spill-size /// measurement: the budget calibrator (`SPILL_BYTES_PER_FEATURE`) is tuned /// per deflate level, so level experiments report this alongside the wall. /// Lags by the frames still queued for batch compression until `finish`. pub fn staged_bytes(&self) -> u64 { self.at } /// Flush, and hand back what the pass learned. pub fn finish(mut self) -> Result { // The last chunk is usually partial and still needs its frame -- without this its // records would be buffered and never staged. self.seal_frame()?; self.drain_frames()?; self.join_bg()?; self.flush_out()?; // Close the last chunk. Without this the final partial chunk has no end, and // `chunk_count` would also over-report by one. if !self.summary.chunks.is_empty() { self.summary.chunks.push(self.at); } Ok(self.summary) } /// Flush, and hand back what the pass learned plus whatever backend holds the bytes. /// /// Unifies [`finish`](Self::finish) and [`finish_anon`](Self::finish_anon): callers that pick /// the backend by budget ([`osm_ingest::mem::SpillPlan`]) seal without knowing which one they /// chose. A file backend yields no store -- its bytes live at the path it was created with, /// and readers open that path. pub fn finish_either(mut self) -> Result<(NormalizedSummary, Option)> { self.seal_frame()?; self.drain_frames()?; self.join_bg()?; self.flush_out()?; if !self.summary.chunks.is_empty() { self.summary.chunks.push(self.at); } match self.out.take().expect("joined above") { WriterSink::Anon(a) => Ok((self.summary, Some(a))), WriterSink::File(_) => Ok((self.summary, None)), } } /// Anonymous twin of [`finish`](Self::finish): flush, hand back the summary /// AND the staged store for [`NormalizedChunks::open_anon`]. Errors when /// this writer is file-backed (a programming bug, not a runtime one). pub fn finish_anon(mut self) -> Result<(NormalizedSummary, crate::anon::AnonStore)> { self.seal_frame()?; self.drain_frames()?; self.join_bg()?; self.flush_out()?; if !self.summary.chunks.is_empty() { self.summary.chunks.push(self.at); } match self.out.take().expect("joined above") { WriterSink::Anon(a) => Ok((self.summary, a)), WriterSink::File(_) => err("finish_anon on a file-backed writer".to_string()), } } fn flush_out(&mut self) -> Result<()> { match self.out.as_mut().expect("joined before flushing") { WriterSink::File(f) => f .flush() .map_err(|e| Error(format!("flushing {}: {e}", self.path.display())))?, WriterSink::Anon(a) => a.finish(), } Ok(()) } }