maps: hand stage-A records to the feature spill in runs (#perf)
- Commit
d86b96441c3affe2d197f6ca1b1e3d55062a18b0- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-11 05:36 UTC (25 days ago)
- Parents
82ee677
What: tile_build's NormalizedWriter gains push_run() (a buffer of records encoded off-thread, with their end offsets) and writes its compressed frames from a background thread; mamaps_build builds a RecordRun per ways block (materialise-ways) and per 1024 graph nodes (junction layer) on the pool, and the serial drain appends one run per call (Sink::push_run). MAPS_FORCE_FILE_SPILL=1 is a test knob that takes the file-staged spill path on any input (the planet's path) for profiling. Why: materialise-ways was 202 s of the Nov 10 planet build, all of it the ordered drain (profile: wall 195 s, drain 194.8 s): ~1.1 B records each pushed one at a time -- copied into the open frame, folded into the summary, chunk-min bookkeeping -- then every frame batch written inline. How, and why it is byte-identical: - Frame offsets are a prefix sum of compressed sizes, so the chunk index is complete before any byte is written; the bytes go to a bounded background writer in the same order. - push_run tops up the open frame, compresses whole 64-record frames straight out of the run's buffer (no copy), and carries the tail into the next frame: the same frames on the same 64-record boundaries as per-record pushes. - Sink::push_run closes chunk minimums on the same boundaries; the bbox and summary folds are min/max. - Errors keep spill order: a block's first failure ends its run and surfaces when the in-order drain reaches it. Test pushing_runs_writes_what_pushing_records_writes compares file bytes and summaries (chunk index included) for runs of 1..262147 records, both backends.
Diff
scripts/maps/mamaps_build/src/extract.rs
diff --git a/scripts/maps/mamaps_build/src/extract.rs b/scripts/maps/mamaps_build/src/extract.rsindex 772d029297..fdac5ab755 100644--- a/scripts/maps/mamaps_build/src/extract.rs+++ b/scripts/maps/mamaps_build/src/extract.rs@@ -68,7 +68,7 @@ use rayon::prelude::*; use crate::schema::{self, Class, Layers}; use crate::store::{- PreRecord, Sink, Store, WayBlock, WayBlockLoc, WayBlocks, WayCounts, WayReader, WaySink,+ PreRecord, RecordRun, Sink, Store, WayBlock, WayBlockLoc, WayBlocks, WayCounts, WayReader, WaySink, WAY_BLOCK_WAYS, }; use tilecodec::mamaps::body::{BuildingAttrs, Carriageway};
scripts/maps/mamaps_build/src/extract_part1.rs
diff --git a/scripts/maps/mamaps_build/src/extract_part1.rs b/scripts/maps/mamaps_build/src/extract_part1.rsindex 28f7746698..ad7bddce77 100644--- a/scripts/maps/mamaps_build/src/extract_part1.rs+++ b/scripts/maps/mamaps_build/src/extract_part1.rs@@ -228,8 +228,9 @@ fn plan_ways_spill( let input_bytes = std::fs::metadata(input) .map(|m| m.len()) .unwrap_or(0);- // No gate on small inputs: the historical anon path, no behaviour change.- if input_bytes < (8u64 << 30) {+ // No gate on small inputs: the historical anon path, no behaviour change (unless the+ // `MAPS_FORCE_FILE_SPILL` test knob asks for the planet's file path).+ if input_bytes < (8u64 << 30) && std::env::var_os("MAPS_FORCE_FILE_SPILL").is_none() { return Ok(osm_ingest::mem::SpillPlan::Anon); } let estimate = (input_bytes / 32).max(1 << 30);
scripts/maps/mamaps_build/src/extract_part2.rs
diff --git a/scripts/maps/mamaps_build/src/extract_part2.rs b/scripts/maps/mamaps_build/src/extract_part2.rsindex 5b619d4e37..a93e55a7f0 100644--- a/scripts/maps/mamaps_build/src/extract_part2.rs+++ b/scripts/maps/mamaps_build/src/extract_part2.rs@@ -584,9 +584,13 @@ fn materialise_ways( let (mut failed, mut kept) = (0u64, 0u64); for_each_way_block( &blocks,- |mut reader| -> Result<Vec<Result<BuiltWay>>> {+ |mut reader| -> Result<(RecordRun, u64)> { let mut refs: Vec<i64> = Vec::new();- let mut out = Vec::new();+ // The block's kept records go straight into one run (`Sink::push_run`); the first+ // failure in the block ends it with that error, which the in-order drain reports as+ // the first in spill order -- as the record-by-record drain did.+ let mut run = RecordRun::default();+ let mut block_failed = 0u64; while let Some((id, class, name, lane_count, turn_fwd, turn_bwd, carriageway, building)) = reader.next(&mut refs)? {@@ -625,7 +629,7 @@ fn materialise_ways( } else { way_geometry(&line, class.area) };- out.push(build_way(+ match build_way( &class, geometry, region,@@ -636,24 +640,20 @@ fn materialise_ways( &turn_bwd, carriageway, building,- ));+ )? {+ BuiltWay::Failed => block_failed += 1,+ BuiltWay::Dropped => {}+ BuiltWay::Kept(record) => run.add(record),+ } }- Ok(out)+ Ok((run, block_failed)) }, |ways, built| { let t = std::time::Instant::now();- for built in built {- // `?` in spill order: the first encode failure in feature order,- // exactly as inline encoding would report it.- match built? {- BuiltWay::Failed => failed += 1,- BuiltWay::Dropped => {}- BuiltWay::Kept(record) => {- sink.push_pre(&record)?;- kept += 1;- }- }- }+ let (run, block_failed) = built;+ failed += block_failed;+ kept += run.len() as u64;+ sink.push_run(run)?; bar.tick_n(ways as usize, "way(s)"); drain_wall += t.elapsed(); Ok(())
scripts/maps/mamaps_build/src/schema/junction_part2.rs
diff --git a/scripts/maps/mamaps_build/src/schema/junction_part2.rs b/scripts/maps/mamaps_build/src/schema/junction_part2.rsindex e7259cc8c3..c4819d16b5 100644--- a/scripts/maps/mamaps_build/src/schema/junction_part2.rs+++ b/scripts/maps/mamaps_build/src/schema/junction_part2.rs@@ -248,24 +248,37 @@ pub fn stream_junctions(dir: &Path, conventions: &Conventions, sink: &mut Sink) "node(s)", true, );+ // One task per run of `JUNCTION_NODES` consecutive nodes, each producing one `RecordRun`, so+ // the serial drain appends a run at a time rather than a record at a time (~177 M connectors+ // on the planet).+ const JUNCTION_NODES: usize = 1024;+ let node_count = graph.node_count as usize;+ let units = node_count.div_ceil(JUNCTION_NODES); crate::extract::pipeline_ordered(- graph.node_count as usize,- JUNCTION_GROUP,- |n| -> Result<Vec<crate::store::PreRecord>> {- junctions_for_node(n as u64, &graph, lanes.as_ref(), &incoming, conventions)- .into_iter()- .map(|points| {+ units,+ JUNCTION_GROUP / JUNCTION_NODES,+ |u| -> Result<crate::store::RecordRun> {+ let mut run = crate::store::RecordRun::default();+ let lo = u * JUNCTION_NODES;+ for n in lo..(lo + JUNCTION_NODES).min(node_count) {+ for points in junctions_for_node(n as u64, &graph, lanes.as_ref(), &incoming, conventions) { let encoded = crate::store::EncodedGeom::live(&Geometry::Lines(vec![points]))?;- crate::store::PreRecord::named(&class, &encoded, None, tilecodec::mamaps::body::ID_NONE)- })- .collect()- },- |_, records| {- for record in records? {- sink.push_pre(&record)?;- emitted += 1;+ run.add(crate::store::PreRecord::named(+ &class,+ &encoded,+ None,+ tilecodec::mamaps::body::ID_NONE,+ )?);+ } }- bar.tick("node(s)");+ Ok(run)+ },+ |u, run| {+ let run = run?;+ emitted += run.len() as u64;+ sink.push_run(run)?;+ let lo = u * JUNCTION_NODES;+ bar.tick_n((lo + JUNCTION_NODES).min(node_count) - lo, "node(s)"); Ok(()) }, )?;
scripts/maps/mamaps_build/src/store_part6.rs
diff --git a/scripts/maps/mamaps_build/src/store_part6.rs b/scripts/maps/mamaps_build/src/store_part6.rsindex 36d3c56c1d..3e3e3e871d 100644--- a/scripts/maps/mamaps_build/src/store_part6.rs+++ b/scripts/maps/mamaps_build/src/store_part6.rs@@ -160,7 +160,87 @@ impl PreRecord { } } +/// Many pool-built records in one buffer, for [`Sink::push_run`]: what the materialise drains+/// used to push one `PreRecord` at a time. Built on the pool (one per ways block, per junction+/// group), so the serial thread does one call per run instead of per-record bookkeeping -- on the+/// planet ~1.1 B records, which was the floor under `materialise-ways` (195 s, all of it drain).+#[derive(Default)]+pub struct RecordRun {+ bytes: Vec<u8>,+ ends: Vec<usize>,+ min_zoom: Vec<u8>,+ first_kind: Option<GeomKind>,+ bounds: Option<Rect>,+ ebbx: Option<(i32, i32, i32, i32)>,+}++impl RecordRun {+ /// Append one record, folding its facts exactly as `Sink::push_pre` would one at a time.+ pub fn add(&mut self, record: PreRecord) {+ if self.bytes.is_empty() && self.ends.is_empty() {+ self.bytes = record.rec;+ } else {+ self.bytes.extend_from_slice(&record.rec);+ }+ self.ends.push(self.bytes.len());+ self.min_zoom.push(record.min_zoom);+ if self.first_kind.is_none() {+ self.first_kind = Some(record.kind);+ }+ self.bounds = match (self.bounds, record.bounds) {+ (None, b) => b,+ (a, None) => a,+ (Some(a), Some(b)) => Some(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),+ }),+ };+ if let Some((x0, y0, x1, y1)) = record.ebbx {+ self.ebbx = Some(match self.ebbx {+ None => (x0, y0, x1, y1),+ Some(e) => (e.0.min(x0), e.1.min(y0), e.2.max(x1), e.3.max(y1)),+ });+ }+ }++ pub fn len(&self) -> usize {+ self.ends.len()+ }+}+ impl Sink {+ /// Append a whole [`RecordRun`]: the same writer bytes, chunk minimums, count and bounding box+ /// as `push_pre` on each of its records in order. The chunk minimums close on the same+ /// 64-record boundaries; the box and the summary folds are min/max, so folding a run first+ /// changes nothing.+ pub fn push_run(&mut self, run: RecordRun) -> Result<()> {+ let RecordRun { bytes, ends, min_zoom, first_kind, bounds, ebbx } = run;+ if ends.is_empty() {+ return Ok(());+ }+ self.writer+ .push_run(bytes, &ends, first_kind, bounds)+ .map_err(|e| osm_ingest::proto::Error(e.to_string()))?;+ let per = NORM_CHUNK_FEATURES as usize;+ let mut rest = &min_zoom[..];+ while !rest.is_empty() {+ let room = per - (self.count % NORM_CHUNK_FEATURES) as usize;+ let take = room.min(rest.len());+ let m = rest[..take].iter().copied().min().expect("non-empty");+ self.filling = self.filling.min(m);+ self.count += take as u64;+ if self.count % NORM_CHUNK_FEATURES == 0 {+ self.chunk_mins.push(self.filling);+ self.filling = u8::MAX;+ }+ rest = &rest[take..];+ }+ self.grow_bounds(ebbx);+ Ok(())+ }+ /// Append a pool-built record: [`write_record`](Self::write_record) with the encoding already /// done. Same writer call, same chunk-min, count and bbox bookkeeping, in the same order. pub fn push_pre(&mut self, record: &PreRecord) -> Result<()> {
scripts/maps/osm_ingest/src/mem.rs
diff --git a/scripts/maps/osm_ingest/src/mem.rs b/scripts/maps/osm_ingest/src/mem.rsindex a2cc289ad1..0bc331bd95 100644--- a/scripts/maps/osm_ingest/src/mem.rs+++ b/scripts/maps/osm_ingest/src/mem.rs@@ -322,6 +322,11 @@ impl SpillPlan { const ANON_SHARE_DEN: u64 = 2; let need_anon = budget.anon_commit_bytes(); let need_disk = budget.disk_bytes();+ // Test knob: take the file backend whatever the budget says, so a regional extract runs+ // the planet's code path (file-staged spills) for profiling. Same records either way.+ if std::env::var_os("MAPS_FORCE_FILE_SPILL").is_some() {+ return Ok(SpillPlan::File);+ } match (commit_avail_bytes(), commit_limit_bytes(), disk_free_bytes(spill_path)) { (Some(avail), Some(limit), disk) => {
scripts/maps/tile_build/src/spill_part2.rs
diff --git a/scripts/maps/tile_build/src/spill_part2.rs b/scripts/maps/tile_build/src/spill_part2.rsindex 91df7c98e1..9704ceb90f 100644--- a/scripts/maps/tile_build/src/spill_part2.rs+++ b/scripts/maps/tile_build/src/spill_part2.rs@@ -188,8 +188,90 @@ const NORM_FILE_HEADER_BYTES: usize = 8; /// kilobytes; a gigabyte frame is corruption, not a dense chunk. const MAX_FRAME_BYTES: u64 = 1 << 30; +/// A sealed frame's raw records: its own buffer, or a whole-frame slice of a caller's run+/// ([`NormalizedWriter::push_run`]) compressed in place without a copy.+enum FrameSrc {+ Owned(Vec<u8>),+ Shared(std::sync::Arc<Vec<u8>>, std::ops::Range<usize>),+}++impl FrameSrc {+ fn bytes(&self) -> &[u8] {+ match self {+ FrameSrc::Owned(v) => v,+ FrameSrc::Shared(v, r) => &v[r.clone()],+ }+ }+}++/// A thread staging compressed frames into the sink, in the order they are sent: each frame as+/// its `u32` length then its bytes, exactly what the inline path wrote. Bounded, so at most a few+/// batches wait.+struct BgWriter {+ tx: Option<std::sync::mpsc::SyncSender<Vec<Vec<u8>>>>,+ handle: Option<std::thread::JoinHandle<Result<WriterSink>>>,+}++impl BgWriter {+ fn start(mut out: WriterSink, path: PathBuf) -> BgWriter {+ let (tx, rx) = std::sync::mpsc::sync_channel::<Vec<Vec<u8>>>(4);+ let handle = std::thread::Builder::new()+ .name("spill-writer".to_string())+ .spawn(move || -> Result<WriterSink> {+ for batch in rx {+ for frame in batch {+ let len = (frame.len() as u32).to_le_bytes();+ match &mut out {+ WriterSink::File(f) => f+ .write_all(&len)+ .and_then(|()| f.write_all(&frame))+ .map_err(|e| Error(format!("writing {}: {e}", path.display())))?,+ WriterSink::Anon(a) => {+ a.push(&len)?;+ a.push(&frame)?;+ }+ }+ }+ }+ Ok(out)+ })+ .expect("start the spill writer thread");+ BgWriter { tx: Some(tx), handle: Some(handle) }+ }++ /// Queue one batch. A writer that already failed reports its error here, at the next send,+ /// rather than at `finish`.+ fn send(&self, batch: Vec<Vec<u8>>) -> Result<()> {+ if self.tx.as_ref().expect("open until finish").send(batch).is_err() {+ return err("the spill writer stopped early; its error follows at finish".to_string());+ }+ Ok(())+ }++ fn finish(mut self) -> Result<WriterSink> {+ drop(self.tx.take());+ self.handle+ .take()+ .expect("joined once")+ .join()+ .map_err(|_| Error("the spill writer thread panicked".to_string()))?+ }+}++impl Drop for BgWriter {+ fn drop(&mut self) {+ drop(self.tx.take());+ if let Some(h) = self.handle.take() {+ let _ = h.join();+ }+ }+}+ pub struct NormalizedWriter {- out: WriterSink,+ /// `None` while a background writer owns it (see [`BgWriter`]); back by `finish`.+ out: Option<WriterSink>,+ /// The thread staging compressed frames, started at the first batch.+ bg: Option<BgWriter>, path: PathBuf, summary: NormalizedSummary, rec: Vec<u8>,@@ -200,13 +282,11 @@ pub struct NormalizedWriter { pending: Vec<u8>, /// Records in `pending`. Counted rather than derived because records are variable-length. pending_count: u64,- /// Compressed scratch, reused across frames so a chunk seal allocates nothing.- sealed: Vec<u8>, /// 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<Vec<u8>>,+ queued: Vec<FrameSrc>, /// Bytes written so far, which is the next frame's offset. Tracks *compressed* bytes: the /// chunk index addresses frames, not records. at: u64,@@ -232,13 +312,13 @@ impl NormalizedWriter { let f = File::create(&path) .map_err(|e| Error(format!("cannot create {}: {e}", path.display())))?; let mut w = NormalizedWriter {- out: WriterSink::File(BufWriter::with_capacity(1 << 20, f)),+ 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,- sealed: Vec::new(), 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.@@ -254,13 +334,13 @@ impl NormalizedWriter { /// [`NormalizedChunks::open_anon`] on the way back. pub fn create_anon(path: impl Into<PathBuf>) -> Result<NormalizedWriter> { let mut w = NormalizedWriter {- out: WriterSink::Anon(crate::anon::AnonStore::new()),+ 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,- sealed: Vec::new(), queued: Vec::new(), at: NORM_FILE_HEADER_BYTES as u64, };@@ -275,7 +355,7 @@ impl NormalizedWriter { let mut head = [0u8; NORM_FILE_HEADER_BYTES]; head[0..4].copy_from_slice(NORM_MAGIC); head[4] = NORM_VERSION;- match &mut self.out {+ 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())))?,@@ -403,7 +483,7 @@ impl NormalizedWriter { } // 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(std::mem::take(&mut self.pending));+ self.queued.push(FrameSrc::Owned(std::mem::take(&mut self.pending))); self.pending_count = 0; if self.queued.len() >= SEAL_BATCH { self.drain_frames()?;@@ -428,37 +508,100 @@ impl NormalizedWriter { } let frames = std::mem::take(&mut self.queued); let compressed: Vec<Vec<u8>> = if frames.len() == 1 {- vec![miniz_oxide::deflate::compress_to_vec(&frames[0], SPILL_DEFLATE_LEVEL)]+ 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, SPILL_DEFLATE_LEVEL))+ .map(|raw| miniz_oxide::deflate::compress_to_vec(raw.bytes(), SPILL_DEFLATE_LEVEL)) .collect() }) }; drop(frames);- let total: usize = compressed.iter().map(|c| 4 + c.len()).sum();- self.sealed.clear();- self.sealed.reserve(total);+ // 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 {- let frame_len = u32::try_from(frame.len())+ 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.sealed.len() as u64);- self.sealed.extend_from_slice(&frame_len.to_le_bytes());- self.sealed.extend_from_slice(frame);+ self.summary.chunks.push(self.at);+ self.at += 4 + frame.len() as u64; }- match &mut self.out {- WriterSink::File(f) => f- .write_all(&self.sealed)- .map_err(|e| Error(format!("writing {}: {e}", self.path.display())))?,- WriterSink::Anon(a) => {- a.push(&self.sealed)?;+ 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<u8>,+ ends: &[usize],+ first_kind: Option<GeomKind>,+ bounds: Option<crate::geom::Rect>,+ ) -> 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()?; } }- self.at += self.sealed.len() as u64;- self.sealed.clear();+ 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(()) } @@ -476,6 +619,7 @@ impl NormalizedWriter { // 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.@@ -494,11 +638,12 @@ impl NormalizedWriter { pub fn finish_either(mut self) -> Result<(NormalizedSummary, Option<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 {+ match self.out.take().expect("joined above") { WriterSink::Anon(a) => Ok((self.summary, Some(a))), WriterSink::File(_) => Ok((self.summary, None)), }@@ -510,18 +655,19 @@ impl NormalizedWriter { 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 {+ 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 &mut self.out {+ match self.out.as_mut().expect("joined before flushing") { WriterSink::File(f) => f .flush() .map_err(|e| Error(format!("flushing {}: {e}", self.path.display())))?,
scripts/maps/tile_build/src/spill_part4.rs
diff --git a/scripts/maps/tile_build/src/spill_part4.rs b/scripts/maps/tile_build/src/spill_part4.rsindex 781aef2a80..31f22e95c2 100644--- a/scripts/maps/tile_build/src/spill_part4.rs+++ b/scripts/maps/tile_build/src/spill_part4.rs@@ -389,3 +389,69 @@ assert!(!path.exists(), "the guard must remove it"); let _ = std::fs::remove_dir_all(&dir); }++ /// Runs pushed whole ([`NormalizedWriter::push_run`]) -- of every length, starting mid-frame+ /// and on frame boundaries, mixed with single records and with enough frames to cross a+ /// background batch -- write the same file and the same summary as pushing record by record.+ #[test]+ fn pushing_runs_writes_what_pushing_records_writes() {+ let dir = tmp("runs");+ let mut records: Vec<(GeomKind, Vec<u8>, Option<crate::geom::Rect>)> = Vec::new();+ for i in 0..(NORM_CHUNK_FEATURES as usize * 4200 + 37) {+ let g = Geometry::Lines(vec![vec![(i as f64 * 1e-4, 1.0), (i as f64 * 1e-4 + 0.5, (i % 7) as f64)]]);+ let mut geom = Vec::new();+ encode_geometry(&g, &mut geom).unwrap();+ let mut rec = Vec::new();+ let props = vec![("c".to_string(), Value::Uint(i as u64))];+ encode_normalized_record(GeomKind::of(&g), &geom, &props, &mut rec).unwrap();+ records.push((GeomKind::of(&g), rec, crate::geom::bounds(&g)));+ }+ for anon in [false, true] {+ let (a, b) = (dir.join(format!("one{anon}.bin")), dir.join(format!("run{anon}.bin")));+ let mk = |p: &std::path::Path| {+ if anon { NormalizedWriter::create_anon(p) } else { NormalizedWriter::create(p) }.unwrap()+ };+ let mut one = mk(&a);+ for (k, r, bd) in &records {+ one.push_record(*k, r, *bd).unwrap();+ }+ let mut run = mk(&b);+ let mut i = 0usize;+ let mut step = 1usize;+ while i < records.len() {+ let n = step.min(records.len() - i);+ let mut bytes = Vec::new();+ let mut ends = Vec::new();+ let mut bounds = None;+ for (_, r, bd) in &records[i..i + n] {+ bytes.extend_from_slice(r);+ ends.push(bytes.len());+ bounds = match (bounds, *bd) {+ (None, x) => x,+ (x, None) => x,+ (Some(p), Some(q)) => Some(crate::geom::Rect {+ min_x: f64::min(p.min_x, q.min_x),+ min_y: f64::min(p.min_y, q.min_y),+ max_x: f64::max(p.max_x, q.max_x),+ max_y: f64::max(p.max_y, q.max_y),+ }),+ };+ }+ run.push_run(bytes, &ends, Some(records[i].0), bounds).unwrap();+ i += n;+ step = [1, 63, 64, 65, 200, 4096 * 64 + 3][(step + i) % 6];+ }+ let (s1, st1) = one.finish_either().unwrap();+ let (s2, st2) = run.finish_either().unwrap();+ assert_eq!(s1, s2, "summaries (chunk index included) agree, anon={anon}");+ let bytes = |p: &std::path::Path, st: Option<crate::anon::AnonStore>| match st {+ Some(s) => {+ let mut v = vec![0u8; s.len() as usize];+ s.read_at(0, &mut v).unwrap();+ v+ }+ None => std::fs::read(p).unwrap(),+ };+ assert_eq!(bytes(&a, st1), bytes(&b, st2), "same bytes, anon={anon}");+ }+ }