tile_build: read the normalized stream across the pool
- Commit
769083579ed64dc81675dd5d39914ccf81574cc7- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-26 21:13 UTC (3 months ago)
- Parents
ec40236
Diff
scripts/maps/tile_build/src/pmtiles.rs
diff --git a/scripts/maps/tile_build/src/pmtiles.rs b/scripts/maps/tile_build/src/pmtiles.rsindex c84d0dac39..579ee3512f 100644--- a/scripts/maps/tile_build/src/pmtiles.rs+++ b/scripts/maps/tile_build/src/pmtiles.rs@@ -690,7 +690,14 @@ impl ArchiveFile { /// between clones of a handle — so seek-then-read cannot be done concurrently on one /// archive, while this can. Both platforms expose a positional read; neither is /// guaranteed to return everything at once, hence the loop.-fn read_exact_at(file: &File, mut buf: &mut [u8], mut offset: u64) -> std::io::Result<()> {+///+/// `pub(crate)` because [`crate::spill::NormalizedChunks`] needs the same thing for+/// the same reason: many threads pulling disjoint ranges out of one file.+pub(crate) fn read_exact_at(+ file: &File,+ mut buf: &mut [u8],+ mut offset: u64,+) -> std::io::Result<()> { while !buf.is_empty() { #[cfg(windows)] let n = std::os::windows::fs::FileExt::seek_read(file, buf, offset)?;
scripts/maps/tile_build/src/pyramid.rs
diff --git a/scripts/maps/tile_build/src/pyramid.rs b/scripts/maps/tile_build/src/pyramid.rsindex 0a4bc26367..837b39633a 100644--- a/scripts/maps/tile_build/src/pyramid.rs+++ b/scripts/maps/tile_build/src/pyramid.rs@@ -215,9 +215,15 @@ struct BucketedFeature { /// this across the pool — and the reason the buffers are passed in rather than /// declared here is the one the serial loop had, unchanged: allocating them per /// feature would cost three million allocations a zoom.+///+/// Takes the geometry and properties rather than a [`Feature`] so the chunked read path+/// can pass a [`crate::spill::NormalizedFeature`]'s fields straight in. The two types+/// hold the same two things, and converting would mean copying a geometry per feature+/// per zoom to gain nothing. #[allow(clippy::too_many_arguments)] fn bucket_feature(- f: &Feature,+ geometry: &Geometry,+ props: &[(String, Value)], seq: u64, z: u8, opts: &Options,@@ -229,7 +235,7 @@ fn bucket_feature( let t0 = std::time::Instant::now(); // Project once per feature per zoom, not once per tile: a coastline can cross // thousands of tiles and the projection is the expensive part.- let projected = geom::project_geometry(&f.geometry, z, opts.extent);+ let projected = geom::project_geometry(geometry, z, opts.extent); geom::tiles_touched(&projected, z, opts.extent, buffer, touched); let mut out = BucketedFeature { blob: Vec::new(),@@ -249,7 +255,7 @@ fn bucket_feature( seq, extent_of(&simplified), &simplified,- &f.props,+ props, rec, )?; let at = out.blob.len();@@ -659,6 +665,17 @@ pub trait FeatureSource { fn bounds(&self) -> Option<geom::Rect>; /// The FIRST feature's kind, the rule [`dominant_geom_type`] already applies. fn geom_kind(&self) -> Option<GeomKind>;++ /// A positionally-readable view of the same features, when there is one.+ ///+ /// `Some` lets the bucket pass read and decode the source across the pool rather+ /// than through this cursor; `None` keeps it sequential. Only the file-backed source+ /// has one: [`SliceSource`]'s features are already resident and there is nothing to+ /// read. It is also `None` for a file written before the index existed, or an empty+ /// one, so the sequential path stays the fallback rather than a special case.+ fn chunks(&self) -> Option<&spill::NormalizedChunks> {+ None+ } } /// A [`FeatureSource`] over features already in memory.@@ -714,6 +731,7 @@ impl FeatureSource for SliceSource<'_> { pub struct NormalizedSource { reader: spill::NormalizedReader, summary: spill::NormalizedSummary,+ chunks: Option<spill::NormalizedChunks>, } impl NormalizedSource {@@ -724,9 +742,21 @@ impl NormalizedSource { path: impl Into<std::path::PathBuf>, summary: spill::NormalizedSummary, ) -> Result<NormalizedSource> {+ let path = path.into();+ // A second handle on the same file, for the chunked reads. Separate because the+ // sequential reader owns a cursor and positional reads must not disturb it.+ let chunks = if summary.chunk_count() == 0 {+ None+ } else {+ Some(spill::NormalizedChunks::open(+ path.clone(),+ summary.chunks.clone(),+ )?)+ }; Ok(NormalizedSource { reader: spill::NormalizedReader::open(path)?, summary,+ chunks, }) } }@@ -754,6 +784,10 @@ impl FeatureSource for NormalizedSource { fn geom_kind(&self) -> Option<GeomKind> { self.summary.geom_kind }++ fn chunks(&self) -> Option<&spill::NormalizedChunks> {+ self.chunks.as_ref()+ } } /// Features bucketed in one zoom's first pass.@@ -762,6 +796,185 @@ const BUCKETED: &str = "feature(s) bucketed"; /// Spill records encoded in one zoom's second pass. const ENCODED: &str = "record(s) encoded"; +/// One zoom's bucket pass: project every feature, clip it into each tile it reaches, and+/// write a spill record per `(feature, tile)`.+///+/// Two read shapes, one output. Both derive `seq` from the feature's index in the source+/// rather than from arrival order, which is what makes them interchangeable:+/// `encode_buckets` sorts each bucket by the total key `(tile_id, extent, seq)`, so push+/// order never reaches the archive.+#[allow(clippy::too_many_arguments)]+fn bucket_pass(+ src: &mut impl FeatureSource,+ z: u8,+ opts: &Options,+ buffer: f64,+ tolerance: f64,+ set: &mut spill::BucketSet,+ bar: &mut Progress,+) -> Result<()> {+ if let Some(chunks) = src.chunks() {+ return bucket_chunked(chunks, z, opts, buffer, tolerance, set, bar);+ }+ bucket_serial(src, z, opts, buffer, tolerance, set, bar)+}++/// Read serially, project and clip across the pool, push serially.+///+/// The fallback shape, for a source that is only a cursor. Everything between the read+/// and the write -- projection, clipping, simplification, record encoding -- is+/// per-feature pure and is where the time goes, so that part threads; the read does not.+/// Live memory is one batch's records, which is what bounds the batch.+#[allow(clippy::too_many_arguments)]+fn bucket_serial(+ src: &mut impl FeatureSource,+ z: u8,+ opts: &Options,+ buffer: f64,+ tolerance: f64,+ set: &mut spill::BucketSet,+ bar: &mut Progress,+) -> Result<()> {+ let mut touched: Vec<(u64, u64)> = Vec::new();+ let mut rec = Vec::new();+ let mut seq = 0u64;+ let batch_len = par::batch_len();+ let mut batch: Vec<Feature> = Vec::with_capacity(batch_len);+ loop {+ batch.clear();+ while batch.len() < batch_len {+ match src.next()? {+ Some(f) => batch.push(f),+ None => break,+ }+ }+ if batch.is_empty() {+ break;+ }+ let first = seq;+ let encoded: Vec<Result<BucketedFeature>> = if batch.len() == 1 {+ // One feature is not worth a pool round trip, and this is the path the+ // single-threaded case and the tail of every stream take.+ vec![bucket_feature(+ &batch[0].geometry,+ &batch[0].props,+ first,+ z,+ opts,+ buffer,+ tolerance,+ &mut touched,+ &mut rec,+ )]+ } else {+ par::install(|| {+ batch+ .par_iter()+ .enumerate()+ .with_min_len(par::min_task_len(batch.len()))+ .map_init(+ || (Vec::new(), Vec::new()),+ |(touched, rec), (i, f)| {+ bucket_feature(+ &f.geometry,+ &f.props,+ first + i as u64,+ z,+ opts,+ buffer,+ tolerance,+ touched,+ rec,+ )+ },+ )+ .collect()+ })+ };+ for one in encoded {+ let one = one?;+ for &(id, at, len) in &one.spans {+ set.push(id, &one.blob[at..at + len])?;+ }+ bar.tick(BUCKETED);+ }+ seq += batch.len() as u64;+ }+ Ok(())+}++/// Read, decode, project and clip across the pool; push serially.+///+/// The production shape. The serial path's remaining bottleneck was `src.next()`: it+/// decodes a geometry and a property vector per feature, allocating both, and does so+/// once per zoom on whichever single thread owns the cursor while the pool waits. Here a+/// worker takes a whole chunk, reads its byte range positionally, and decodes it itself,+/// so the decode scales with the pool and the pass no longer has a serial middle.+///+/// Chunk `c` starts at feature `c * NORM_CHUNK_FEATURES` by construction of the index,+/// which is what lets this reproduce the sequential path's `seq` exactly rather than+/// approximately.+#[allow(clippy::too_many_arguments)]+fn bucket_chunked(+ chunks: &spill::NormalizedChunks,+ z: u8,+ opts: &Options,+ buffer: f64,+ tolerance: f64,+ set: &mut spill::BucketSet,+ bar: &mut Progress,+) -> Result<()> {+ // One chunk per task, and as many chunks per batch as the serial path holds+ // features, so peak live memory is unchanged: a batch's encoded records bound it+ // either way.+ let per_batch = (par::batch_len() / spill::NORM_CHUNK_FEATURES as usize).max(1);+ let total = chunks.chunk_count();+ let mut ids: Vec<usize> = Vec::with_capacity(per_batch);+ let mut at = 0usize;+ while at < total {+ let end = (at + per_batch).min(total);+ ids.clear();+ ids.extend(at..end);+ let encoded: Vec<Result<Vec<BucketedFeature>>> = par::install(|| {+ ids.par_iter()+ .with_min_len(par::min_task_len(ids.len()))+ .map_init(+ || (Vec::new(), Vec::new(), Vec::new(), Vec::new()),+ |(scratch, feats, touched, rec), &ci| {+ chunks.read_into(ci, scratch, feats)?;+ let first = ci as u64 * spill::NORM_CHUNK_FEATURES;+ let mut out = Vec::with_capacity(feats.len());+ for (j, f) in feats.iter().enumerate() {+ out.push(bucket_feature(+ &f.geometry,+ &f.props,+ first + j as u64,+ z,+ opts,+ buffer,+ tolerance,+ touched,+ rec,+ )?);+ }+ Ok(out)+ },+ )+ .collect()+ });+ for one in encoded {+ for f in one? {+ for &(id, o, len) in &f.spans {+ set.push(id, &f.blob[o..o + len])?;+ }+ bar.tick(BUCKETED);+ }+ }+ at = end;+ }+ Ok(())+}+ /// Build the archive straight to `out`, with peak memory set by the tile count. /// /// The same drop policy, the same encoder and the same [`ZoomStats`] as@@ -872,81 +1085,8 @@ pub fn build_archive_to( BUCKETED, opts.progress, );- let mut touched: Vec<(u64, u64)> = Vec::new();- let mut rec = Vec::new(); let phase = std::time::Instant::now();- let mut seq = 0u64;- // Read serially, project and clip across the pool, push serially.- //- // The source is a `&mut` cursor and the bucket writers are buffered files, so- // neither end threads; everything between them -- projection, clipping,- // simplification, record encoding -- is per-feature pure and is where the time- // goes. Live memory is one batch's records, which is what bounds the batch.- //- // Push order does not matter to the output: `encode_buckets` sorts each bucket- // by the total key `(tile_id, extent, seq)`, and `seq` is the feature's index in- // the source, not its arrival order. Pushing in batch order anyway costs nothing- // and keeps the spill files themselves reproducible.- let batch_len = par::batch_len();- let mut batch: Vec<Feature> = Vec::with_capacity(batch_len);- loop {- batch.clear();- while batch.len() < batch_len {- match src.next()? {- Some(f) => batch.push(f),- None => break,- }- }- if batch.is_empty() {- break;- }- let first = seq;- let encoded: Vec<Result<BucketedFeature>> = if batch.len() == 1 {- // One feature is not worth a pool round trip, and this is the path the- // single-threaded case and the tail of every stream take.- vec![bucket_feature(- &batch[0],- first,- z,- opts,- buffer,- tolerance,- &mut touched,- &mut rec,- )]- } else {- par::install(|| {- batch- .par_iter()- .enumerate()- .with_min_len(par::min_task_len(batch.len()))- .map_init(- || (Vec::new(), Vec::new()),- |(touched, rec), (i, f)| {- bucket_feature(- f,- first + i as u64,- z,- opts,- buffer,- tolerance,- touched,- rec,- )- },- )- .collect()- })- };- for one in encoded {- let one = one?;- for &(id, at, len) in &one.spans {- set.push(id, &one.blob[at..at + len])?;- }- bar.tick(BUCKETED);- }- seq += batch.len() as u64;- }+ bucket_pass(src, z, opts, buffer, tolerance, &mut set, &mut bar)?; bar.finish(BUCKETED); let bucketed_in = phase.elapsed(); set.seal()?;@@ -2333,6 +2473,98 @@ mod tests { assert!(e.to_string().contains("above 30"), "{e}"); } + /// The same normalized file forced through the sequential path, so a test can pin the+ /// chunked reader against it. Everything delegates; `chunks` is left at its `None`+ /// default, which is the whole point.+ struct SerialOnly(NormalizedSource);++ impl FeatureSource for SerialOnly {+ fn rewind(&mut self) -> Result<()> {+ self.0.rewind()+ }+ fn next(&mut self) -> Result<Option<Feature>> {+ self.0.next()+ }+ fn len(&self) -> u64 {+ self.0.len()+ }+ fn bounds(&self) -> Option<geom::Rect> {+ self.0.bounds()+ }+ fn geom_kind(&self) -> Option<GeomKind> {+ self.0.geom_kind()+ }+ }++ /// The chunked reader is the production read path, so it must produce exactly what the+ /// sequential one does, at every thread count.+ ///+ /// `tight_fixture` is 201 features against `NORM_CHUNK_FEATURES` of 64, so the index+ /// spans four chunks and ends mid-chunk — the shape that catches an off-by-one in the+ /// chunk-to-`seq` mapping. The tight budget matters more: it makes the drop policy+ /// run, so a perturbed `seq` changes which features SURVIVE rather than only which+ /// bucket they land in. Without it a wrong `seq` would still sort out and the test+ /// would pass while the mapping was broken.+ ///+ /// Checked by mutation: dropping the chunk base (`first = 0`, so `seq` collides+ /// across chunks) fails this. Adding a constant to it does NOT, and should not —+ /// `seq` is only ever a tie-break, so a uniform shift preserves every comparison.+ #[test]+ fn the_chunked_reader_matches_the_sequential_one() {+ let features = tight_fixture();+ let mut opts = Options::new("l", 11, 11);+ opts.max_tile_bytes = 400;+ let limits = StreamLimits::default();++ let held = Scratch::new("chunked_src");+ let norm = held.0.join("features.bin");+ let mut w = crate::spill::NormalizedWriter::create(&norm).unwrap();+ for f in &features {+ w.push(&f.geometry, &f.props).unwrap();+ }+ let summary = w.finish().unwrap();++ // The fixture has to span several chunks and end mid-chunk, or this degenerates+ // into the single-chunk case and asserts nothing about the mapping.+ assert!(+ summary.chunk_count() > 1,+ "fixture must span several chunks, got {}",+ summary.chunk_count()+ );+ assert_ne!(+ summary.count % crate::spill::NORM_CHUNK_FEATURES,+ 0,+ "fixture must end mid-chunk to exercise the partial tail"+ );++ let serial = {+ let scratch = Scratch::new("chunked_serial");+ let out = scratch.0.join("out.pmtiles");+ let mut src = SerialOnly(NormalizedSource::open(&norm, summary.clone()).unwrap());+ assert!(src.chunks().is_none(), "this must take the serial path");+ let report = build_archive_to(&out, &scratch.0, &opts, &mut src, &limits).unwrap();+ (std::fs::read(&out).unwrap(), report)+ };++ for n in [1, 2, 3, 32] {+ par::set_threads(n);+ let scratch = Scratch::new(&format!("chunked_{n}"));+ let out = scratch.0.join("out.pmtiles");+ let mut src = NormalizedSource::open(&norm, summary.clone()).unwrap();+ assert!(src.chunks().is_some(), "this must take the chunked path");+ let report = build_archive_to(&out, &scratch.0, &opts, &mut src, &limits).unwrap();+ assert_eq!(+ report, serial.1,+ "{n} threads: the chunked reader changed the report"+ );+ assert!(+ std::fs::read(&out).unwrap() == serial.0,+ "{n} threads: the chunked reader perturbed the archive"+ );+ }+ par::clear_threads();+ }+ /// The production source is a file, and it must yield exactly what the slice-backed /// one does -- otherwise the byte-identity tests above are testing a path nothing /// ships.
scripts/maps/tile_build/src/spill.rs
diff --git a/scripts/maps/tile_build/src/spill.rs b/scripts/maps/tile_build/src/spill.rsindex 9d8d122438..245d1b94eb 100644--- a/scripts/maps/tile_build/src/spill.rs+++ b/scripts/maps/tile_build/src/spill.rs@@ -17,7 +17,10 @@ //! //! * **The normalized file** ([`NormalizedWriter`]) is the geojsonseq parsed exactly //! once into a compact binary. Every zoom then re-reads that instead of re-parsing-//! JSON, which is the cheaper end of a trade that has to be made six times.+//! JSON, which is the cheaper end of a trade that has to be made six times. The same+//! pass records a fixed-stride offset index ([`NormalizedSummary::chunks`]), so those+//! re-reads can be spread across the pool via [`NormalizedChunks`] rather than pulled+//! through one cursor. //! * **The buckets** ([`BucketSet`]) hold one record per `(feature, tile)` pair for ONE //! zoom, partitioned by `tile_id` range. //!@@ -63,6 +66,22 @@ pub const REC_HEADER_BYTES: usize = 48; /// Bytes of fixed header before a normalized record's two variable payloads. pub const NORM_HEADER_BYTES: usize = 16; +/// Features per entry in the normalized file's chunk index.+///+/// The index is what lets the bucket pass read the normalized file across the pool+/// instead of through one cursor: a worker takes a chunk, reads its byte range+/// positionally, and decodes the records in it. Records are self-delimiting, so an+/// offset every `NORM_CHUNK_FEATURES` features is all that is needed — a per-feature+/// table would cost 64x the memory to save nothing.+///+/// 64 is a compromise between two hard constraints. Larger chunks mean fewer tasks+/// per batch, and the batch is bounded by memory (`par::batch_len()` features), so a+/// stride of 1024 would leave a 64-core box with four tasks per batch. Smaller chunks+/// mean more index entries and smaller reads. At 64 the batch is one chunk per thread+/// at memory parity with the serial path, and the index is 8 bytes per 64 features:+/// a 200M-feature Europe extract indexes in ~25 MB.+pub const NORM_CHUNK_FEATURES: u64 = 64;+ /// A record longer than this is corruption, not a large feature. The largest plausible /// single OSM geometry is a coastline relation at a few million vertices, which is two /// orders of magnitude below this.@@ -947,6 +966,20 @@ pub struct NormalizedSummary { /// show as wrong rendering rather than hide as a silently split layer. pub geom_kind: Option<GeomKind>, pub skipped: u64,+ /// Byte offset of every `NORM_CHUNK_FEATURES`-th record, plus a final sentinel+ /// holding the file's total length — so chunk `i` spans `chunks[i]..chunks[i + 1]`+ /// and there are `chunks.len() - 1` of them.+ ///+ /// Built by the same single pass that writes the records, because the writer is the+ /// only place that already knows each record's length. Empty for an empty file.+ pub chunks: Vec<u64>,+}++impl NormalizedSummary {+ /// How many chunks the file has, for [`NormalizedChunks::read_into`].+ pub fn chunk_count(&self) -> usize {+ self.chunks.len().saturating_sub(1)+ } } /// Writes the geojsonseq once into a compact binary every zoom can re-read.@@ -964,6 +997,8 @@ pub struct NormalizedWriter { path: PathBuf, summary: NormalizedSummary, rec: Vec<u8>,+ /// Bytes written so far, which is the next record's offset.+ at: u64, } impl NormalizedWriter {@@ -982,6 +1017,7 @@ impl NormalizedWriter { path, summary: NormalizedSummary::default(), rec: Vec::new(),+ at: 0, }) } @@ -1003,9 +1039,14 @@ impl NormalizedWriter { 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();+ // Index before writing, so the offset recorded is this record's own start.+ if self.summary.count.is_multiple_of(NORM_CHUNK_FEATURES) {+ self.summary.chunks.push(self.at);+ } self.out .write_all(&self.rec) .map_err(|e| Error(format!("writing {}: {e}", self.path.display())))?;+ self.at += self.rec.len() as u64; if self.summary.geom_kind.is_none() { self.summary.geom_kind = Some(GeomKind::of(geometry));@@ -1020,6 +1061,11 @@ impl NormalizedWriter { self.out .flush() .map_err(|e| Error(format!("flushing {}: {e}", self.path.display())))?;+ // 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) } }@@ -1031,6 +1077,40 @@ pub struct NormalizedFeature { pub props: Vec<(String, Value)>, } +/// Validate a normalized record's fixed header, returning its payload shape.+///+/// Shared by the sequential reader and the chunked one, so the two cannot diverge on+/// what they accept: a record one of them rejects must not be one the other decodes.+fn norm_header(head: &[u8; NORM_HEADER_BYTES]) -> Result<(usize, usize, GeomKind)> {+ if head[13..NORM_HEADER_BYTES].iter().any(|v| *v != 0) {+ return err("normalized record has a nonzero reserved tail");+ }+ let u32_at = |o: usize| u32::from_le_bytes(head[o..o + 4].try_into().expect("4 bytes"));+ let rec_len = u32_at(0) as u64;+ let geom_len = u32_at(4) as usize;+ let props_len = u32_at(8) as usize;+ let want = NORM_HEADER_BYTES as u64 + geom_len as u64 + props_len as u64;+ if rec_len != want {+ return err(format!(+ "normalized record claims {rec_len} byte(s) but its header adds up to {want}"+ ));+ }+ if want > MAX_RECORD_BYTES {+ return err(format!(+ "normalized record is {want} byte(s), which is corruption"+ ));+ }+ Ok((geom_len, props_len, GeomKind::from_tag(head[12])?))+}++/// Decode a validated record's payload, `geom_len` bytes of geometry then properties.+fn norm_payload(kind: GeomKind, geom_len: usize, payload: &[u8]) -> Result<NormalizedFeature> {+ Ok(NormalizedFeature {+ geometry: decode_geometry(kind, &payload[..geom_len])?,+ props: decode_props(&payload[geom_len..])?,+ })+}+ /// Sequential reader over the normalized file, rewindable because every zoom re-reads /// it from the front. pub struct NormalizedReader {@@ -1082,34 +1162,113 @@ impl NormalizedReader { self.path.display() )); }- if head[13..NORM_HEADER_BYTES].iter().any(|v| *v != 0) {- return err("normalized record has a nonzero reserved tail");- }- let u32_at = |o: usize| u32::from_le_bytes(head[o..o + 4].try_into().expect("4 bytes"));- let rec_len = u32_at(0) as u64;- let geom_len = u32_at(4) as usize;- let props_len = u32_at(8) as usize;- let want = NORM_HEADER_BYTES as u64 + geom_len as u64 + props_len as u64;- if rec_len != want {+ let (geom_len, props_len, kind) = norm_header(&head)?;+ self.buf.clear();+ self.buf.resize(geom_len + props_len, 0);+ self.src.read_exact(&mut self.buf).map_err(|e| {+ Error(format!(+ "reading {}'s record payload: {e}",+ self.path.display()+ ))+ })?;+ Ok(Some(norm_payload(kind, geom_len, &self.buf)?))+ }+}++/// Chunked reader over the normalized file, for reading it across a thread pool.+///+/// The sequential [`NormalizedReader`] is one cursor, so the decode of every feature —+/// which allocates a `Geometry` and a `Vec` of properties, six times over a z11..z16+/// build — happens on whichever single thread owns it, while the pool waits. This reads+/// a whole chunk's byte range positionally instead, so the decode happens on the worker+/// that will bucket those features.+///+/// Takes `&self` throughout: see [`crate::pmtiles::read_exact_at`]. One handle serves+/// every thread.+pub struct NormalizedChunks {+ file: File,+ path: PathBuf,+ /// Chunk boundaries, `chunk_count() + 1` of them. See [`NormalizedSummary::chunks`].+ chunks: Vec<u64>,+}++impl NormalizedChunks {+ /// `chunks` is [`NormalizedSummary::chunks`] for this file.+ pub fn open(path: impl Into<PathBuf>, chunks: Vec<u64>) -> Result<NormalizedChunks> {+ let path = path.into();+ let file = File::open(&path)+ .map_err(|e| Error(format!("cannot read {}: {e}", path.display())))?;+ Ok(NormalizedChunks { file, path, chunks })+ }++ pub fn chunk_count(&self) -> usize {+ self.chunks.len().saturating_sub(1)+ }++ /// Decode chunk `i` into `out`, which is cleared first.+ ///+ /// `scratch` is the caller's per-worker byte buffer, reused across chunks so a pass+ /// allocates once per thread rather than once per chunk.+ ///+ /// The first feature of chunk `i` is input feature `i * NORM_CHUNK_FEATURES`, by+ /// construction of the index — which is what lets the caller reproduce the exact+ /// `seq` the sequential path assigns.+ pub fn read_into(+ &self,+ i: usize,+ scratch: &mut Vec<u8>,+ out: &mut Vec<NormalizedFeature>,+ ) -> Result<()> {+ out.clear();+ let (Some(&start), Some(&end)) = (self.chunks.get(i), self.chunks.get(i + 1)) else { return err(format!(- "normalized record claims {rec_len} byte(s) but its header adds up to {want}"+ "normalized chunk {i} is past the {} in {}",+ self.chunk_count(),+ self.path.display() ));- }- if want > MAX_RECORD_BYTES {+ };+ if end < start { return err(format!(- "normalized record is {want} byte(s), which is corruption"+ "normalized chunk {i} of {} ends before it starts",+ self.path.display() )); }- let kind = GeomKind::from_tag(head[12])?;- self.buf.clear();- self.buf.resize(geom_len + props_len, 0);- self.src.read_exact(&mut self.buf).map_err(|e| {- Error(format!("reading {}'s record payload: {e}", self.path.display()))+ let len = (end - start) as usize;+ scratch.clear();+ scratch.resize(len, 0);+ crate::pmtiles::read_exact_at(&self.file, scratch, start).map_err(|e| {+ Error(format!(+ "reading normalized chunk {i} of {}: {e}",+ self.path.display()+ )) })?;- Ok(Some(NormalizedFeature {- geometry: decode_geometry(kind, &self.buf[..geom_len])?,- props: decode_props(&self.buf[geom_len..])?,- }))+ let mut at = 0usize;+ while at < len {+ if len - at < NORM_HEADER_BYTES {+ return err(format!(+ "normalized chunk {i} of {} ends {} byte(s) into a \+ {NORM_HEADER_BYTES}-byte record header",+ self.path.display(),+ len - at+ ));+ }+ let head: &[u8; NORM_HEADER_BYTES] = scratch[at..at + NORM_HEADER_BYTES]+ .try_into()+ .expect("a header's worth of bytes");+ let (geom_len, props_len, kind) = norm_header(head)?;+ let body = at + NORM_HEADER_BYTES;+ let rec_end = body + geom_len + props_len;+ if rec_end > len {+ return err(format!(+ "normalized chunk {i} of {} holds a record running {} byte(s) past its end",+ self.path.display(),+ rec_end - len+ ));+ }+ out.push(norm_payload(kind, geom_len, &scratch[body..rec_end])?);+ at = rec_end;+ }+ Ok(()) } } @@ -1573,6 +1732,130 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// The chunked reader must yield exactly the sequential reader's features in exactly+ /// its order, and its chunk boundaries must land on multiples of+ /// `NORM_CHUNK_FEATURES` — that alignment is what the bucket pass relies on to+ /// reconstruct `seq` without reading the whole file.+ #[test]+ fn the_chunked_reader_yields_what_the_sequential_one_does() {+ let dir = tmp("normchunks");+ let path = dir.join("features.bin");++ // Deliberately not a multiple of the stride, so the last chunk is partial, and+ // varied enough that a record-length mistake cannot cancel out.+ let n = 2 * NORM_CHUNK_FEATURES as usize + 7;+ let features: Vec<NormalizedFeature> = (0..n)+ .map(|i| {+ let f = i as f64;+ if i % 3 == 0 {+ NormalizedFeature {+ geometry: Geometry::Points(vec![(f * 0.01, -f * 0.02)]),+ props: vec![("i".to_string(), Value::Uint(i as u64))],+ }+ } else if i % 3 == 1 {+ NormalizedFeature {+ geometry: Geometry::Lines(vec![vec![(f * 0.01, 1.0), (f * 0.01, 2.0)]]),+ props: every_value(),+ }+ } else {+ NormalizedFeature {+ geometry: Geometry::Lines(vec![vec![(0.0, f * 0.01), (1.0, f * 0.01)]]),+ props: vec![],+ }+ }+ })+ .collect();++ let mut w = NormalizedWriter::create(&path).unwrap();+ for f in &features {+ w.push(&f.geometry, &f.props).unwrap();+ }+ let summary = w.finish().unwrap();+ assert_eq!(summary.count, n as u64);+ assert_eq!(summary.chunk_count(), 3, "two full chunks and a partial one");+ assert_eq!(+ *summary.chunks.last().unwrap(),+ std::fs::metadata(&path).unwrap().len(),+ "the sentinel must be the file's length"+ );++ let chunks = NormalizedChunks::open(&path, summary.chunks.clone()).unwrap();+ let mut scratch = Vec::new();+ let mut out = Vec::new();+ let mut back = Vec::new();+ for i in 0..chunks.chunk_count() {+ chunks.read_into(i, &mut scratch, &mut out).unwrap();+ // The alignment the `seq` reconstruction depends on.+ assert_eq!(+ back.len() as u64,+ i as u64 * NORM_CHUNK_FEATURES,+ "chunk {i} must start at feature {}",+ i as u64 * NORM_CHUNK_FEATURES+ );+ back.extend(out.iter().cloned());+ }+ assert_eq!(back, features, "the chunked read must match the input");++ // And the sequential reader, so neither can drift from the other.+ let mut r = NormalizedReader::open(&path).unwrap();+ let mut seq = Vec::new();+ while let Some(f) = r.next().unwrap() {+ seq.push(f);+ }+ assert_eq!(back, seq, "the two readers must agree");++ assert!(+ chunks+ .read_into(chunks.chunk_count(), &mut scratch, &mut out)+ .is_err(),+ "a chunk past the end must error rather than read nothing"+ );++ let _ = std::fs::remove_dir_all(&dir);+ }++ /// A corrupt chunk index must be reported, not silently mis-decoded: the offsets are+ /// the one part of the format the records themselves cannot validate.+ #[test]+ fn a_chunk_index_pointing_into_a_record_errors() {+ let dir = tmp("normchunkbad");+ let path = dir.join("f.bin");+ let mut w = NormalizedWriter::create(&path).unwrap();+ for i in 0..NORM_CHUNK_FEATURES + 3 {+ w.push(+ &Geometry::Lines(vec![vec![(i as f64, 1.0), (i as f64, 2.0)]]),+ &every_value(),+ )+ .unwrap();+ }+ let summary = w.finish().unwrap();++ let mut scratch = Vec::new();+ let mut out = Vec::new();++ // Nudge a boundary into the middle of a record.+ let mut bad = summary.chunks.clone();+ bad[1] += 3;+ let chunks = NormalizedChunks::open(&path, bad).unwrap();+ assert!(+ chunks.read_into(0, &mut scratch, &mut out).is_err()+ || chunks.read_into(1, &mut scratch, &mut out).is_err(),+ "a misaligned boundary must error"+ );++ // A boundary that runs backwards.+ let mut backwards = summary.chunks.clone();+ backwards[1] = backwards[0];+ backwards[0] = *summary.chunks.last().unwrap();+ let chunks = NormalizedChunks::open(&path, backwards).unwrap();+ assert!(+ chunks.read_into(0, &mut scratch, &mut out).is_err(),+ "a backwards range must error"+ );++ let _ = std::fs::remove_dir_all(&dir);+ }+ /// The summary's bounds must be exactly what the in-memory path computes, or the /// two producers write different header bytes for the same input. #[test]