From 1c51b55bb3ff28323664f98834fdf4538db32653 Mon Sep 17 00:00:00 2001 From: Li-Sheng Chou <142213184+choupeanut@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:45:04 +0800 Subject: [PATCH 01/22] fix(data): GeoParquet row groups decode within a byte budget on every read, not only an unbounded view (#2913) --- crates/data/src/source/parquet.rs | 314 ++++++++++++++++++++++++------ crates/data/src/source/tests.rs | 102 +++++++++- docs/user-guide/data-formats.md | 2 +- 3 files changed, 352 insertions(+), 66 deletions(-) diff --git a/crates/data/src/source/parquet.rs b/crates/data/src/source/parquet.rs index f977e74ffa..a2a014d6fe 100644 --- a/crates/data/src/source/parquet.rs +++ b/crates/data/src/source/parquet.rs @@ -18,7 +18,7 @@ use crate::{DataError, Feature, Field, FieldType, GeometryType, Result, Value, w use bytes::Bytes; use parquet::basic::{ConvertedType, Encoding, LogicalType, Type as Physical}; use parquet::column::reader::{ColumnReader, ColumnReaderImpl}; -use parquet::data_type::DataType as PqType; +use parquet::data_type::{ByteArray, DataType as PqType}; use parquet::file::metadata::ParquetMetaData; use parquet::file::reader::{FileReader, RowGroupReader, SerializedFileReader}; use parquet::file::statistics::Statistics; @@ -37,6 +37,47 @@ const MAX_GROUP_ROWS: usize = if cfg!(target_arch = "wasm32") { 1 << 21 } else { /// Conservative decoded-column budget for one group scanned without native view bounds. const MAX_SCAN_BYTES: u64 = if cfg!(target_arch = "wasm32") { 64 << 20 } else { 256 << 20 }; +/// The least [`max_decoded_bytes`] allows, and its limit in the browser. +const DECODED_FLOOR: usize = if cfg!(target_arch = "wasm32") { 128 << 20 } else { 512 << 20 }; +/// The most [`max_decoded_bytes`] allows, however much the computer has. +const DECODED_CEILING: usize = 3 << 30; + +/// Most bytes of text and geometry one row group's read may decode into owned values, whatever the +/// view: on the desktop a quarter of the computer's memory, from [`DECODED_FLOOR`] up to +/// [`DECODED_CEILING`]; less once RustGIS holds more than half of it ([`crate::memory::planned`], #2431). +/// A file's sizes don't bound it: one long dictionary entry used by every row is copied for each. +fn max_decoded_bytes() -> u64 { + u64::try_from(crate::memory::planned(DECODED_FLOOR, DECODED_CEILING, 1)).unwrap_or(u64::MAX) +} + +/// What one row group's read may still decode into owned values ([`max_decoded_bytes`]), shared +/// by the columns decoded together. +struct Budget { + left: std::cell::Cell, + limit: u64, + group: usize, +} + +impl Budget { + fn new(limit: u64, group: usize) -> Self { + Budget { left: std::cell::Cell::new(limit), limit, group } + } + + /// Takes `bytes` of the budget for a value of `column`, or refuses the group. + fn charge(&self, bytes: usize, column: &str) -> Result<()> { + let left = self.left.get().checked_sub(u64::try_from(bytes).unwrap_or(u64::MAX)).ok_or_else(|| self.refusal(column))?; + self.left.set(left); + Ok(()) + } + + fn refusal(&self, column: &str) -> DataError { + DataError::Format(format!( + "GeoParquet: row group {} exceeds the {} byte decoded-column budget in column '{column}'; rewrite the file with smaller row groups", + self.group, self.limit + )) + } +} + /// What a GeoParquet source's reads are attributed to ([`ParquetSource::attribute`]). #[derive(Clone, Debug)] enum Attributed { @@ -74,6 +115,8 @@ pub struct ParquetSource { group_rows: usize, /// Decoded-column budget for an unbounded spatial scan; lowered by tests. scan_bytes: u64, + /// Decoded bytes one row group's text and geometry values may take in any read; lowered by tests. + decoded_bytes: u64, /// Declared after `reader`: Windows must close its file before removing the workspace. #[cfg(not(target_arch = "wasm32"))] _workspace: Option>, @@ -343,6 +386,7 @@ impl ParquetSource { exact: false, group_rows: MAX_GROUP_ROWS, scan_bytes: MAX_SCAN_BYTES, + decoded_bytes: max_decoded_bytes(), #[cfg(not(target_arch = "wasm32"))] _workspace: None, }; @@ -373,7 +417,7 @@ impl ParquetSource { } let rows = usize::try_from(md.row_group(0).num_rows()).unwrap_or(0).min(16); let rg = self.reader.get_row_group(0).ok()?; - let geoms = read_bytes(rg.as_ref(), self.geom_col, &vec![true; rows]).ok()?; + let geoms = read_bytes(rg.as_ref(), self.geom_col, &vec![true; rows], &Budget::new(self.decoded_bytes, 0)).ok()?; Some(geoms.iter().filter_map(|b| b.as_deref()).any(wkb::has_zm)) } } @@ -393,6 +437,13 @@ impl ParquetSource { self } + /// A lower decoded-byte budget for any read, for tests without large allocations. + #[cfg(test)] + pub(crate) fn with_decoded_bytes(mut self, bytes: u64) -> Self { + self.decoded_bytes = bytes; + self + } + /// The rows of row group `g` read. Row counts come from the file: bounded by what the /// geometry column chunk holds, and by a cap, so a crafted count can't size a huge allocation. fn rows_in(&self, md: &ParquetMetaData, g: usize) -> usize { @@ -691,8 +742,10 @@ impl FeatureSource for ParquetSource { self.check_scan_bytes(md, g, true)?; } let rg = self.reader.get_row_group(g).map_err(err)?; - let geoms = read_bytes(rg.as_ref(), self.geom_col, take)?; - let attrs: Vec = self.field_cols.iter().map(|&c| read_values(rg.as_ref(), c, take)).collect::>()?; + let budget = Budget::new(self.decoded_bytes, g); + let geoms = read_bytes(rg.as_ref(), self.geom_col, take, &budget)?; + let attrs: Vec = + self.field_cols.iter().map(|&c| read_values(rg.as_ref(), c, take, &budget)).collect::>()?; // A column shorter than its row group (a truncated or corrupt file) would pair values // with the wrong rows: refuse it. let wanted = take.iter().filter(|&&t| t).count(); @@ -807,8 +860,10 @@ impl FeatureSource for ParquetSource { continue; } let rg = self.reader.get_row_group(g).map_err(err)?; - let geoms = read_bytes(rg.as_ref(), self.geom_col, &take)?; - let attrs: Vec = self.field_cols.iter().map(|&c| read_values(rg.as_ref(), c, &take)).collect::>()?; + let budget = Budget::new(self.decoded_bytes, g); + let geoms = read_bytes(rg.as_ref(), self.geom_col, &take, &budget)?; + let attrs: Vec = + self.field_cols.iter().map(|&c| read_values(rg.as_ref(), c, &take, &budget)).collect::>()?; let wanted = take.iter().filter(|&&t| t).count(); if geoms.len() != wanted || attrs.iter().any(|a| a.values.len() != wanted) { return Err(DataError::Format(format!("GeoParquet: row group {g} has columns shorter than its rows"))); @@ -979,17 +1034,29 @@ fn column_reader(rg: &dyn RowGroupReader, col: usize) -> Result { Physical::INT96 => 96, Physical::FIXED_LEN_BYTE_ARRAY => u64::try_from(desc.type_length()).unwrap_or(0).max(1) * 8, }; - let pages = CheckedPages { pages: rg.get_column_page_reader(col).map_err(err)?, bits }; + let chunk = rg.metadata().column(col); + let pages = CheckedPages { + pages: rg.get_column_page_reader(col).map_err(err)?, + bits, + chunk_bytes: u64::try_from(chunk.uncompressed_size()).unwrap_or(0), + delta_declared: chunk.encodings().any(|e| e == Encoding::DELTA_BYTE_ARRAY), + }; Ok(parquet::column::reader::get_column_reader(desc, Box::new(pages))) } /// A column's pages, a dictionary page refused when it says it holds more values than its bytes /// can: the `parquet` crate makes room for the count it is told before decoding any (a few bytes -/// of header can ask for tens of gigabytes). +/// of header can ask for tens of gigabytes). A page bigger than the column chunk it belongs to, and +/// a data page in the DELTA_BYTE_ARRAY encoding that the chunk doesn't list, are refused too: the +/// batch sizes of [`read_binary`] rest on both. struct CheckedPages { pages: Box, /// The fewest bits one value of the column takes in a dictionary page (plain encoded). bits: u64, + /// The bytes the column chunk's footer says its pages hold decoded, `0` when it says none. + chunk_bytes: u64, + /// The footer lists the DELTA_BYTE_ARRAY encoding for the chunk. + delta_declared: bool, } impl Iterator for CheckedPages { @@ -1014,6 +1081,23 @@ impl parquet::column::page::PageReader for CheckedPages { buf.len() ))); } + if let Some(page) = &page { + let len = page.buffer().len() as u64; + if self.chunk_bytes > 0 && len > self.chunk_bytes { + return Err(parquet::errors::ParquetError::General(format!( + "a page holds {len} bytes, more than the {} its column chunk says it holds", + self.chunk_bytes + ))); + } + if !self.delta_declared + && let parquet::column::page::Page::DataPage { encoding: Encoding::DELTA_BYTE_ARRAY, .. } + | parquet::column::page::Page::DataPageV2 { encoding: Encoding::DELTA_BYTE_ARRAY, .. } = page + { + return Err(parquet::errors::ParquetError::General( + "a page uses the DELTA_BYTE_ARRAY encoding, which its column chunk doesn't list".into(), + )); + } + } Ok(page) } @@ -1242,6 +1326,18 @@ fn field_type(c: &ColumnDescPtr) -> Option { /// rows not taken are skipped without being decoded into values, so a sample of a large row /// group doesn't hold all of it. fn read_column(r: &mut ColumnReaderImpl, take: &[bool], max_def: i16) -> Result>> { + read_column_with(r, take, max_def, &|| BATCH, &mut |_| Ok(())) +} + +/// [`read_column`] asking `batch` for the most values to read at once and `charge` about each value +/// it keeps, before the caller copies any: a read that passes its budget stops there. +fn read_column_with( + r: &mut ColumnReaderImpl, + take: &[bool], + max_def: i16, + batch: &dyn Fn() -> usize, + charge: &mut dyn FnMut(&T::T) -> Result<()>, +) -> Result>> { let wanted = take.iter().filter(|&&t| t).count(); let mut out: Vec> = Vec::with_capacity(wanted.min(1 << 24)); let mut defs = Vec::new(); @@ -1264,17 +1360,24 @@ fn read_column(r: &mut ColumnReaderImpl, take: &[bool], max_def: i while left > 0 { defs.clear(); values.clear(); - let (records, _, levels) = r.read_records(left.min(BATCH), Some(&mut defs), None, &mut values).map_err(err)?; + let (records, _, levels) = r.read_records(left.min(batch().max(1)), Some(&mut defs), None, &mut values).map_err(err)?; if records == 0 { return Ok(out); } left = left.saturating_sub(records); if max_def == 0 { - out.extend(values.drain(..).map(Some)); + for v in values.drain(..) { + charge(&v)?; + out.push(Some(v)); + } } else { let mut it = values.drain(..); for d in defs.iter().take(levels) { - out.push(if *d == max_def { it.next() } else { None }); + let v = if *d == max_def { it.next() } else { None }; + if let Some(v) = &v { + charge(v)?; + } + out.push(v); } } } @@ -1338,7 +1441,7 @@ impl ColumnValues { } /// Reads a field column for the selected rows, keeping date flags for the final filter. -fn read_values(rg: &dyn RowGroupReader, col: usize, take: &[bool]) -> Result { +fn read_values(rg: &dyn RowGroupReader, col: usize, take: &[bool], budget: &Budget) -> Result { let desc = rg.metadata().column(col).column_descr_ptr(); let max_def = desc.max_def_level(); let scale = decimal_scale(&desc).map(|s| 10f64.powi(-s)); @@ -1384,48 +1487,50 @@ fn read_values(rg: &dyn RowGroupReader, col: usize, take: &[bool]) -> Result Value::Int(i), } }; - let values = match column_reader(rg, col)? { - ColumnReader::BoolColumnReader(mut r) => { - read_column(&mut r, take, max_def)?.into_iter().map(|v| v.map(Value::Bool).unwrap_or_default()).collect() - } - ColumnReader::Int32ColumnReader(mut r) => read_column(&mut r, take, max_def)?.into_iter().map(|v| int(v.map(i64::from))).collect(), - ColumnReader::Int64ColumnReader(mut r) => read_column(&mut r, take, max_def)?.into_iter().map(int).collect(), - ColumnReader::Int96ColumnReader(mut r) => read_column(&mut r, take, max_def)? - .into_iter() - .map(|v| { - flags.push(0u8); - v.map(|v| { - let words = v.data(); - let ns = u64::from(words.first().copied().unwrap_or(0)) | (u64::from(words.get(1).copied().unwrap_or(0)) << 32); - let day = i64::from(words.get(2).copied().unwrap_or(0)) - 2_440_588; - let (rounded, cut, lossy) = nanos_to_micros(ns as i64); - let at = |us: Option| day.checked_mul(86_400_000_000)?.checked_add(us?).and_then(crate::DateTime::local); - let t = if ns < 86_400_000_000_000 { at(rounded).or_else(|| at(cut)) } else { None }; - if let Some(flag) = flags.last_mut() { - *flag = if t.is_none() { - INVALID - } else if lossy { - ROUNDED - } else { - 0 - }; - } - t.map(Value::DateTime).unwrap_or_default() + let values = if let Some(binary) = read_binary(rg, col, take, budget)? { + binary.into_iter().map(|v| v.map(|b| Value::Text(String::from_utf8_lossy(b.data()).into_owned())).unwrap_or_default()).collect() + } else { + match column_reader(rg, col)? { + ColumnReader::BoolColumnReader(mut r) => { + read_column(&mut r, take, max_def)?.into_iter().map(|v| v.map(Value::Bool).unwrap_or_default()).collect() + } + ColumnReader::Int32ColumnReader(mut r) => { + read_column(&mut r, take, max_def)?.into_iter().map(|v| int(v.map(i64::from))).collect() + } + ColumnReader::Int64ColumnReader(mut r) => read_column(&mut r, take, max_def)?.into_iter().map(int).collect(), + ColumnReader::Int96ColumnReader(mut r) => read_column(&mut r, take, max_def)? + .into_iter() + .map(|v| { + flags.push(0u8); + v.map(|v| { + let words = v.data(); + let ns = u64::from(words.first().copied().unwrap_or(0)) | (u64::from(words.get(1).copied().unwrap_or(0)) << 32); + let day = i64::from(words.get(2).copied().unwrap_or(0)) - 2_440_588; + let (rounded, cut, lossy) = nanos_to_micros(ns as i64); + let at = |us: Option| day.checked_mul(86_400_000_000)?.checked_add(us?).and_then(crate::DateTime::local); + let t = if ns < 86_400_000_000_000 { at(rounded).or_else(|| at(cut)) } else { None }; + if let Some(flag) = flags.last_mut() { + *flag = if t.is_none() { + INVALID + } else if lossy { + ROUNDED + } else { + 0 + }; + } + t.map(Value::DateTime).unwrap_or_default() + }) + .unwrap_or_default() }) - .unwrap_or_default() - }) - .collect(), - ColumnReader::FloatColumnReader(mut r) => { - read_column(&mut r, take, max_def)?.into_iter().map(|v| v.map(|f| Value::Float(f64::from(f))).unwrap_or_default()).collect() - } - ColumnReader::DoubleColumnReader(mut r) => { - read_column(&mut r, take, max_def)?.into_iter().map(|v| v.map(Value::Float).unwrap_or_default()).collect() + .collect(), + ColumnReader::FloatColumnReader(mut r) => { + read_column(&mut r, take, max_def)?.into_iter().map(|v| v.map(|f| Value::Float(f64::from(f))).unwrap_or_default()).collect() + } + ColumnReader::DoubleColumnReader(mut r) => { + read_column(&mut r, take, max_def)?.into_iter().map(|v| v.map(Value::Float).unwrap_or_default()).collect() + } + _ => Vec::new(), } - ColumnReader::ByteArrayColumnReader(mut r) => read_column(&mut r, take, max_def)? - .into_iter() - .map(|v| v.map(|b| Value::Text(String::from_utf8_lossy(b.data()).into_owned())).unwrap_or_default()) - .collect(), - _ => Vec::new(), }; Ok(ColumnValues { values, flags }) } @@ -1452,15 +1557,35 @@ fn binary_dictionary_max(bytes: &[u8], count: u32) -> Result { Ok(longest) } -/// Reads a binary column (the WKB geometry), for the rows `take` marks, in order. -fn read_bytes(rg: &dyn RowGroupReader, col: usize, take: &[bool]) -> Result>>> { - let max_def = rg.metadata().column(col).column_descr().max_def_level(); - match column_reader(rg, col)? { - ColumnReader::ByteArrayColumnReader(mut r) => { - Ok(read_column(&mut r, take, max_def)?.into_iter().map(|v| v.map(|b| b.data().to_vec())).collect()) - } - _ => Err(DataError::Format("GeoParquet: the geometry column is not binary".into())), +/// Reads a binary column (the WKB geometry), for the rows `take` marks, in order, within `budget`. +fn read_bytes(rg: &dyn RowGroupReader, col: usize, take: &[bool], budget: &Budget) -> Result>>> { + match read_binary(rg, col, take, budget)? { + Some(values) => Ok(values.into_iter().map(|v| v.map(|b| b.data().to_vec())).collect()), + None => Err(DataError::Format("GeoParquet: the geometry column is not binary".into())), + } +} + +/// The rows `take` marks of a BYTE_ARRAY column, charging `budget` for each value as it is read, +/// before any is copied (`None` for a column of another type). The column chunk's own bytes may not +/// pass the budget either: no honest page is bigger than its chunk, and the `parquet` crate makes +/// room for a page from its header. A column with DELTA_BYTE_ARRAY pages, whose values the +/// decoder builds one by one, reads no more values at once than the budget left holds at the most +/// a page's size each. +fn read_binary(rg: &dyn RowGroupReader, col: usize, take: &[bool], budget: &Budget) -> Result>>> { + let chunk = rg.metadata().column(col); + if chunk.column_descr().physical_type() != Physical::BYTE_ARRAY { + return Ok(None); + } + let name = chunk.column_path().string(); + let bytes = u64::try_from(chunk.uncompressed_size()).unwrap_or(u64::MAX); + if bytes > budget.limit { + return Err(budget.refusal(&name)); } + let ColumnReader::ByteArrayColumnReader(mut r) = column_reader(rg, col)? else { return Ok(None) }; + let delta = chunk.encodings().any(|e| e == Encoding::DELTA_BYTE_ARRAY); + let batch = || if delta { usize::try_from(budget.left.get() / bytes.max(1)).unwrap_or(BATCH).clamp(1, BATCH) } else { BATCH }; + read_column_with(&mut r, take, chunk.column_descr().max_def_level(), &batch, &mut |b: &ByteArray| budget.charge(b.len(), &name)) + .map(Some) } /// Reads every one of `n` rows of a float or double column as doubles (the covering). @@ -1523,7 +1648,7 @@ pub fn read_vectors(file: &Arc, extent: &Extent, column: &str, max_group for &g in &groups { let rg = reader.get_row_group(g).map_err(err)?; let rows = usize::try_from(rg.metadata().num_rows()).unwrap_or(0).min(MAX_GROUP_ROWS); - let geoms = read_bytes(rg.as_ref(), geom, &vec![true; rows])?; + let geoms = read_bytes(rg.as_ref(), geom, &vec![true; rows], &Budget::new(max_decoded_bytes(), g))?; let inside: Vec<(usize, (f64, f64))> = geoms .iter() .enumerate() @@ -1864,7 +1989,7 @@ pub(crate) fn write_features( feed: &mut dyn FnMut(&mut dyn FnMut(&[Feature]) -> Result<()>) -> Result<()>, ) -> Result<(W, Vec, Vec)> { use parquet::basic::{Compression, Encoding, Repetition, ZstdLevel}; - use parquet::data_type::{BoolType, ByteArray, ByteArrayType, DoubleType, Int32Type, Int64Type}; + use parquet::data_type::{BoolType, ByteArrayType, DoubleType, Int32Type, Int64Type}; use parquet::file::metadata::KeyValue; use parquet::file::properties::WriterProperties; use parquet::file::writer::SerializedFileWriter; @@ -2055,3 +2180,68 @@ pub(crate) fn write_features( // Without a target: the caller says the path the export is written to. Ok((w.into_inner().map_err(err)?, unfit_counts, layout.notes(fields, ""))) } + +#[cfg(test)] +mod tests { + use super::*; + use parquet::column::page::{Page, PageMetadata, PageReader}; + + /// Pages handed out one by one, as a file's would be. + struct Pages(std::vec::IntoIter); + + impl Iterator for Pages { + type Item = parquet::errors::Result; + fn next(&mut self) -> Option { + self.0.next().map(Ok) + } + } + + impl PageReader for Pages { + fn get_next_page(&mut self) -> parquet::errors::Result> { + Ok(self.0.next()) + } + fn peek_next_page(&mut self) -> parquet::errors::Result> { + Ok(None) + } + fn skip_next_page(&mut self) -> parquet::errors::Result<()> { + Ok(()) + } + fn at_record_boundary(&mut self) -> parquet::errors::Result { + Ok(true) + } + } + + fn data_page(bytes: usize, encoding: Encoding) -> Page { + Page::DataPage { + buf: Bytes::from(vec![0u8; bytes]), + num_values: 1, + encoding, + def_level_encoding: Encoding::RLE, + rep_level_encoding: Encoding::RLE, + statistics: None, + } + } + + fn checked(page: Page, chunk_bytes: u64, delta_declared: bool) -> parquet::errors::Result> { + CheckedPages { pages: Box::new(Pages(vec![page].into_iter())), bits: 32, chunk_bytes, delta_declared }.get_next_page() + } + + /// A page can't hold more than the column chunk it belongs to says it does. + #[test] + fn checked_pages_refuse_a_page_larger_than_its_chunk() { + let error = checked(data_page(11, Encoding::PLAIN), 10, false).unwrap_err().to_string(); + assert!(error.contains("a page holds 11 bytes, more than the 10 its column chunk says it holds"), "{error}"); + assert!(checked(data_page(10, Encoding::PLAIN), 10, false).unwrap().is_some()); + // A footer that gives no size says nothing to check against. + assert!(checked(data_page(11, Encoding::PLAIN), 0, false).unwrap().is_some()); + } + + /// A page in the one encoding that builds its values one by one must be in the chunk's list. + #[test] + fn checked_pages_refuse_an_undeclared_delta_page() { + let error = checked(data_page(4, Encoding::DELTA_BYTE_ARRAY), 10, false).unwrap_err().to_string(); + assert!(error.contains("the DELTA_BYTE_ARRAY encoding, which its column chunk doesn't list"), "{error}"); + assert!(checked(data_page(4, Encoding::DELTA_BYTE_ARRAY), 10, true).unwrap().is_some()); + assert!(checked(data_page(4, Encoding::PLAIN), 10, false).unwrap().is_some()); + } +} diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 43cb396a54..7244487036 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -5189,6 +5189,92 @@ fn unbounded_parquet_view_refuses_decoded_columns_over_budget() { assert_eq!(batch.features[0].attrs[0], Value::Text("x".repeat(1024))); } +/// A whole read, an export and a view with bounds decode a dictionary's one long value once for +/// each row they take, so they stop at the decoded-column budget as an unbounded view does (#2913). +#[test] +fn parquet_reads_refuse_decoded_columns_over_budget_without_a_view() { + let p = dir().join("decoded-reads.parquet"); + let mut ds = Dataset::new("pts", GeometryType::Point, vec![Field::new("label", FieldType::Text)]); + for _ in 0..20 { + ds.push(Some(Geometry::Point(Coord::new(-81.0, 0.0))), vec![Value::Text("x".repeat(1024))]); + } + write_unbounded_view_fixture(&ds, &p); + let source = parquet::ParquetSource::open_path(&p, "pts").unwrap().with_decoded_bytes(8 << 10); + let whole = Request { extent: None, limit: 100, own: None }; + let error = source.read(&whole).unwrap_err().to_string(); + assert!(error.contains("decoded-column budget") && error.contains("column 'label'"), "{error}"); + let bounded = Request { extent: Some(Extent::new(-84.0, -1.0, -78.0, 1.0)), limit: 100, own: None }; + let error = source.read(&bounded).unwrap_err().to_string(); + assert!(error.contains("decoded-column budget"), "{error}"); + let error = source.visit_chunks(None, 4096, &mut |_| Ok(())).unwrap_err().to_string(); + assert!(error.contains("decoded-column budget"), "{error}"); + let error = source.visit_chunks(bounded.extent, 4096, &mut |_| Ok(())).unwrap_err().to_string(); + assert!(error.contains("decoded-column budget"), "{error}"); + // Only the rows a read takes count: one row of 1 KiB is under 8 KiB. + let one = Request { extent: Some(Extent::new(-84.0, -1.0, -78.0, 1.0)), limit: 1, own: None }; + assert_eq!(source.read(&one).unwrap().features.len(), 1); + // Clean input, no refusal: the default budget reads every row. + let source = parquet::ParquetSource::open_path(&p, "pts").unwrap(); + let batch = source.read(&whole).unwrap(); + assert_eq!(batch.features.len(), 20); + assert_eq!(batch.features[0].attrs[0], Value::Text("x".repeat(1024))); + let mut rows = 0; + source + .visit_chunks(None, 1 << 20, &mut |chunk| { + rows += chunk.len(); + Ok(()) + }) + .unwrap(); + assert_eq!(rows, 20); +} + +/// The geometry column's decoded bytes count with the fields', in the same row group. +#[test] +fn parquet_geometry_column_is_charged_with_the_fields() { + let p = dir().join("decoded-geometry.parquet"); + let mut ds = Dataset::new("pts", GeometryType::Point, vec![]); + for i in 0..20 { + ds.push(Some(Geometry::Point(Coord::new(-81.0 + f64::from(i) / 100.0, 0.0))), vec![]); + } + write_unbounded_view_fixture(&ds, &p); + let whole = Request { extent: None, limit: 100, own: None }; + let source = parquet::ParquetSource::open_path(&p, "pts").unwrap().with_decoded_bytes(100); + let error = source.read(&whole).unwrap_err().to_string(); + assert!(error.contains("column 'geometry'"), "{error}"); + let source = parquet::ParquetSource::open_path(&p, "pts").unwrap().with_decoded_bytes(1 << 10); + assert_eq!(source.read(&whole).unwrap().features.len(), 20); +} + +/// A DELTA_BYTE_ARRAY column builds each value in the decoder, so its reads take fewer values at a +/// time as the budget gets smaller, and still read every row, or stop at the budget (#2913). +#[test] +fn parquet_delta_byte_array_reads_within_the_decoded_budget() { + let p = dir().join("decoded-delta.parquet"); + let mut ds = Dataset::new("pts", GeometryType::Point, vec![Field::new("label", FieldType::Text)]); + for i in 0..20 { + ds.push(Some(Geometry::Point(Coord::new(-81.0, 0.0))), vec![Value::Text(format!("{}{i:02}", "x".repeat(1024)))]); + } + write_encoded_parquet_fixture(&ds, &p, 100, false, true); + let footer = ::parquet::file::reader::SerializedFileReader::new(std::fs::File::open(&p).unwrap()).unwrap(); + let encodings: Vec<_> = ::parquet::file::reader::FileReader::metadata(&footer) + .row_group(0) + .columns() + .iter() + .filter(|c| c.column_path().string() == "label") + .flat_map(|c| c.encodings()) + .collect(); + assert!(encodings.contains(&::parquet::basic::Encoding::DELTA_BYTE_ARRAY), "{encodings:?}"); + let whole = Request { extent: None, limit: 100, own: None }; + // 20 values of 1,026 bytes: a budget of 32 KiB reads them all, a smaller one stops. + let source = parquet::ParquetSource::open_path(&p, "pts").unwrap().with_decoded_bytes(32 << 10); + let batch = source.read(&whole).unwrap(); + assert_eq!(batch.features.len(), 20); + assert_eq!(batch.features[19].attrs[0], Value::Text(format!("{}19", "x".repeat(1024)))); + let source = parquet::ParquetSource::open_path(&p, "pts").unwrap().with_decoded_bytes(16 << 10); + let error = source.read(&whole).unwrap_err().to_string(); + assert!(error.contains("decoded-column budget"), "{error}"); +} + /// The same small file must remain readable with plain or dictionary-encoded binary columns. #[test] fn unbounded_parquet_scan_accepts_two_thousand_distinct_points() { @@ -5279,6 +5365,11 @@ fn write_unbounded_view_fixture(ds: &Dataset, path: &Path) { /// A UTM fixture with selectable row-group size and binary encoding, using the same covering. fn write_projected_parquet_fixture(ds: &Dataset, path: &Path, rows: usize, dictionary: bool) { + write_encoded_parquet_fixture(ds, path, rows, dictionary, false); +} + +/// [`write_projected_parquet_fixture`], its text fields in the DELTA_BYTE_ARRAY encoding when `delta`. +fn write_encoded_parquet_fixture(ds: &Dataset, path: &Path, rows: usize, dictionary: bool, delta: bool) { let crs = Crs::from_epsg(32617).unwrap(); use arrow_array::{BinaryArray, Float64Array, RecordBatch, StringArray, StructArray}; use arrow_schema::{DataType, Field as AField, Schema}; @@ -5317,11 +5408,16 @@ fn write_projected_parquet_fixture(ds: &Dataset, path: &Path, rows: usize, dicti "encoding": "WKB", "geometry_types": ["Point"], "crs": {"type": "ProjectedCRS", "id": {"authority": "EPSG", "code": 32617}}, "covering": {"bbox": {"xmin": ["bbox", "xmin"], "ymin": ["bbox", "ymin"], "xmax": ["bbox", "xmax"], "ymax": ["bbox", "ymax"]}} }}}); - let props = ::parquet::file::properties::WriterProperties::builder() + let mut props = ::parquet::file::properties::WriterProperties::builder() .set_max_row_group_row_count(Some(rows)) .set_dictionary_enabled(dictionary) - .set_key_value_metadata(Some(vec![::parquet::file::metadata::KeyValue::new("geo".into(), geo.to_string())])) - .build(); + .set_key_value_metadata(Some(vec![::parquet::file::metadata::KeyValue::new("geo".into(), geo.to_string())])); + if delta { + for field in ds.fields.iter().filter(|f| f.ty == FieldType::Text) { + props = props.set_column_encoding(field.name.as_str().into(), ::parquet::basic::Encoding::DELTA_BYTE_ARRAY); + } + } + let props = props.build(); let mut writer = ::parquet::arrow::ArrowWriter::try_new(std::fs::File::create(path).unwrap(), schema, Some(props)).unwrap(); writer.write(&batch).unwrap(); writer.close().unwrap(); diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 74e45c0a7a..a85f72c921 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -39,7 +39,7 @@ export names its feature. | Geotagged photos | `.jpg`, `.jpeg` | Add Data (several at once in the web app), drop them, upload, or `layer.addPhotos` with `"paths"` or a `"folder"` | JPEGs with a GPS position in their EXIF become points in the **Photos** layer (photos added one at a time join it): each with its `name`, `file`, `time` (when it was taken), `altitude`, `direction` (where the camera faced), `camera` and a `thumbnail` of at most 160 pixels, kept with the feature so the project needs no other file. Identify shows the thumbnail. Photos without a position are named in a notice and left out; a layer holds up to 2,000 photos. A JPEG is always read as a photo unless `layer.addData` or `layer.addDataBytes` is given `"as": "scan"` (a phone photo of a paper map, say: see [Scans with no coordinates](#rasters)). | | LiDAR point clouds | `.las`, `.laz` (COPC too) | Add Data, drop the file, upload, or From URL… | LAS 1.0–1.4 (point formats 0–10) and LAZ, on desktop and web: points with `z`, `intensity`, `classification`, `return` and colour (`red`, `green`, `blue`), coloured by ASPRS class or elevation. An evenly spread sample is read once, at most 2 million points (500,000 in the web app); views use that sample, not the COPC spatial index. LAZ decompression reads at most the first 400 million points (40 million on the web), with a notice when capped. Held in the system of the file's WKT or GeoTIFF-key record, as the file holds its points; without one, coordinates are kept as longitude/latitude, with a notice when they aren't. Points with no place in longitude/latitude are kept and counted ([below](#places-with-no-longitudelatitude)); points with a coordinate that isn't a number are left out and counted. A local project keeps the path; uploads keep the file bytes. Remote files download whole. | | GeoPackage | `.gpkg` | Add Data, or upload in the web app | Local files and browser uploads add every feature table, up to 32 (with the rest counted in `skippedCount` and up to 100 named in `skipped`); `"layer"` picks one, and `info.fileLayers` lists them. Desktop byte uploads and downloads add the first table unless `"layer"` names another. Large local tables use their R-tree. Rows with no geometry (NULL or empty) are kept, with their attributes, in whole reads and exports; a read of an extent leaves them out, as they have no location. A table is read in its coordinate system: by its EPSG code, or, for a system without one (or with a code RustGIS doesn't know), by the WKT definition the file gives it (the WKT2 of GeoPackage 1.2's `definition_12_063` first, as the specification says, else `definition`). The definition also comes before the code when it gives another datum transformation than the code's, or describes another body's system. This holds on the desktop and in the web app alike (an azimuthal equidistant system opens on the desktop only, and the web app says so). Browser tables are scanned, testing each geometry header's envelope first; UTF-16 databases aren't read there. Raster tile tables aren't imported. `DATE` and `DATETIME` columns are read as dates and date-times (ISO 8601 text, as GeoPackage stores them); a value that isn't one is empty and counted in a notice. | -| GeoParquet | `.parquet`, `.geoparquet` | Add Data, or upload in the web app | WKB geometry, with the CRS from the file's `geo` metadata. A binary geometry column is required; plain non-spatial Parquet tables and GeoArrow-native geometry encodings aren't read by this importer. Row groups are pruned by the bbox covering. Whole reads and exports retain rows with null geometry and their attributes; extent-filtered reads exclude them because they have no location. Snappy, gzip, LZ4 and zstd compression are read, in the browser too; Brotli isn't. Text, whole-number, floating-point and true/false columns become fields, as do decimals stored as 32- or 64-bit integers (up to 18 digits), read as floating-point numbers. Dates and times stored as 32- or 64-bit integers are read as those whole numbers (such as milliseconds since 1970). Other columns are left out: decimals stored as bytes (how many writers store every decimal), binary, lists, maps, structs, INT96 timestamps and further geometry columns. A notice gives how many were left out and names the first 12, each with its kind; another names the date and time columns with their unit. | +| GeoParquet | `.parquet`, `.geoparquet` | Add Data, or upload in the web app | WKB geometry, with the CRS from the file's `geo` metadata. A binary geometry column is required; plain non-spatial Parquet tables and GeoArrow-native geometry encodings aren't read by this importer. Row groups are pruned by the bbox covering. Whole reads and exports retain rows with null geometry and their attributes; extent-filtered reads exclude them because they have no location. Snappy, gzip, LZ4 and zstd compression are read, in the browser too; Brotli isn't. Text, whole-number, floating-point and true/false columns become fields, as do decimals stored as 32- or 64-bit integers (up to 18 digits), read as floating-point numbers. Dates and times stored as 32- or 64-bit integers are read as those whole numbers (such as milliseconds since 1970). Other columns are left out: decimals stored as bytes (how many writers store every decimal), binary, lists, maps, structs, INT96 timestamps and further geometry columns. A notice gives how many were left out and names the first 12, each with its kind; another names the date and time columns with their unit. A row group whose text and geometry values, for the rows a read takes, decode to more than the decoded-column budget (512 MiB at least on the desktop, up to a quarter of the computer's memory and at most 3 GiB; 128 MiB in the browser) is refused with a message naming the group and the column, whatever the view or export: rewrite the file with smaller row groups. | | FlatGeobuf | `.fgb` | Add Data, or upload | Read in place by its packed R-tree. Binary columns are left out, with a notice counting them and naming the first 12. Coordinates use the header's EPSG code, else its WKT, as a GeoPackage's system does: the WKT comes first when it gives another datum transformation than the code's, or another body's system, and a grid shift it gives beside the code isn't applied, with a notice. Another organization's code (an `ESRI` one, say) or a negative code without a WKT is read as longitude/latitude, with a notice. Another body's IAU code without a WKT is read with a notice, or refused when its coordinates are projected; with a WKT, the WKT is read (see coordinate systems of other bodies, below). | | Esri File Geodatabase | `.gdb` folder (desktop) | In Add Data pick a `.gdbtable` file inside it; or double-click the `.gdb` in the Browser, or drop the folder | The native reader loads up to 512 feature classes and tables, up to 2 GiB per table. Feature classes become layers and non-spatial tables standalone tables; dates are text. Coordinates use the EPSG/Esri code, else WKT; the WKT comes first when it gives another datum transformation than an EPSG code's, or another body's system. An Esri-only code still comes first, as ArcGIS keeps transformations apart from the system, with a notice when the WKT gives another one; a grid shift the WKT gives isn't applied, with a notice. `"layer"` picks one; `info.fileLayers` lists them. Multipatches become footprints with `z_min`, `z_max` and `height`; large or wall-only ones may use a convex hull. Curves become straight segments between their ends. Unreadable tables (compressed storage, raster fields or unsupported row indexes) are tried through GDAL when installed; otherwise they are named in a notice. | | Standalone tables | CSV, or any layer without geometry | Add Data | Listed under the map in Layers; join or relate them to layers. | From aa5617ecbc5e1903c30df961efd40b90fdec0df7 Mon Sep 17 00:00:00 2001 From: Li-Sheng Chou <142213184+choupeanut@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:33:13 +0800 Subject: [PATCH 02/22] fix(data): GeoParquet decoded budget counts the rows taken and the pages read, not the column chunk (#2913) --- crates/data/src/source/parquet.rs | 271 ++++++++++++++++++++++++------ crates/data/src/source/tests.rs | 92 +++++++++- docs/user-guide/data-formats.md | 2 +- 3 files changed, 305 insertions(+), 60 deletions(-) diff --git a/crates/data/src/source/parquet.rs b/crates/data/src/source/parquet.rs index a2a014d6fe..fc971b9842 100644 --- a/crates/data/src/source/parquet.rs +++ b/crates/data/src/source/parquet.rs @@ -27,6 +27,7 @@ use rustgis_geom::Extent; use std::collections::HashSet; use std::path::Path; use std::sync::Arc; +use std::sync::atomic::Ordering; /// Values read per call. const BATCH: usize = 8192; @@ -115,8 +116,9 @@ pub struct ParquetSource { group_rows: usize, /// Decoded-column budget for an unbounded spatial scan; lowered by tests. scan_bytes: u64, - /// Decoded bytes one row group's text and geometry values may take in any read; lowered by tests. - decoded_bytes: u64, + /// Decoded bytes one row group's text and geometry values may take in any read, else + /// [`max_decoded_bytes`] as each read finds it; set by tests. + decoded_bytes: Option, /// Declared after `reader`: Windows must close its file before removing the workspace. #[cfg(not(target_arch = "wasm32"))] _workspace: Option>, @@ -386,7 +388,7 @@ impl ParquetSource { exact: false, group_rows: MAX_GROUP_ROWS, scan_bytes: MAX_SCAN_BYTES, - decoded_bytes: max_decoded_bytes(), + decoded_bytes: None, #[cfg(not(target_arch = "wasm32"))] _workspace: None, }; @@ -417,12 +419,18 @@ impl ParquetSource { } let rows = usize::try_from(md.row_group(0).num_rows()).unwrap_or(0).min(16); let rg = self.reader.get_row_group(0).ok()?; - let geoms = read_bytes(rg.as_ref(), self.geom_col, &vec![true; rows], &Budget::new(self.decoded_bytes, 0)).ok()?; + let geoms = read_bytes(rg.as_ref(), self.geom_col, &vec![true; rows], &Budget::new(self.decoded_limit(), 0)).ok()?; Some(geoms.iter().filter_map(|b| b.as_deref()).any(wkb::has_zm)) } } impl ParquetSource { + /// The decoded bytes a row group may take in the read starting now: asked once a read, as the + /// memory the process holds changes between reads ([`crate::memory::planned`]). + fn decoded_limit(&self) -> u64 { + self.decoded_bytes.unwrap_or_else(max_decoded_bytes) + } + /// A source that reads at most `rows` of a row group, for tests of the cap. #[cfg(test)] pub(crate) fn with_group_rows(mut self, rows: usize) -> Self { @@ -440,7 +448,7 @@ impl ParquetSource { /// A lower decoded-byte budget for any read, for tests without large allocations. #[cfg(test)] pub(crate) fn with_decoded_bytes(mut self, bytes: u64) -> Self { - self.decoded_bytes = bytes; + self.decoded_bytes = Some(bytes); self } @@ -591,6 +599,7 @@ impl FeatureSource for ParquetSource { /// and fields before sampling matches; a refused view therefore scans the selected file. fn read(&self, req: &Request) -> Result { self.attribute(); + let decoded = self.decoded_limit(); let limit = clamp_limit(req.limit); let md = self.reader.metadata(); let native = self.reproject.request_box(req); @@ -742,7 +751,7 @@ impl FeatureSource for ParquetSource { self.check_scan_bytes(md, g, true)?; } let rg = self.reader.get_row_group(g).map_err(err)?; - let budget = Budget::new(self.decoded_bytes, g); + let budget = Budget::new(decoded, g); let geoms = read_bytes(rg.as_ref(), self.geom_col, take, &budget)?; let attrs: Vec = self.field_cols.iter().map(|&c| read_values(rg.as_ref(), c, take, &budget)).collect::>()?; @@ -810,6 +819,7 @@ impl FeatureSource for ParquetSource { /// before the next check. An unbounded view also checks the decoded-column budget first. fn visit_chunks(&self, extent: Option, bytes: usize, visit: &mut dyn FnMut(Vec) -> Result<()>) -> Result { self.attribute(); + let decoded = self.decoded_limit(); let mut chunks = super::chunk_memory::Chunker::new(bytes, visit)?; if self.remote.is_some() { return Err(DataError::Unsupported("a whole GeoParquet by its web address read a chunk at a time".into())); @@ -860,7 +870,7 @@ impl FeatureSource for ParquetSource { continue; } let rg = self.reader.get_row_group(g).map_err(err)?; - let budget = Budget::new(self.decoded_bytes, g); + let budget = Budget::new(decoded, g); let geoms = read_bytes(rg.as_ref(), self.geom_col, &take, &budget)?; let attrs: Vec = self.field_cols.iter().map(|&c| read_values(rg.as_ref(), c, &take, &budget)).collect::>()?; @@ -1024,8 +1034,15 @@ fn err(e: parquet::errors::ParquetError) -> DataError { DataError::Format(format!("GeoParquet: {e}")) } -/// The reader of a row group's column, its pages checked by [`CheckedPages`]. +/// The reader of a row group's column, its pages checked by [`CheckedPages`] (a page no bigger +/// than the column chunk says). fn column_reader(rg: &dyn RowGroupReader, col: usize) -> Result { + Ok(column_reader_within(rg, col, u64::MAX)?.0) +} + +/// [`column_reader`] refusing any page of more than `limit` bytes too, with what it has seen of +/// the pages ([`PageNote`]). +fn column_reader_within(rg: &dyn RowGroupReader, col: usize, limit: u64) -> Result<(ColumnReader, Arc)> { let desc = rg.metadata().column(col).column_descr_ptr(); let bits = match desc.physical_type() { Physical::BOOLEAN => 1, @@ -1035,28 +1052,76 @@ fn column_reader(rg: &dyn RowGroupReader, col: usize) -> Result { Physical::FIXED_LEN_BYTE_ARRAY => u64::try_from(desc.type_length()).unwrap_or(0).max(1) * 8, }; let chunk = rg.metadata().column(col); + let note = Arc::new(PageNote::default()); let pages = CheckedPages { pages: rg.get_column_page_reader(col).map_err(err)?, bits, - chunk_bytes: u64::try_from(chunk.uncompressed_size()).unwrap_or(0), + limit, + // A footer that gives no size, or a negative one, bounds a page by the limit alone. + chunk_bytes: u64::try_from(chunk.uncompressed_size()).ok().filter(|&n| n > 0), delta_declared: chunk.encodings().any(|e| e == Encoding::DELTA_BYTE_ARRAY), + note: note.clone(), }; - Ok(parquet::column::reader::get_column_reader(desc, Box::new(pages))) + Ok((parquet::column::reader::get_column_reader(desc, Box::new(pages)), note)) +} + +/// What a column's [`CheckedPages`] have seen of its data pages, for [`Pace`]. +#[derive(Default)] +struct PageNote { + /// The bytes of the data page being read, decoded. + page: std::sync::atomic::AtomicU64, + /// The values of that page not yet read or skipped (`0`: the next read fetches a page). + in_page: std::sync::atomic::AtomicUsize, +} + +/// How many values of a column one `read_records` or `skip_records` call takes. The `parquet` +/// crate builds the values of a DELTA_BYTE_ARRAY page one by one in the call, each up to the page's +/// size, so the call takes no more than the budget left holds at that size, and none that reach +/// into a page it hasn't seen: at a page's start it takes one value, which fetches the page. +/// A column of another encoding takes [`BATCH`] values, as before. +struct Pace<'a> { + watch: Option<(&'a PageNote, &'a Budget)>, +} + +impl Pace<'_> { + /// The values of the next call, of the `left` still to read or skip (more than `0`). + fn take(&self, left: usize) -> usize { + let most = left.min(BATCH); + let Some((note, budget)) = self.watch else { return most }; + let in_page = note.in_page.load(Ordering::Relaxed); + if in_page == 0 { + return 1; + } + let page = note.page.load(Ordering::Relaxed).max(1); + let fit = usize::try_from(budget.left.get() / page).unwrap_or(BATCH); + most.min(in_page).min(fit.max(1)) + } + + /// Notes that a call read or skipped `values` of the page. + fn used(&self, values: usize) { + if let Some((note, _)) = self.watch { + note.in_page.store(note.in_page.load(Ordering::Relaxed).saturating_sub(values), Ordering::Relaxed); + } + } } /// A column's pages, a dictionary page refused when it says it holds more values than its bytes /// can: the `parquet` crate makes room for the count it is told before decoding any (a few bytes -/// of header can ask for tens of gigabytes). A page bigger than the column chunk it belongs to, and -/// a data page in the DELTA_BYTE_ARRAY encoding that the chunk doesn't list, are refused too: the -/// batch sizes of [`read_binary`] rest on both. +/// of header can ask for tens of gigabytes). A page bigger than the column chunk it belongs to or +/// than `limit`, and a data page in the DELTA_BYTE_ARRAY encoding that the chunk doesn't list, are +/// refused too: the pace of [`read_binary`] rests on both. The size is checked once the crate has +/// the page; a header asking for more than the file holds is still allocated by the crate first. struct CheckedPages { pages: Box, /// The fewest bits one value of the column takes in a dictionary page (plain encoded). bits: u64, - /// The bytes the column chunk's footer says its pages hold decoded, `0` when it says none. - chunk_bytes: u64, + /// The most bytes of one page the read allows. + limit: u64, + /// The bytes the column chunk's footer says its pages hold decoded, when it says. + chunk_bytes: Option, /// The footer lists the DELTA_BYTE_ARRAY encoding for the chunk. delta_declared: bool, + note: Arc, } impl Iterator for CheckedPages { @@ -1074,7 +1139,7 @@ impl parquet::column::page::PageReader for CheckedPages { fn get_next_page(&mut self) -> parquet::errors::Result> { let page = self.pages.get_next_page()?; if let Some(parquet::column::page::Page::DictionaryPage { buf, num_values, .. }) = &page - && u64::from(*num_values).saturating_mul(self.bits) > (buf.len() as u64).saturating_mul(8) + && u64::from(*num_values).saturating_mul(self.bits) > u64::try_from(buf.len()).unwrap_or(u64::MAX).saturating_mul(8) { return Err(parquet::errors::ParquetError::General(format!( "a dictionary page says it holds {num_values} values, more than its {} bytes can", @@ -1082,11 +1147,18 @@ impl parquet::column::page::PageReader for CheckedPages { ))); } if let Some(page) = &page { - let len = page.buffer().len() as u64; - if self.chunk_bytes > 0 && len > self.chunk_bytes { + let len = u64::try_from(page.buffer().len()).unwrap_or(u64::MAX); + if let Some(chunk) = self.chunk_bytes + && len > chunk + { + return Err(parquet::errors::ParquetError::General(format!( + "a page holds {len} bytes, more than the {chunk} its column chunk says it holds" + ))); + } + if len > self.limit { return Err(parquet::errors::ParquetError::General(format!( - "a page holds {len} bytes, more than the {} its column chunk says it holds", - self.chunk_bytes + "a page holds {len} bytes, more than the {} byte decoded-column budget", + self.limit ))); } if !self.delta_declared @@ -1097,6 +1169,12 @@ impl parquet::column::page::PageReader for CheckedPages { "a page uses the DELTA_BYTE_ARRAY encoding, which its column chunk doesn't list".into(), )); } + if let parquet::column::page::Page::DataPage { num_values, .. } | parquet::column::page::Page::DataPageV2 { num_values, .. } = + page + { + self.note.page.store(len, Ordering::Relaxed); + self.note.in_page.store(usize::try_from(*num_values).unwrap_or(usize::MAX), Ordering::Relaxed); + } } Ok(page) } @@ -1326,16 +1404,16 @@ fn field_type(c: &ColumnDescPtr) -> Option { /// rows not taken are skipped without being decoded into values, so a sample of a large row /// group doesn't hold all of it. fn read_column(r: &mut ColumnReaderImpl, take: &[bool], max_def: i16) -> Result>> { - read_column_with(r, take, max_def, &|| BATCH, &mut |_| Ok(())) + read_column_with(r, take, max_def, &Pace { watch: None }, &mut |_| Ok(())) } -/// [`read_column`] asking `batch` for the most values to read at once and `charge` about each value +/// [`read_column`] reading as `pace` says and asking `charge` about each value /// it keeps, before the caller copies any: a read that passes its budget stops there. fn read_column_with( r: &mut ColumnReaderImpl, take: &[bool], max_def: i16, - batch: &dyn Fn() -> usize, + pace: &Pace, charge: &mut dyn FnMut(&T::T) -> Result<()>, ) -> Result>> { let wanted = take.iter().filter(|&&t| t).count(); @@ -1352,18 +1430,25 @@ fn read_column_with( let mut left = j - i; i = j; if !on { - if r.skip_records(left).map_err(err)? < left { - break; + while left > 0 { + let asked = pace.take(left); + let skipped = r.skip_records(asked).map_err(err)?; + pace.used(skipped); + left = left.saturating_sub(skipped); + if skipped < asked { + return Ok(out); + } } continue; } while left > 0 { defs.clear(); values.clear(); - let (records, _, levels) = r.read_records(left.min(batch().max(1)), Some(&mut defs), None, &mut values).map_err(err)?; + let (records, _, levels) = r.read_records(pace.take(left), Some(&mut defs), None, &mut values).map_err(err)?; if records == 0 { return Ok(out); } + pace.used(records); left = left.saturating_sub(records); if max_def == 0 { for v in values.drain(..) { @@ -1566,25 +1651,21 @@ fn read_bytes(rg: &dyn RowGroupReader, col: usize, take: &[bool], budget: &Budge } /// The rows `take` marks of a BYTE_ARRAY column, charging `budget` for each value as it is read, -/// before any is copied (`None` for a column of another type). The column chunk's own bytes may not -/// pass the budget either: no honest page is bigger than its chunk, and the `parquet` crate makes -/// room for a page from its header. A column with DELTA_BYTE_ARRAY pages, whose values the -/// decoder builds one by one, reads no more values at once than the budget left holds at the most -/// a page's size each. +/// before any is copied (`None` for a column of another type). Only the rows taken count, not the +/// column chunk's size; a page of more than the budget is refused, as the `parquet` crate makes +/// room for a whole page. A column with DELTA_BYTE_ARRAY pages, whose values the decoder builds +/// one by one, is read at the [`Pace`] its page size and the budget left allow. fn read_binary(rg: &dyn RowGroupReader, col: usize, take: &[bool], budget: &Budget) -> Result>>> { let chunk = rg.metadata().column(col); if chunk.column_descr().physical_type() != Physical::BYTE_ARRAY { return Ok(None); } let name = chunk.column_path().string(); - let bytes = u64::try_from(chunk.uncompressed_size()).unwrap_or(u64::MAX); - if bytes > budget.limit { - return Err(budget.refusal(&name)); - } - let ColumnReader::ByteArrayColumnReader(mut r) = column_reader(rg, col)? else { return Ok(None) }; + let (reader, note) = column_reader_within(rg, col, budget.limit)?; + let ColumnReader::ByteArrayColumnReader(mut r) = reader else { return Ok(None) }; let delta = chunk.encodings().any(|e| e == Encoding::DELTA_BYTE_ARRAY); - let batch = || if delta { usize::try_from(budget.left.get() / bytes.max(1)).unwrap_or(BATCH).clamp(1, BATCH) } else { BATCH }; - read_column_with(&mut r, take, chunk.column_descr().max_def_level(), &batch, &mut |b: &ByteArray| budget.charge(b.len(), &name)) + let pace = Pace { watch: delta.then_some((&*note, budget)) }; + read_column_with(&mut r, take, chunk.column_descr().max_def_level(), &pace, &mut |b: &ByteArray| budget.charge(b.len(), &name)) .map(Some) } @@ -1642,13 +1723,14 @@ pub fn read_vectors(file: &Arc, extent: &Extent, column: &str, max_group return Err(remote::need()); } // The points in the extent, by row group. + let decoded = max_decoded_bytes(); let mut found: Vec<(usize, Vec<(usize, (f64, f64))>)> = Vec::new(); let mut total = 0usize; let mut hit = 0usize; for &g in &groups { let rg = reader.get_row_group(g).map_err(err)?; let rows = usize::try_from(rg.metadata().num_rows()).unwrap_or(0).min(MAX_GROUP_ROWS); - let geoms = read_bytes(rg.as_ref(), geom, &vec![true; rows], &Budget::new(max_decoded_bytes(), g))?; + let geoms = read_bytes(rg.as_ref(), geom, &vec![true; rows], &Budget::new(decoded, g))?; let inside: Vec<(usize, (f64, f64))> = geoms .iter() .enumerate() @@ -2222,26 +2304,111 @@ mod tests { } } - fn checked(page: Page, chunk_bytes: u64, delta_declared: bool) -> parquet::errors::Result> { - CheckedPages { pages: Box::new(Pages(vec![page].into_iter())), bits: 32, chunk_bytes, delta_declared }.get_next_page() + fn data_page_v2(bytes: usize, encoding: Encoding) -> Page { + Page::DataPageV2 { + buf: Bytes::from(vec![0u8; bytes]), + num_values: 1, + encoding, + num_nulls: 0, + num_rows: 1, + def_levels_byte_len: 0, + rep_levels_byte_len: 0, + is_compressed: false, + statistics: None, + } } - /// A page can't hold more than the column chunk it belongs to says it does. + /// `page` through [`CheckedPages`] of a column chunk the footer gives `chunk_bytes` for, read with `limit`. + fn checked(page: Page, chunk_bytes: Option, limit: u64, delta_declared: bool) -> parquet::errors::Result> { + CheckedPages { + pages: Box::new(Pages(vec![page].into_iter())), + bits: 32, + limit, + chunk_bytes, + delta_declared, + note: Arc::new(PageNote::default()), + } + .get_next_page() + } + + /// A page can't hold more than the column chunk it belongs to says it does, nor more than the + /// read allows; a footer without a size leaves the read's limit. #[test] - fn checked_pages_refuse_a_page_larger_than_its_chunk() { - let error = checked(data_page(11, Encoding::PLAIN), 10, false).unwrap_err().to_string(); + fn checked_pages_refuse_a_page_larger_than_its_chunk_or_the_limit() { + let error = checked(data_page(11, Encoding::PLAIN), Some(10), u64::MAX, false).unwrap_err().to_string(); assert!(error.contains("a page holds 11 bytes, more than the 10 its column chunk says it holds"), "{error}"); - assert!(checked(data_page(10, Encoding::PLAIN), 10, false).unwrap().is_some()); - // A footer that gives no size says nothing to check against. - assert!(checked(data_page(11, Encoding::PLAIN), 0, false).unwrap().is_some()); + assert!(checked(data_page(10, Encoding::PLAIN), Some(10), u64::MAX, false).unwrap().is_some()); + for chunk in [None, Some(100)] { + let error = checked(data_page(11, Encoding::PLAIN), chunk, 10, false).unwrap_err().to_string(); + assert!(error.contains("a page holds 11 bytes, more than the 10 byte decoded-column budget"), "{error}"); + assert!(checked(data_page(10, Encoding::PLAIN), chunk, 10, false).unwrap().is_some()); + } + } + + /// A footer that gives no usable size (zero or negative) is read as no size, not as a large one. + #[test] + fn checked_pages_take_the_limit_for_a_footer_without_a_size() { + let size = |n: i64| u64::try_from(n).ok().filter(|&n| n > 0); + for n in [0, -1, i64::MIN] { + assert_eq!(size(n), None, "{n}"); + assert!(checked(data_page(11, Encoding::PLAIN), size(n), 10, false).is_err(), "{n}"); + } + assert_eq!(size(7), Some(7)); } - /// A page in the one encoding that builds its values one by one must be in the chunk's list. + /// A page in the one encoding that builds its values one by one must be in the chunk's list, + /// whichever version of data page it is. #[test] fn checked_pages_refuse_an_undeclared_delta_page() { - let error = checked(data_page(4, Encoding::DELTA_BYTE_ARRAY), 10, false).unwrap_err().to_string(); - assert!(error.contains("the DELTA_BYTE_ARRAY encoding, which its column chunk doesn't list"), "{error}"); - assert!(checked(data_page(4, Encoding::DELTA_BYTE_ARRAY), 10, true).unwrap().is_some()); - assert!(checked(data_page(4, Encoding::PLAIN), 10, false).unwrap().is_some()); + for page in [data_page as fn(usize, Encoding) -> Page, data_page_v2] { + let error = checked(page(4, Encoding::DELTA_BYTE_ARRAY), Some(10), u64::MAX, false).unwrap_err().to_string(); + assert!(error.contains("the DELTA_BYTE_ARRAY encoding, which its column chunk doesn't list"), "{error}"); + assert!(checked(page(4, Encoding::DELTA_BYTE_ARRAY), Some(10), u64::MAX, true).unwrap().is_some()); + assert!(checked(page(4, Encoding::PLAIN), Some(10), u64::MAX, false).unwrap().is_some()); + } + } + + /// A data page tells the pace its size and its values. + #[test] + fn checked_pages_note_the_data_page_they_hand_over() { + for page in [data_page(40, Encoding::PLAIN), data_page_v2(40, Encoding::PLAIN)] { + let note = Arc::new(PageNote::default()); + let mut pages = CheckedPages { + pages: Box::new(Pages(vec![page].into_iter())), + bits: 32, + limit: u64::MAX, + chunk_bytes: None, + delta_declared: false, + note: note.clone(), + }; + assert!(pages.get_next_page().unwrap().is_some()); + assert_eq!((note.page.load(Ordering::Relaxed), note.in_page.load(Ordering::Relaxed)), (40, 1)); + } + } + + /// A DELTA_BYTE_ARRAY column takes one value at a page's start, then no more than its page + /// and what the budget left holds at that page's size; other columns take a batch. + #[test] + fn delta_pace_follows_the_page_and_the_budget_left() { + let note = PageNote::default(); + let budget = Budget::new(8 << 10, 0); + let pace = Pace { watch: Some((¬e, &budget)) }; + assert_eq!(pace.take(5000), 1, "a page not yet seen"); + note.in_page.store(5000, Ordering::Relaxed); + note.page.store(1024, Ordering::Relaxed); + assert_eq!(pace.take(5000), 8, "8 KiB left holds eight values of a page of 1 KiB"); + pace.used(3); + assert_eq!(note.in_page.load(Ordering::Relaxed), 4997); + note.page.store(1 << 20, Ordering::Relaxed); + assert_eq!(pace.take(5000), 1, "a page bigger than what is left still moves on"); + note.page.store(1, Ordering::Relaxed); + note.in_page.store(100, Ordering::Relaxed); + assert_eq!((pace.take(5000), pace.take(50)), (100, 50), "never past the page or the run"); + note.in_page.store(1 << 20, Ordering::Relaxed); + assert_eq!(pace.take(1 << 20), BATCH, "small values take a full batch"); + pace.used(usize::MAX); + assert_eq!(note.in_page.load(Ordering::Relaxed), 0); + assert_eq!(Pace { watch: None }.take(1 << 20), BATCH); + assert_eq!(Pace { watch: None }.take(7), 7); } } diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 7244487036..4e02dcb455 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -5233,8 +5233,8 @@ fn parquet_reads_refuse_decoded_columns_over_budget_without_a_view() { fn parquet_geometry_column_is_charged_with_the_fields() { let p = dir().join("decoded-geometry.parquet"); let mut ds = Dataset::new("pts", GeometryType::Point, vec![]); - for i in 0..20 { - ds.push(Some(Geometry::Point(Coord::new(-81.0 + f64::from(i) / 100.0, 0.0))), vec![]); + for _ in 0..20 { + ds.push(Some(Geometry::Point(Coord::new(-81.0, 0.0))), vec![]); } write_unbounded_view_fixture(&ds, &p); let whole = Request { extent: None, limit: 100, own: None }; @@ -5245,6 +5245,29 @@ fn parquet_geometry_column_is_charged_with_the_fields() { assert_eq!(source.read(&whole).unwrap().features.len(), 20); } +/// A read takes only some rows of a column chunk far bigger than the budget: it is the rows taken +/// and the size of a page that count, not the chunk's, so a view or a sample still reads (#2913). +#[test] +fn parquet_sampled_read_of_a_chunk_over_the_budget_succeeds() { + let p = dir().join("decoded-sampled.parquet"); + let mut ds = Dataset::new("pts", GeometryType::Point, vec![Field::new("label", FieldType::Text)]); + for i in 0..20 { + ds.push(Some(Geometry::Point(Coord::new(-81.0, 0.0))), vec![Value::Text(format!("{}{i:02}", "x".repeat(1024)))]); + } + // Plain text of 20 KiB in pages of about 2 KiB, read with a budget of 8 KiB. + write_encoded_parquet_fixture(&ds, &p, 100, false, FixturePages { page_bytes: Some(2 << 10), ..FixturePages::default() }); + let source = parquet::ParquetSource::open_path(&p, "pts").unwrap().with_decoded_bytes(8 << 10); + let bounded = Extent::new(-84.0, -1.0, -78.0, 1.0); + let one = Request { extent: Some(bounded), limit: 1, own: None }; + assert_eq!(source.read(&one).unwrap().features.len(), 1); + let none = Request { extent: None, limit: 1, own: None }; + assert_eq!(source.read(&none).unwrap().features.len(), 1); + // Taking every row still stops at the budget. + let all = Request { extent: Some(bounded), limit: 100, own: None }; + let error = source.read(&all).unwrap_err().to_string(); + assert!(error.contains("decoded-column budget"), "{error}"); +} + /// A DELTA_BYTE_ARRAY column builds each value in the decoder, so its reads take fewer values at a /// time as the budget gets smaller, and still read every row, or stop at the budget (#2913). #[test] @@ -5254,7 +5277,7 @@ fn parquet_delta_byte_array_reads_within_the_decoded_budget() { for i in 0..20 { ds.push(Some(Geometry::Point(Coord::new(-81.0, 0.0))), vec![Value::Text(format!("{}{i:02}", "x".repeat(1024)))]); } - write_encoded_parquet_fixture(&ds, &p, 100, false, true); + write_encoded_parquet_fixture(&ds, &p, 100, false, FixturePages { delta: true, ..FixturePages::default() }); let footer = ::parquet::file::reader::SerializedFileReader::new(std::fs::File::open(&p).unwrap()).unwrap(); let encodings: Vec<_> = ::parquet::file::reader::FileReader::metadata(&footer) .row_group(0) @@ -5275,6 +5298,43 @@ fn parquet_delta_byte_array_reads_within_the_decoded_budget() { assert!(error.contains("decoded-column budget"), "{error}"); } +/// Data pages of version 2 read as version 1 do, with and without a budget that stops them. +#[test] +fn parquet_version_two_pages_read_within_the_decoded_budget() { + let p = dir().join("decoded-v2.parquet"); + let mut ds = Dataset::new("pts", GeometryType::Point, vec![Field::new("label", FieldType::Text)]); + for i in 0..20 { + ds.push(Some(Geometry::Point(Coord::new(-81.0, 0.0))), vec![Value::Text(format!("{}{i:02}", "x".repeat(1024)))]); + } + let whole = Request { extent: None, limit: 100, own: None }; + for delta in [false, true] { + let pages = FixturePages { delta, v2: true, page_bytes: Some(2 << 10) }; + write_encoded_parquet_fixture(&ds, &p, 100, false, pages); + let source = parquet::ParquetSource::open_path(&p, "pts").unwrap(); + let batch = source.read(&whole).unwrap(); + assert_eq!(batch.features.len(), 20, "delta {delta}"); + assert_eq!(batch.features[19].attrs[0], Value::Text(format!("{}19", "x".repeat(1024))), "delta {delta}"); + let source = parquet::ParquetSource::open_path(&p, "pts").unwrap().with_decoded_bytes(8 << 10); + let error = source.read(&whole).unwrap_err().to_string(); + assert!(error.contains("decoded-column budget"), "delta {delta}: {error}"); + } +} + +/// A page of more than the budget is refused, whatever the rows taken. +#[test] +fn parquet_page_over_the_budget_is_refused() { + let p = dir().join("decoded-page.parquet"); + let mut ds = Dataset::new("pts", GeometryType::Point, vec![Field::new("label", FieldType::Text)]); + for i in 0..20 { + ds.push(Some(Geometry::Point(Coord::new(-81.0, 0.0))), vec![Value::Text(format!("{}{i:02}", "x".repeat(1024)))]); + } + write_encoded_parquet_fixture(&ds, &p, 100, false, FixturePages { page_bytes: Some(2 << 10), ..FixturePages::default() }); + let source = parquet::ParquetSource::open_path(&p, "pts").unwrap().with_decoded_bytes(1 << 10); + let one = Request { extent: None, limit: 1, own: None }; + let error = source.read(&one).unwrap_err().to_string(); + assert!(error.contains("decoded-column budget"), "{error}"); +} + /// The same small file must remain readable with plain or dictionary-encoded binary columns. #[test] fn unbounded_parquet_scan_accepts_two_thousand_distinct_points() { @@ -5365,11 +5425,22 @@ fn write_unbounded_view_fixture(ds: &Dataset, path: &Path) { /// A UTM fixture with selectable row-group size and binary encoding, using the same covering. fn write_projected_parquet_fixture(ds: &Dataset, path: &Path, rows: usize, dictionary: bool) { - write_encoded_parquet_fixture(ds, path, rows, dictionary, false); + write_encoded_parquet_fixture(ds, path, rows, dictionary, FixturePages::default()); } -/// [`write_projected_parquet_fixture`], its text fields in the DELTA_BYTE_ARRAY encoding when `delta`. -fn write_encoded_parquet_fixture(ds: &Dataset, path: &Path, rows: usize, dictionary: bool, delta: bool) { +/// How [`write_encoded_parquet_fixture`] writes the text fields' pages. +#[derive(Clone, Copy, Default)] +struct FixturePages { + /// The DELTA_BYTE_ARRAY encoding. + delta: bool, + /// Data pages of version 2. + v2: bool, + /// About this many bytes to a data page. + page_bytes: Option, +} + +/// [`write_projected_parquet_fixture`] with the text fields' pages as `pages` says. +fn write_encoded_parquet_fixture(ds: &Dataset, path: &Path, rows: usize, dictionary: bool, pages: FixturePages) { let crs = Crs::from_epsg(32617).unwrap(); use arrow_array::{BinaryArray, Float64Array, RecordBatch, StringArray, StructArray}; use arrow_schema::{DataType, Field as AField, Schema}; @@ -5412,11 +5483,18 @@ fn write_encoded_parquet_fixture(ds: &Dataset, path: &Path, rows: usize, diction .set_max_row_group_row_count(Some(rows)) .set_dictionary_enabled(dictionary) .set_key_value_metadata(Some(vec![::parquet::file::metadata::KeyValue::new("geo".into(), geo.to_string())])); - if delta { + if pages.delta { for field in ds.fields.iter().filter(|f| f.ty == FieldType::Text) { props = props.set_column_encoding(field.name.as_str().into(), ::parquet::basic::Encoding::DELTA_BYTE_ARRAY); } } + if pages.v2 { + props = props.set_writer_version(::parquet::file::properties::WriterVersion::PARQUET_2_0); + } + if let Some(bytes) = pages.page_bytes { + // Pages close after each value, so one holds about `bytes`. + props = props.set_write_batch_size(1).set_data_page_size_limit(bytes); + } let props = props.build(); let mut writer = ::parquet::arrow::ArrowWriter::try_new(std::fs::File::create(path).unwrap(), schema, Some(props)).unwrap(); writer.write(&batch).unwrap(); diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index a85f72c921..0023175e04 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -39,7 +39,7 @@ export names its feature. | Geotagged photos | `.jpg`, `.jpeg` | Add Data (several at once in the web app), drop them, upload, or `layer.addPhotos` with `"paths"` or a `"folder"` | JPEGs with a GPS position in their EXIF become points in the **Photos** layer (photos added one at a time join it): each with its `name`, `file`, `time` (when it was taken), `altitude`, `direction` (where the camera faced), `camera` and a `thumbnail` of at most 160 pixels, kept with the feature so the project needs no other file. Identify shows the thumbnail. Photos without a position are named in a notice and left out; a layer holds up to 2,000 photos. A JPEG is always read as a photo unless `layer.addData` or `layer.addDataBytes` is given `"as": "scan"` (a phone photo of a paper map, say: see [Scans with no coordinates](#rasters)). | | LiDAR point clouds | `.las`, `.laz` (COPC too) | Add Data, drop the file, upload, or From URL… | LAS 1.0–1.4 (point formats 0–10) and LAZ, on desktop and web: points with `z`, `intensity`, `classification`, `return` and colour (`red`, `green`, `blue`), coloured by ASPRS class or elevation. An evenly spread sample is read once, at most 2 million points (500,000 in the web app); views use that sample, not the COPC spatial index. LAZ decompression reads at most the first 400 million points (40 million on the web), with a notice when capped. Held in the system of the file's WKT or GeoTIFF-key record, as the file holds its points; without one, coordinates are kept as longitude/latitude, with a notice when they aren't. Points with no place in longitude/latitude are kept and counted ([below](#places-with-no-longitudelatitude)); points with a coordinate that isn't a number are left out and counted. A local project keeps the path; uploads keep the file bytes. Remote files download whole. | | GeoPackage | `.gpkg` | Add Data, or upload in the web app | Local files and browser uploads add every feature table, up to 32 (with the rest counted in `skippedCount` and up to 100 named in `skipped`); `"layer"` picks one, and `info.fileLayers` lists them. Desktop byte uploads and downloads add the first table unless `"layer"` names another. Large local tables use their R-tree. Rows with no geometry (NULL or empty) are kept, with their attributes, in whole reads and exports; a read of an extent leaves them out, as they have no location. A table is read in its coordinate system: by its EPSG code, or, for a system without one (or with a code RustGIS doesn't know), by the WKT definition the file gives it (the WKT2 of GeoPackage 1.2's `definition_12_063` first, as the specification says, else `definition`). The definition also comes before the code when it gives another datum transformation than the code's, or describes another body's system. This holds on the desktop and in the web app alike (an azimuthal equidistant system opens on the desktop only, and the web app says so). Browser tables are scanned, testing each geometry header's envelope first; UTF-16 databases aren't read there. Raster tile tables aren't imported. `DATE` and `DATETIME` columns are read as dates and date-times (ISO 8601 text, as GeoPackage stores them); a value that isn't one is empty and counted in a notice. | -| GeoParquet | `.parquet`, `.geoparquet` | Add Data, or upload in the web app | WKB geometry, with the CRS from the file's `geo` metadata. A binary geometry column is required; plain non-spatial Parquet tables and GeoArrow-native geometry encodings aren't read by this importer. Row groups are pruned by the bbox covering. Whole reads and exports retain rows with null geometry and their attributes; extent-filtered reads exclude them because they have no location. Snappy, gzip, LZ4 and zstd compression are read, in the browser too; Brotli isn't. Text, whole-number, floating-point and true/false columns become fields, as do decimals stored as 32- or 64-bit integers (up to 18 digits), read as floating-point numbers. Dates and times stored as 32- or 64-bit integers are read as those whole numbers (such as milliseconds since 1970). Other columns are left out: decimals stored as bytes (how many writers store every decimal), binary, lists, maps, structs, INT96 timestamps and further geometry columns. A notice gives how many were left out and names the first 12, each with its kind; another names the date and time columns with their unit. A row group whose text and geometry values, for the rows a read takes, decode to more than the decoded-column budget (512 MiB at least on the desktop, up to a quarter of the computer's memory and at most 3 GiB; 128 MiB in the browser) is refused with a message naming the group and the column, whatever the view or export: rewrite the file with smaller row groups. | +| GeoParquet | `.parquet`, `.geoparquet` | Add Data, or upload in the web app | WKB geometry, with the CRS from the file's `geo` metadata. A binary geometry column is required; plain non-spatial Parquet tables and GeoArrow-native geometry encodings aren't read by this importer. Row groups are pruned by the bbox covering. Whole reads and exports retain rows with null geometry and their attributes; extent-filtered reads exclude them because they have no location. Snappy, gzip, LZ4 and zstd compression are read, in the browser too; Brotli isn't. Text, whole-number, floating-point and true/false columns become fields, as do decimals stored as 32- or 64-bit integers (up to 18 digits), read as floating-point numbers. Dates and times stored as 32- or 64-bit integers are read as those whole numbers (such as milliseconds since 1970). Other columns are left out: decimals stored as bytes (how many writers store every decimal), binary, lists, maps, structs, INT96 timestamps and further geometry columns. A notice gives how many were left out and names the first 12, each with its kind; another names the date and time columns with their unit. A row group whose text and geometry values, for the rows a read takes, decode to more than the decoded-column budget (512 MiB at least on the desktop, up to a quarter of the computer's memory and at most 3 GiB; 128 MiB in the browser) is refused with a message naming the group and the column: rewrite the file with smaller row groups. Only the rows a read takes count, so a view or a sample of such a file still reads; a page of more than the budget is refused too. | | FlatGeobuf | `.fgb` | Add Data, or upload | Read in place by its packed R-tree. Binary columns are left out, with a notice counting them and naming the first 12. Coordinates use the header's EPSG code, else its WKT, as a GeoPackage's system does: the WKT comes first when it gives another datum transformation than the code's, or another body's system, and a grid shift it gives beside the code isn't applied, with a notice. Another organization's code (an `ESRI` one, say) or a negative code without a WKT is read as longitude/latitude, with a notice. Another body's IAU code without a WKT is read with a notice, or refused when its coordinates are projected; with a WKT, the WKT is read (see coordinate systems of other bodies, below). | | Esri File Geodatabase | `.gdb` folder (desktop) | In Add Data pick a `.gdbtable` file inside it; or double-click the `.gdb` in the Browser, or drop the folder | The native reader loads up to 512 feature classes and tables, up to 2 GiB per table. Feature classes become layers and non-spatial tables standalone tables; dates are text. Coordinates use the EPSG/Esri code, else WKT; the WKT comes first when it gives another datum transformation than an EPSG code's, or another body's system. An Esri-only code still comes first, as ArcGIS keeps transformations apart from the system, with a notice when the WKT gives another one; a grid shift the WKT gives isn't applied, with a notice. `"layer"` picks one; `info.fileLayers` lists them. Multipatches become footprints with `z_min`, `z_max` and `height`; large or wall-only ones may use a convex hull. Curves become straight segments between their ends. Unreadable tables (compressed storage, raster fields or unsupported row indexes) are tried through GDAL when installed; otherwise they are named in a notice. | | Standalone tables | CSV, or any layer without geometry | Add Data | Listed under the map in Layers; join or relate them to layers. | From bfe364464351798f03c8e5575f4d20a39f5c4622 Mon Sep 17 00:00:00 2001 From: Li-Sheng Chou <142213184+choupeanut@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:47:08 +0800 Subject: [PATCH 03/22] fix(data): GeoParquet reads skip a run of untaken rows in one call, so whole pages stay undecoded (#2913) --- crates/data/src/source/parquet.rs | 54 ++++++++++++++++++++++++------- crates/data/src/source/tests.rs | 18 +++++++++++ 2 files changed, 61 insertions(+), 11 deletions(-) diff --git a/crates/data/src/source/parquet.rs b/crates/data/src/source/parquet.rs index fc971b9842..c889b1fedc 100644 --- a/crates/data/src/source/parquet.rs +++ b/crates/data/src/source/parquet.rs @@ -425,8 +425,9 @@ impl ParquetSource { } impl ParquetSource { - /// The decoded bytes a row group may take in the read starting now: asked once a read, as the - /// memory the process holds changes between reads ([`crate::memory::planned`]). + /// The decoded bytes a row group may take in the read starting now: asked once a read, when it + /// first reads a row group (a read that reads none never asks), as the memory the process holds + /// changes between reads ([`crate::memory::planned`]). fn decoded_limit(&self) -> u64 { self.decoded_bytes.unwrap_or_else(max_decoded_bytes) } @@ -599,7 +600,7 @@ impl FeatureSource for ParquetSource { /// and fields before sampling matches; a refused view therefore scans the selected file. fn read(&self, req: &Request) -> Result { self.attribute(); - let decoded = self.decoded_limit(); + let decoded = std::cell::LazyCell::new(|| self.decoded_limit()); let limit = clamp_limit(req.limit); let md = self.reader.metadata(); let native = self.reproject.request_box(req); @@ -751,7 +752,7 @@ impl FeatureSource for ParquetSource { self.check_scan_bytes(md, g, true)?; } let rg = self.reader.get_row_group(g).map_err(err)?; - let budget = Budget::new(decoded, g); + let budget = Budget::new(*decoded, g); let geoms = read_bytes(rg.as_ref(), self.geom_col, take, &budget)?; let attrs: Vec = self.field_cols.iter().map(|&c| read_values(rg.as_ref(), c, take, &budget)).collect::>()?; @@ -819,7 +820,7 @@ impl FeatureSource for ParquetSource { /// before the next check. An unbounded view also checks the decoded-column budget first. fn visit_chunks(&self, extent: Option, bytes: usize, visit: &mut dyn FnMut(Vec) -> Result<()>) -> Result { self.attribute(); - let decoded = self.decoded_limit(); + let decoded = std::cell::LazyCell::new(|| self.decoded_limit()); let mut chunks = super::chunk_memory::Chunker::new(bytes, visit)?; if self.remote.is_some() { return Err(DataError::Unsupported("a whole GeoParquet by its web address read a chunk at a time".into())); @@ -870,7 +871,7 @@ impl FeatureSource for ParquetSource { continue; } let rg = self.reader.get_row_group(g).map_err(err)?; - let budget = Budget::new(decoded, g); + let budget = Budget::new(*decoded, g); let geoms = read_bytes(rg.as_ref(), self.geom_col, &take, &budget)?; let attrs: Vec = self.field_cols.iter().map(|&c| read_values(rg.as_ref(), c, &take, &budget)).collect::>()?; @@ -1077,8 +1078,10 @@ struct PageNote { /// How many values of a column one `read_records` or `skip_records` call takes. The `parquet` /// crate builds the values of a DELTA_BYTE_ARRAY page one by one in the call, each up to the page's /// size, so the call takes no more than the budget left holds at that size, and none that reach -/// into a page it hasn't seen: at a page's start it takes one value, which fetches the page. -/// A column of another encoding takes [`BATCH`] values, as before. +/// into a page it hasn't seen: at a page's start it takes one value, which fetches the page. That +/// makes the crate decode each page of such a column, where a skip of the whole page would have +/// passed over it undecoded; a column of another encoding keeps that, as its skips take the whole +/// run, and its reads take [`BATCH`] values, as before. struct Pace<'a> { watch: Option<(&'a PageNote, &'a Budget)>, } @@ -1097,6 +1100,12 @@ impl Pace<'_> { most.min(in_page).min(fit.max(1)) } + /// The values of the next `skip_records` call, of the `left` still to skip (more than `0`): the + /// whole run unless the column is paced, so the crate can pass over whole pages undecoded. + fn skip(&self, left: usize) -> usize { + if self.watch.is_none() { left } else { self.take(left) } + } + /// Notes that a call read or skipped `values` of the page. fn used(&self, values: usize) { if let Some((note, _)) = self.watch { @@ -1407,6 +1416,24 @@ fn read_column(r: &mut ColumnReaderImpl, take: &[bool], max_def: i read_column_with(r, take, max_def, &Pace { watch: None }, &mut |_| Ok(())) } +/// Forgets the longest skip this thread has made, for tests. +#[cfg(test)] +pub(crate) fn reset_largest_skip() { + LARGEST_SKIP.with(|largest| largest.set(0)); +} + +/// The most values one `skip_records` call was asked to skip on this thread, for tests. +#[cfg(test)] +pub(crate) fn largest_skip() -> usize { + LARGEST_SKIP.with(std::cell::Cell::get) +} + +#[cfg(test)] +thread_local! { + /// The most values one `skip_records` call was asked to skip on this thread, for tests. + static LARGEST_SKIP: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// [`read_column`] reading as `pace` says and asking `charge` about each value /// it keeps, before the caller copies any: a read that passes its budget stops there. fn read_column_with( @@ -1431,7 +1458,9 @@ fn read_column_with( i = j; if !on { while left > 0 { - let asked = pace.take(left); + let asked = pace.skip(left); + #[cfg(test)] + LARGEST_SKIP.with(|largest| largest.set(largest.get().max(asked))); let skipped = r.skip_records(asked).map_err(err)?; pace.used(skipped); left = left.saturating_sub(skipped); @@ -1723,14 +1752,14 @@ pub fn read_vectors(file: &Arc, extent: &Extent, column: &str, max_group return Err(remote::need()); } // The points in the extent, by row group. - let decoded = max_decoded_bytes(); + let decoded = std::cell::LazyCell::new(max_decoded_bytes); let mut found: Vec<(usize, Vec<(usize, (f64, f64))>)> = Vec::new(); let mut total = 0usize; let mut hit = 0usize; for &g in &groups { let rg = reader.get_row_group(g).map_err(err)?; let rows = usize::try_from(rg.metadata().num_rows()).unwrap_or(0).min(MAX_GROUP_ROWS); - let geoms = read_bytes(rg.as_ref(), geom, &vec![true; rows], &Budget::new(decoded, g))?; + let geoms = read_bytes(rg.as_ref(), geom, &vec![true; rows], &Budget::new(*decoded, g))?; let inside: Vec<(usize, (f64, f64))> = geoms .iter() .enumerate() @@ -2410,5 +2439,8 @@ mod tests { assert_eq!(note.in_page.load(Ordering::Relaxed), 0); assert_eq!(Pace { watch: None }.take(1 << 20), BATCH); assert_eq!(Pace { watch: None }.take(7), 7); + assert_eq!(Pace { watch: None }.skip(1 << 20), 1 << 20, "a skip of another encoding is one call"); + note.in_page.store(0, Ordering::Relaxed); + assert_eq!(pace.skip(1 << 20), 1, "a delta column's skip starts a page with one value"); } } diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 4e02dcb455..64fb2a120f 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -5298,6 +5298,24 @@ fn parquet_delta_byte_array_reads_within_the_decoded_budget() { assert!(error.contains("decoded-column budget"), "{error}"); } +/// A column that isn't delta encoded skips a run of rows it doesn't take in one call, so the +/// `parquet` crate can pass over whole pages without decoding them (#2913). +#[test] +fn parquet_sampled_read_skips_a_long_run_in_one_call() { + let p = dir().join("sampled-skip.parquet"); + let mut ds = Dataset::new("pts", GeometryType::Point, vec![]); + for i in 0..30_000 { + ds.push(Some(Geometry::Point(Coord::new(-82.0 + f64::from(i) / 30_000.0, 0.0))), vec![]); + } + write_projected_parquet_fixture(&ds, &p, 30_000, false); + let source = parquet::ParquetSource::open_path(&p, "pts").unwrap(); + parquet::reset_largest_skip(); + let one = Request { extent: None, limit: 1, own: None }; + assert_eq!(source.read(&one).unwrap().features.len(), 1); + // Most of the 30,000 rows aren't taken: one run of well over a batch of 8,192. + assert!(parquet::largest_skip() > 8192, "{}", parquet::largest_skip()); +} + /// Data pages of version 2 read as version 1 do, with and without a budget that stops them. #[test] fn parquet_version_two_pages_read_within_the_decoded_budget() { From ffd843b77749c4943168e1e55a584e438bb3944d Mon Sep 17 00:00:00 2001 From: Li-Sheng Chou <142213184+choupeanut@users.noreply.github.com> Date: Fri, 27 Nov 2026 19:49:05 +0800 Subject: [PATCH 04/22] data: test that invalid UTF-8 text is charged at its converted length (#2913) --- crates/data/src/source/tests.rs | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 64fb2a120f..c216926f97 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -5338,6 +5338,38 @@ fn parquet_version_two_pages_read_within_the_decoded_budget() { } } +/// Text that is invalid UTF-8 grows when it is made a `String` (each bad sequence becomes the +/// three bytes of U+FFFD), so the budget counts the converted length, not the stored one (#2913). +#[test] +fn parquet_invalid_text_is_charged_at_its_converted_length() { + use ::parquet::data_type::{ByteArray, ByteArrayType}; + use ::parquet::file::writer::SerializedFileWriter; + let schema = + ::parquet::schema::parser::parse_message_type("message m { REQUIRED BINARY geometry; OPTIONAL BINARY label (STRING); }").unwrap(); + let mut bytes = Vec::new(); + let mut w = SerializedFileWriter::new(&mut bytes, Arc::new(schema), Arc::default()).unwrap(); + let mut rg = w.next_row_group().unwrap(); + let geom = ByteArray::from(wkb::encode(&Geometry::Point(Coord::new(0.0, 0.0)))); + let mut col = rg.next_column().unwrap().unwrap(); + col.typed::().write_batch(&vec![geom; 20], None, None).unwrap(); + col.close().unwrap(); + // 20 values of 256 bytes that are not UTF-8: 5,120 stored, 15,360 once each byte is U+FFFD. + let bad = ByteArray::from(vec![0xffu8; 256]); + let mut col = rg.next_column().unwrap().unwrap(); + col.typed::().write_batch(&vec![bad; 20], Some(&[1; 20]), None).unwrap(); + col.close().unwrap(); + rg.close().unwrap(); + w.close().unwrap(); + let whole = Request { extent: None, limit: 100, own: None }; + let source = parquet::ParquetSource::open_bytes(bytes.clone(), "m").unwrap().with_decoded_bytes(8 << 10); + let error = source.read(&whole).unwrap_err().to_string(); + assert!(error.contains("decoded-column budget") && error.contains("label"), "{error}"); + let source = parquet::ParquetSource::open_bytes(bytes, "m").unwrap().with_decoded_bytes(32 << 10); + let batch = source.read(&whole).unwrap(); + assert_eq!(batch.features.len(), 20); + assert_eq!(batch.features[0].attrs[0], Value::Text("\u{fffd}".repeat(256))); +} + /// A page of more than the budget is refused, whatever the rows taken. #[test] fn parquet_page_over_the_budget_is_refused() { From 342cfb506b9c3ac51c68cfa34f25ed5d9b17eae2 Mon Sep 17 00:00:00 2001 From: Li-Sheng Chou <142213184+choupeanut@users.noreply.github.com> Date: Fri, 27 Nov 2026 19:56:09 +0800 Subject: [PATCH 05/22] data: GeoParquet text is charged at the length it has as a String (#2913) --- crates/data/src/source/parquet.rs | 34 ++++++++++++++++++++++++++----- 1 file changed, 29 insertions(+), 5 deletions(-) diff --git a/crates/data/src/source/parquet.rs b/crates/data/src/source/parquet.rs index c889b1fedc..72d86c40e9 100644 --- a/crates/data/src/source/parquet.rs +++ b/crates/data/src/source/parquet.rs @@ -1601,7 +1601,7 @@ fn read_values(rg: &dyn RowGroupReader, col: usize, take: &[bool], budget: &Budg (Some(i), None) => Value::Int(i), } }; - let values = if let Some(binary) = read_binary(rg, col, take, budget)? { + let values = if let Some(binary) = read_binary(rg, col, take, budget, text_len)? { binary.into_iter().map(|v| v.map(|b| Value::Text(String::from_utf8_lossy(b.data()).into_owned())).unwrap_or_default()).collect() } else { match column_reader(rg, col)? { @@ -1673,18 +1673,32 @@ fn binary_dictionary_max(bytes: &[u8], count: u32) -> Result { /// Reads a binary column (the WKB geometry), for the rows `take` marks, in order, within `budget`. fn read_bytes(rg: &dyn RowGroupReader, col: usize, take: &[bool], budget: &Budget) -> Result>>> { - match read_binary(rg, col, take, budget)? { + match read_binary(rg, col, take, budget, <[u8]>::len)? { Some(values) => Ok(values.into_iter().map(|v| v.map(|b| b.data().to_vec())).collect()), None => Err(DataError::Format("GeoParquet: the geometry column is not binary".into())), } } +/// The bytes `bytes` takes as a `String` made by [`String::from_utf8_lossy`], counted without +/// building it: valid text keeps its length, and each invalid sequence becomes the 3 bytes of +/// U+FFFD, which can be more than it held. +fn text_len(bytes: &[u8]) -> usize { + bytes.utf8_chunks().map(|c| c.valid().len() + if c.invalid().is_empty() { 0 } else { 3 }).sum() +} + /// The rows `take` marks of a BYTE_ARRAY column, charging `budget` for each value as it is read, -/// before any is copied (`None` for a column of another type). Only the rows taken count, not the +/// as `size` counts what the caller makes of its bytes, before any is copied (`None` for a column +/// of another type). Only the rows taken count, not the /// column chunk's size; a page of more than the budget is refused, as the `parquet` crate makes /// room for a whole page. A column with DELTA_BYTE_ARRAY pages, whose values the decoder builds /// one by one, is read at the [`Pace`] its page size and the budget left allow. -fn read_binary(rg: &dyn RowGroupReader, col: usize, take: &[bool], budget: &Budget) -> Result>>> { +fn read_binary( + rg: &dyn RowGroupReader, + col: usize, + take: &[bool], + budget: &Budget, + size: fn(&[u8]) -> usize, +) -> Result>>> { let chunk = rg.metadata().column(col); if chunk.column_descr().physical_type() != Physical::BYTE_ARRAY { return Ok(None); @@ -1694,7 +1708,7 @@ fn read_binary(rg: &dyn RowGroupReader, col: usize, take: &[bool], budget: &Budg let ColumnReader::ByteArrayColumnReader(mut r) = reader else { return Ok(None) }; let delta = chunk.encodings().any(|e| e == Encoding::DELTA_BYTE_ARRAY); let pace = Pace { watch: delta.then_some((&*note, budget)) }; - read_column_with(&mut r, take, chunk.column_descr().max_def_level(), &pace, &mut |b: &ByteArray| budget.charge(b.len(), &name)) + read_column_with(&mut r, take, chunk.column_descr().max_def_level(), &pace, &mut |b: &ByteArray| budget.charge(size(b.data()), &name)) .map(Some) } @@ -2415,6 +2429,16 @@ mod tests { } } + /// The length of text as `from_utf8_lossy` makes it, for any bytes. + #[test] + fn text_len_is_the_length_of_the_lossy_string() { + for bytes in + [&b""[..], b"abc", "h\u{e9}llo \u{4e2d}".as_bytes(), b"\xff", b"a\xffb\xfe\xfec", b"\xe2\x82", b"ok\xe2\x82", b"\xf0\x9f\x98"] + { + assert_eq!(text_len(bytes), String::from_utf8_lossy(bytes).len(), "{bytes:?}"); + } + } + /// A DELTA_BYTE_ARRAY column takes one value at a page's start, then no more than its page /// and what the budget left holds at that page's size; other columns take a batch. #[test] From 5cb1d9a478f15e1eb1b42cc141e99bf65739b698 Mon Sep 17 00:00:00 2001 From: Li-Sheng Chou <142213184+choupeanut@users.noreply.github.com> Date: Fri, 27 Nov 2026 19:58:58 +0800 Subject: [PATCH 06/22] data: test that the non-delta version 2 text pages are plain (#2913) --- crates/data/src/source/tests.rs | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index c216926f97..4d85f7c64c 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -5278,14 +5278,7 @@ fn parquet_delta_byte_array_reads_within_the_decoded_budget() { ds.push(Some(Geometry::Point(Coord::new(-81.0, 0.0))), vec![Value::Text(format!("{}{i:02}", "x".repeat(1024)))]); } write_encoded_parquet_fixture(&ds, &p, 100, false, FixturePages { delta: true, ..FixturePages::default() }); - let footer = ::parquet::file::reader::SerializedFileReader::new(std::fs::File::open(&p).unwrap()).unwrap(); - let encodings: Vec<_> = ::parquet::file::reader::FileReader::metadata(&footer) - .row_group(0) - .columns() - .iter() - .filter(|c| c.column_path().string() == "label") - .flat_map(|c| c.encodings()) - .collect(); + let encodings = text_encodings(&p, "label"); assert!(encodings.contains(&::parquet::basic::Encoding::DELTA_BYTE_ARRAY), "{encodings:?}"); let whole = Request { extent: None, limit: 100, own: None }; // 20 values of 1,026 bytes: a budget of 32 KiB reads them all, a smaller one stops. @@ -5298,6 +5291,18 @@ fn parquet_delta_byte_array_reads_within_the_decoded_budget() { assert!(error.contains("decoded-column budget"), "{error}"); } +/// The encodings the footer lists for the column chunks of the field `name`. +fn text_encodings(path: &Path, name: &str) -> Vec<::parquet::basic::Encoding> { + let footer = ::parquet::file::reader::SerializedFileReader::new(std::fs::File::open(path).unwrap()).unwrap(); + ::parquet::file::reader::FileReader::metadata(&footer) + .row_group(0) + .columns() + .iter() + .filter(|c| c.column_path().string() == name) + .flat_map(|c| c.encodings()) + .collect() +} + /// A column that isn't delta encoded skips a run of rows it doesn't take in one call, so the /// `parquet` crate can pass over whole pages without decoding them (#2913). #[test] @@ -5328,6 +5333,10 @@ fn parquet_version_two_pages_read_within_the_decoded_budget() { for delta in [false, true] { let pages = FixturePages { delta, v2: true, page_bytes: Some(2 << 10) }; write_encoded_parquet_fixture(&ds, &p, 100, false, pages); + // The writer's own choice for version 2 text is DELTA_BYTE_ARRAY, so each case says its own. + let encodings = text_encodings(&p, "label"); + assert_eq!(encodings.contains(&::parquet::basic::Encoding::DELTA_BYTE_ARRAY), delta, "{encodings:?}"); + assert_eq!(encodings.contains(&::parquet::basic::Encoding::PLAIN), !delta, "{encodings:?}"); let source = parquet::ParquetSource::open_path(&p, "pts").unwrap(); let batch = source.read(&whole).unwrap(); assert_eq!(batch.features.len(), 20, "delta {delta}"); From fce01a52f1b9d12dbf36fbc92e93cc8769d41823 Mon Sep 17 00:00:00 2001 From: Li-Sheng Chou <142213184+choupeanut@users.noreply.github.com> Date: Fri, 27 Nov 2026 20:01:37 +0800 Subject: [PATCH 07/22] data: the fixture writes plain text pages when it is not asked for delta (#2913) --- crates/data/src/source/tests.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 4d85f7c64c..056f8a266f 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -5542,10 +5542,10 @@ fn write_encoded_parquet_fixture(ds: &Dataset, path: &Path, rows: usize, diction .set_max_row_group_row_count(Some(rows)) .set_dictionary_enabled(dictionary) .set_key_value_metadata(Some(vec![::parquet::file::metadata::KeyValue::new("geo".into(), geo.to_string())])); - if pages.delta { - for field in ds.fields.iter().filter(|f| f.ty == FieldType::Text) { - props = props.set_column_encoding(field.name.as_str().into(), ::parquet::basic::Encoding::DELTA_BYTE_ARRAY); - } + // Left alone, version 2 writes text as DELTA_BYTE_ARRAY, so the plain case says so. + let encoding = if pages.delta { ::parquet::basic::Encoding::DELTA_BYTE_ARRAY } else { ::parquet::basic::Encoding::PLAIN }; + for field in ds.fields.iter().filter(|f| f.ty == FieldType::Text) { + props = props.set_column_encoding(field.name.as_str().into(), encoding); } if pages.v2 { props = props.set_writer_version(::parquet::file::properties::WriterVersion::PARQUET_2_0); From b44abb042a5e540bcefaa73a06dfd0a2b4c71b68 Mon Sep 17 00:00:00 2001 From: Li-Sheng Chou <142213184+choupeanut@users.noreply.github.com> Date: Fri, 27 Nov 2026 20:12:19 +0800 Subject: [PATCH 08/22] data: test that a sampled delta read skips pages it takes no row of without fetching them (#2913) --- crates/data/src/source/parquet.rs | 19 ++++++++++++++++++ crates/data/src/source/tests.rs | 32 +++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/crates/data/src/source/parquet.rs b/crates/data/src/source/parquet.rs index 72d86c40e9..bf7e22ecde 100644 --- a/crates/data/src/source/parquet.rs +++ b/crates/data/src/source/parquet.rs @@ -1181,6 +1181,10 @@ impl parquet::column::page::PageReader for CheckedPages { if let parquet::column::page::Page::DataPage { num_values, .. } | parquet::column::page::Page::DataPageV2 { num_values, .. } = page { + #[cfg(test)] + if self.delta_declared { + DELTA_PAGES.with(|pages| pages.set(pages.get() + 1)); + } self.note.page.store(len, Ordering::Relaxed); self.note.in_page.store(usize::try_from(*num_values).unwrap_or(usize::MAX), Ordering::Relaxed); } @@ -1432,6 +1436,21 @@ pub(crate) fn largest_skip() -> usize { thread_local! { /// The most values one `skip_records` call was asked to skip on this thread, for tests. static LARGEST_SKIP: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// The DELTA_BYTE_ARRAY data pages the crate fetched (and so set a decoder up for) on this + /// thread, for tests. + static DELTA_PAGES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Forgets the delta pages this thread has fetched, for tests. +#[cfg(test)] +pub(crate) fn reset_delta_pages() { + DELTA_PAGES.with(|pages| pages.set(0)); +} + +/// The DELTA_BYTE_ARRAY data pages the crate fetched on this thread, for tests. +#[cfg(test)] +pub(crate) fn delta_pages() -> usize { + DELTA_PAGES.with(std::cell::Cell::get) } /// [`read_column`] reading as `pace` says and asking `charge` about each value diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 056f8a266f..94256911a1 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -5321,6 +5321,38 @@ fn parquet_sampled_read_skips_a_long_run_in_one_call() { assert!(parquet::largest_skip() > 8192, "{}", parquet::largest_skip()); } +/// A sampled read of a DELTA_BYTE_ARRAY column passes over the pages it takes no row of without +/// fetching them, as it does a column of another encoding, so the crate sets no decoder up for a +/// page it only skips (its decoder sizes arrays from a count in the page) (#2913). +#[test] +fn parquet_sampled_delta_read_does_not_fetch_the_pages_it_skips() { + let p = dir().join("decoded-delta-skip.parquet"); + let mut ds = Dataset::new("pts", GeometryType::Point, vec![Field::new("label", FieldType::Text)]); + for i in 0..20 { + ds.push( + Some(Geometry::Point(Coord::new(-81.0 + f64::from(i) * 0.01, 0.0))), + vec![Value::Text(format!("{i:02}{}", "x".repeat(1024)))], + ); + } + for v2 in [false, true] { + let pages = FixturePages { delta: true, v2, page_bytes: Some(2 << 10), ..FixturePages::default() }; + write_encoded_parquet_fixture(&ds, &p, 100, false, pages); + let source = parquet::ParquetSource::open_path(&p, "pts").unwrap(); + // Values that start differently share no prefix, so pages of 2 KiB hold about two each. + let everything = Request { extent: None, limit: 100, own: None }; + parquet::reset_delta_pages(); + assert_eq!(source.read(&everything).unwrap().features.len(), 20, "v2 {v2}"); + assert!(parquet::delta_pages() >= 5, "v2 {v2}: {} pages", parquet::delta_pages()); + // Only the last point is in the extent: the rows before it, in pages of two or so, are skipped. + let last = Request { extent: Some(Extent::new(-80.815, -1.0, -80.805, 1.0)), limit: 100, own: None }; + parquet::reset_delta_pages(); + let batch = source.read(&last).unwrap(); + assert_eq!(batch.features.len(), 1, "v2 {v2}"); + assert_eq!(batch.features[0].attrs[0], Value::Text(format!("19{}", "x".repeat(1024))), "v2 {v2}"); + assert_eq!(parquet::delta_pages(), 1, "v2 {v2}: only the page holding the row is fetched"); + } +} + /// Data pages of version 2 read as version 1 do, with and without a budget that stops them. #[test] fn parquet_version_two_pages_read_within_the_decoded_budget() { From ccdd5876e543720bf84128d5af58646dfd3f84b2 Mon Sep 17 00:00:00 2001 From: Li-Sheng Chou <142213184+choupeanut@users.noreply.github.com> Date: Fri, 27 Nov 2026 20:29:18 +0800 Subject: [PATCH 09/22] data: a sampled delta read passes over whole pages it takes no row of without fetching them (#2913) --- crates/data/src/source/parquet.rs | 161 +++++++++++++++++++++++++++--- crates/data/src/source/tests.rs | 6 +- 2 files changed, 151 insertions(+), 16 deletions(-) diff --git a/crates/data/src/source/parquet.rs b/crates/data/src/source/parquet.rs index bf7e22ecde..5fe2a75471 100644 --- a/crates/data/src/source/parquet.rs +++ b/crates/data/src/source/parquet.rs @@ -1067,21 +1067,47 @@ fn column_reader_within(rg: &dyn RowGroupReader, col: usize, limit: u64) -> Resu } /// What a column's [`CheckedPages`] have seen of its data pages, for [`Pace`]. -#[derive(Default)] struct PageNote { /// The bytes of the data page being read, decoded. page: std::sync::atomic::AtomicU64, /// The values of that page not yet read or skipped (`0`: the next read fetches a page). in_page: std::sync::atomic::AtomicUsize, + /// While a `skip_records` call may pass over whole pages undecoded: the values of the run it is + /// asked for that are still to skip ([`NOT_SKIPPING`] outside such a call). + skip_left: std::sync::atomic::AtomicUsize, + /// The values of the whole pages that call has passed over. + passed: std::sync::atomic::AtomicUsize, + /// The values of the data page last peeked at in such a call. + peeked: std::sync::atomic::AtomicUsize, + /// Such a call was stopped at a page it would only have skipped part of. + stopped: std::sync::atomic::AtomicBool, +} + +/// [`PageNote::skip_left`] when no skip is passing over whole pages. +const NOT_SKIPPING: usize = usize::MAX; + +impl Default for PageNote { + fn default() -> Self { + Self { + page: Default::default(), + in_page: Default::default(), + skip_left: std::sync::atomic::AtomicUsize::new(NOT_SKIPPING), + passed: Default::default(), + peeked: Default::default(), + stopped: Default::default(), + } + } } /// How many values of a column one `read_records` or `skip_records` call takes. The `parquet` /// crate builds the values of a DELTA_BYTE_ARRAY page one by one in the call, each up to the page's -/// size, so the call takes no more than the budget left holds at that size, and none that reach -/// into a page it hasn't seen: at a page's start it takes one value, which fetches the page. That -/// makes the crate decode each page of such a column, where a skip of the whole page would have -/// passed over it undecoded; a column of another encoding keeps that, as its skips take the whole -/// run, and its reads take [`BATCH`] values, as before. +/// size, so a call that reads or skips into a page takes no more than the budget left holds at +/// that size, and none that reach past the page; at a page it hasn't seen it takes one value, which +/// fetches the page. A skip that starts at such a page is asked for its whole run instead, so the +/// crate passes over the pages the run covers undecoded (fetching one sets its decoder up, and the +/// decoder sizes arrays from a count the page holds), and [`CheckedPages`] stops it at a page it +/// would only skip part of, which the one-value pace then takes. A column of another encoding +/// skips its whole runs, and its reads take [`BATCH`] values, as before. struct Pace<'a> { watch: Option<(&'a PageNote, &'a Budget)>, } @@ -1101,9 +1127,28 @@ impl Pace<'_> { } /// The values of the next `skip_records` call, of the `left` still to skip (more than `0`): the - /// whole run unless the column is paced, so the crate can pass over whole pages undecoded. + /// whole run unless the column is paced and the call is inside a page, or follows a stop at one. fn skip(&self, left: usize) -> usize { - if self.watch.is_none() { left } else { self.take(left) } + let Some((note, _)) = self.watch else { return left }; + if note.in_page.load(Ordering::Relaxed) > 0 || note.stopped.swap(false, Ordering::Relaxed) { + return self.take(left); + } + note.passed.store(0, Ordering::Relaxed); + note.skip_left.store(left, Ordering::Relaxed); + left + } + + /// Ends a skip call that [`skip`](Self::skip) asked for, which `result` is the outcome of: the + /// values it skipped, whether it was stopped at a page it would only have skipped part of (the + /// whole pages before that count). + fn skipped(&self, result: parquet::errors::Result) -> Result<(usize, bool)> { + let Some((note, _)) = self.watch else { return result.map(|n| (n, false)).map_err(err) }; + note.skip_left.store(NOT_SKIPPING, Ordering::Relaxed); + match result { + Ok(n) => Ok((n, false)), + Err(_) if note.stopped.load(Ordering::Relaxed) => Ok((note.passed.load(Ordering::Relaxed), true)), + Err(e) => Err(err(e)), + } } /// Notes that a call read or skipped `values` of the page. @@ -1192,14 +1237,34 @@ impl parquet::column::page::PageReader for CheckedPages { Ok(page) } - /// The next page's header, unchecked: a peek decodes no values. + /// The next page's header, unchecked: a peek decodes no values. While a skip is passing over + /// whole pages, a data page the skip would only pass over part of is refused (the skip would + /// set its decoder up first): [`Pace`] takes that page at its own pace. fn peek_next_page(&mut self) -> parquet::errors::Result> { - self.pages.peek_next_page() + let meta = self.pages.peek_next_page()?; + let left = self.note.skip_left.load(Ordering::Relaxed); + if left != NOT_SKIPPING + && let Some(meta) = &meta + { + let rows = if meta.is_dict { Some(0) } else { meta.num_rows.or(meta.num_levels) }; + if rows.is_none_or(|rows| rows > left) { + self.note.stopped.store(true, Ordering::Relaxed); + return Err(parquet::errors::ParquetError::General("a skip stops at a page it would only partly pass over".into())); + } + self.note.peeked.store(rows.unwrap_or(0), Ordering::Relaxed); + } + Ok(meta) } /// Skips the next page unchecked: a skipped page is never decoded. fn skip_next_page(&mut self) -> parquet::errors::Result<()> { - self.pages.skip_next_page() + self.pages.skip_next_page()?; + if self.note.skip_left.load(Ordering::Relaxed) != NOT_SKIPPING { + let rows = self.note.peeked.swap(0, Ordering::Relaxed); + self.note.skip_left.store(self.note.skip_left.load(Ordering::Relaxed).saturating_sub(rows), Ordering::Relaxed); + self.note.passed.store(self.note.passed.load(Ordering::Relaxed).saturating_add(rows), Ordering::Relaxed); + } + Ok(()) } /// Whether the next page starts a record, as the column's own pages say. @@ -1480,10 +1545,10 @@ fn read_column_with( let asked = pace.skip(left); #[cfg(test)] LARGEST_SKIP.with(|largest| largest.set(largest.get().max(asked))); - let skipped = r.skip_records(asked).map_err(err)?; + let (skipped, stopped) = pace.skipped(r.skip_records(asked))?; pace.used(skipped); left = left.saturating_sub(skipped); - if skipped < asked { + if skipped < asked && !stopped { return Ok(out); } } @@ -2458,6 +2523,71 @@ mod tests { } } + /// Headers handed out one by one, as a file's pages would be peeked at and skipped. + struct Headers(Vec); + + impl Iterator for Headers { + type Item = parquet::errors::Result; + fn next(&mut self) -> Option { + None + } + } + + impl PageReader for Headers { + fn get_next_page(&mut self) -> parquet::errors::Result> { + Ok(None) + } + fn peek_next_page(&mut self) -> parquet::errors::Result> { + Ok(self.0.first().cloned()) + } + fn skip_next_page(&mut self) -> parquet::errors::Result<()> { + self.0.remove(0); + Ok(()) + } + fn at_record_boundary(&mut self) -> parquet::errors::Result { + Ok(true) + } + } + + /// A skip passes over the whole pages its run covers, and is stopped (an error, with the values + /// it passed over noted) at a data page it would only skip part of, whose decoder it would set up. + #[test] + fn checked_pages_stop_a_skip_at_a_page_it_would_only_partly_pass_over() { + let page = |rows| PageMetadata { num_rows: Some(rows), num_levels: Some(rows), is_dict: false }; + let dictionary = PageMetadata { num_rows: None, num_levels: None, is_dict: true }; + let note = Arc::new(PageNote::default()); + let mut pages = CheckedPages { + pages: Box::new(Headers(vec![dictionary, page(4), page(4), page(4)])), + bits: 32, + limit: u64::MAX, + chunk_bytes: None, + delta_declared: true, + note: note.clone(), + }; + let budget = Budget::new(1 << 20, 0); + let pace = Pace { watch: Some((¬e, &budget)) }; + // Not skipping: a peek is a peek. + assert!(pages.peek_next_page().unwrap().is_some_and(|m| m.is_dict)); + assert_eq!(pace.skip(10), 10, "a run from a page's start is asked for whole"); + assert!(pages.peek_next_page().unwrap().is_some_and(|m| m.is_dict), "a dictionary page is left to the crate"); + pages.skip_next_page().unwrap(); + for _ in 0..2 { + assert_eq!(pages.peek_next_page().unwrap().and_then(|m| m.num_rows), Some(4)); + pages.skip_next_page().unwrap(); + } + // 2 values of the run are left, the next page holds 4: the skip stops there. + assert!(pages.peek_next_page().is_err()); + let (skipped, stopped) = pace.skipped(Err(parquet::errors::ParquetError::General("stop".into()))).unwrap(); + assert_eq!((skipped, stopped), (8, true)); + assert_eq!(note.skip_left.load(Ordering::Relaxed), NOT_SKIPPING); + assert_eq!(pages.peek_next_page().unwrap().and_then(|m| m.num_rows), Some(4), "nothing was fetched"); + assert_eq!(pace.skip(2), 1, "the page is then taken a value at a time"); + // Another error is the caller's. + assert_eq!(pace.skip(3), 3); + assert!(pace.skipped(Err(parquet::errors::ParquetError::General("other".into()))).is_err()); + assert_eq!(pace.skipped(Ok(3)).unwrap(), (3, false)); + } + /// A DELTA_BYTE_ARRAY column takes one value at a page's start, then no more than its page /// and what the budget left holds at that page's size; other columns take a batch. #[test] @@ -2483,7 +2613,10 @@ mod tests { assert_eq!(Pace { watch: None }.take(1 << 20), BATCH); assert_eq!(Pace { watch: None }.take(7), 7); assert_eq!(Pace { watch: None }.skip(1 << 20), 1 << 20, "a skip of another encoding is one call"); + note.in_page.store(100, Ordering::Relaxed); + assert_eq!(pace.skip(1 << 20), 100, "a skip inside a page takes no more than the page's rest"); note.in_page.store(0, Ordering::Relaxed); - assert_eq!(pace.skip(1 << 20), 1, "a delta column's skip starts a page with one value"); + assert_eq!(pace.skip(1 << 20), 1 << 20, "a delta column's skip starts a page with its whole run"); + assert_eq!(note.skip_left.load(Ordering::Relaxed), 1 << 20, "so the pages it covers pass undecoded"); } } diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 94256911a1..58b49fc1ba 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -5335,7 +5335,7 @@ fn parquet_sampled_delta_read_does_not_fetch_the_pages_it_skips() { ); } for v2 in [false, true] { - let pages = FixturePages { delta: true, v2, page_bytes: Some(2 << 10), ..FixturePages::default() }; + let pages = FixturePages { delta: true, v2, page_bytes: Some(2 << 10) }; write_encoded_parquet_fixture(&ds, &p, 100, false, pages); let source = parquet::ParquetSource::open_path(&p, "pts").unwrap(); // Values that start differently share no prefix, so pages of 2 KiB hold about two each. @@ -5349,7 +5349,9 @@ fn parquet_sampled_delta_read_does_not_fetch_the_pages_it_skips() { let batch = source.read(&last).unwrap(); assert_eq!(batch.features.len(), 1, "v2 {v2}"); assert_eq!(batch.features[0].attrs[0], Value::Text(format!("19{}", "x".repeat(1024))), "v2 {v2}"); - assert_eq!(parquet::delta_pages(), 1, "v2 {v2}: only the page holding the row is fetched"); + // The page holding the row, and for version 2 the one of the geometry column, which is delta + // encoded too: no page before them. + assert_eq!(parquet::delta_pages(), 1 + usize::from(v2), "v2 {v2}: only the pages holding the row are fetched"); } } From 1b92920943c90a15f00c00af34f311f93bccef70 Mon Sep 17 00:00:00 2001 From: Li-Sheng Chou <142213184+choupeanut@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:50:32 +0800 Subject: [PATCH 10/22] data: tests for delta pages with an unholdable count and a page refusal that names its column (#2913) --- crates/data/src/source/parquet.rs | 100 ++++++++++++++++++++++++++++++ crates/data/src/source/tests.rs | 2 + 2 files changed, 102 insertions(+) diff --git a/crates/data/src/source/parquet.rs b/crates/data/src/source/parquet.rs index 5fe2a75471..6a7d17447e 100644 --- a/crates/data/src/source/parquet.rs +++ b/crates/data/src/source/parquet.rs @@ -2523,6 +2523,106 @@ mod tests { } } + /// A DELTA_BINARY_PACKED stream of `count` values, with `blocks` blocks of 128 values in 4 + /// miniblocks, all of bit width 0 (a run of equal values). + fn delta_stream(count: u32, first: u8, blocks: usize) -> Vec { + let mut out = vec![0x80, 0x01, 0x04]; + let mut n = count; + loop { + let low = (n & 0x7f) as u8; + n >>= 7; + if n == 0 { + out.push(low); + break; + } + out.push(low | 0x80); + } + out.push(first); + for _ in 0..blocks { + // min delta 0, then four miniblock widths of 0. + out.extend_from_slice(&[0, 0, 0, 0, 0]); + } + out + } + + fn delta_page(levels: usize, values: Vec, num_values: u32, encoding: Encoding, v2: bool) -> Page { + let mut buf = vec![0xAAu8; levels]; + buf.extend(values); + let buf = Bytes::from(buf); + if v2 { + Page::DataPageV2 { + buf, + num_values, + encoding, + num_nulls: 0, + num_rows: num_values, + def_levels_byte_len: u32::try_from(levels).unwrap_or(0), + rep_levels_byte_len: 0, + is_compressed: false, + statistics: None, + } + } else { + Page::DataPage { + buf, + num_values, + encoding, + def_level_encoding: Encoding::RLE, + rep_level_encoding: Encoding::RLE, + statistics: None, + } + } + } + + /// A delta page whose count is more than its values, or more than its bytes can hold, or whose + /// header is cut off or malformed, is refused before the crate's decoder sizes an array from the + /// count (a few bytes can say two billion values), and a sound one is handed over. + #[test] + fn checked_pages_refuse_a_delta_page_with_a_count_its_bytes_cannot_hold() { + let huge = delta_stream(i32::MAX as u32, 0, 0); + let mut sound = delta_stream(3, 0, 1); + sound.extend(delta_stream(3, 4, 1)); + sound.extend_from_slice(b"ababab"); + for v2 in [false, true] { + // The two streams of DELTA_BYTE_ARRAY (levels first, in version 2 and in version 1 of a required column: none). + for levels in [0, 2] { + if !v2 && levels > 0 { + continue; + } + let page = |values: Vec, n: u32, e| delta_page(levels, values, n, e, v2); + let refused = |values: Vec, n: u32, e| checked(page(values, n, e), None, 1 << 30, true).unwrap_err().to_string(); + let delta = Encoding::DELTA_BYTE_ARRAY; + let lengths = Encoding::DELTA_LENGTH_BYTE_ARRAY; + let error = refused(huge.clone(), 3, delta); + assert!(error.contains("more than the page's 3 values"), "v2 {v2} {levels}: {error}"); + let error = refused(huge.clone(), 3, lengths); + assert!(error.contains("more than the page's 3 values"), "v2 {v2} {levels}: {error}"); + // A count the page's own value count allows, but its few bytes can't hold. + let error = refused(delta_stream(1000, 0, 1), 1000, delta); + assert!(error.contains("bytes can't hold"), "v2 {v2} {levels}: {error}"); + // The decoder's array of that count, more than the budget allows. + let error = checked(page(delta_stream(1 << 20, 0, 1), 1 << 20, delta), None, 1 << 10, true).unwrap_err().to_string(); + assert!(error.contains("decoded-column budget"), "v2 {v2} {levels}: {error}"); + // Cut off in its header, a miniblock width or its data, or not a header at all. + for cut in [0, 1, 2, 4, 6, 7] { + let error = refused(delta_stream(3, 0, 1)[..cut].to_vec(), 3, delta); + assert!(error.contains("delta"), "v2 {v2} {levels} cut {cut}: {error}"); + } + let error = refused(vec![0x80; 12], 3, delta); + assert!(error.contains("delta"), "v2 {v2} {levels}: {error}"); + let error = refused(vec![0x81, 0x01, 0x04, 0x03, 0x00], 3, delta); + assert!(error.contains("delta"), "a block size that is not a multiple of 128: {error}"); + // The second stream's count must be the first's. + let mut odd = delta_stream(3, 0, 1); + odd.extend(delta_stream(2, 4, 1)); + let error = refused(odd, 3, delta); + assert!(error.contains("delta"), "v2 {v2} {levels}: {error}"); + // Sound pages go through. + assert!(checked(page(sound.clone(), 3, delta), None, 1 << 30, true).unwrap().is_some(), "v2 {v2} {levels}"); + assert!(checked(page(delta_stream(3, 4, 1), 3, lengths), None, 1 << 30, true).unwrap().is_some(), "v2 {v2} {levels}"); + } + } + } + /// Headers handed out one by one, as a file's pages would be peeked at and skipped. struct Headers(Vec); diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 58b49fc1ba..f65fafcaef 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -5426,6 +5426,8 @@ fn parquet_page_over_the_budget_is_refused() { let one = Request { extent: None, limit: 1, own: None }; let error = source.read(&one).unwrap_err().to_string(); assert!(error.contains("decoded-column budget"), "{error}"); + // A page's refusal names the row group and the column, as the budget's does. + assert!(error.contains("row group 0") && error.contains("column 'label'"), "{error}"); } /// The same small file must remain readable with plain or dictionary-encoded binary columns. From 23a1f0c01f55fa5cd173e8e24147e420bd183d65 Mon Sep 17 00:00:00 2001 From: Li-Sheng Chou <142213184+choupeanut@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:04:18 +0800 Subject: [PATCH 11/22] data: delta pages are checked for a count their bytes can hold, and page refusals name the row group and column (#2913) --- crates/data/src/source/parquet.rs | 184 +++++++++++++++++++++++++++--- crates/data/src/source/tests.rs | 23 ++++ 2 files changed, 192 insertions(+), 15 deletions(-) diff --git a/crates/data/src/source/parquet.rs b/crates/data/src/source/parquet.rs index 6a7d17447e..a56f7689ef 100644 --- a/crates/data/src/source/parquet.rs +++ b/crates/data/src/source/parquet.rs @@ -1035,6 +1035,11 @@ fn err(e: parquet::errors::ParquetError) -> DataError { DataError::Format(format!("GeoParquet: {e}")) } +/// [`err`] for an error met in `place` (a row group and column, or `""` when not known). +fn err_in(place: &str, e: parquet::errors::ParquetError) -> DataError { + if place.is_empty() { err(e) } else { DataError::Format(format!("GeoParquet: {place}: {e}")) } +} + /// The reader of a row group's column, its pages checked by [`CheckedPages`] (a page no bigger /// than the column chunk says). fn column_reader(rg: &dyn RowGroupReader, col: usize) -> Result { @@ -1061,6 +1066,8 @@ fn column_reader_within(rg: &dyn RowGroupReader, col: usize, limit: u64) -> Resu // A footer that gives no size, or a negative one, bounds a page by the limit alone. chunk_bytes: u64::try_from(chunk.uncompressed_size()).ok().filter(|&n| n > 0), delta_declared: chunk.encodings().any(|e| e == Encoding::DELTA_BYTE_ARRAY), + max_def: desc.max_def_level(), + max_rep: desc.max_rep_level(), note: note.clone(), }; Ok((parquet::column::reader::get_column_reader(desc, Box::new(pages)), note)) @@ -1141,13 +1148,13 @@ impl Pace<'_> { /// Ends a skip call that [`skip`](Self::skip) asked for, which `result` is the outcome of: the /// values it skipped, whether it was stopped at a page it would only have skipped part of (the /// whole pages before that count). - fn skipped(&self, result: parquet::errors::Result) -> Result<(usize, bool)> { - let Some((note, _)) = self.watch else { return result.map(|n| (n, false)).map_err(err) }; + fn skipped(&self, place: &str, result: parquet::errors::Result) -> Result<(usize, bool)> { + let Some((note, _)) = self.watch else { return result.map(|n| (n, false)).map_err(|e| err_in(place, e)) }; note.skip_left.store(NOT_SKIPPING, Ordering::Relaxed); match result { Ok(n) => Ok((n, false)), Err(_) if note.stopped.load(Ordering::Relaxed) => Ok((note.passed.load(Ordering::Relaxed), true)), - Err(e) => Err(err(e)), + Err(e) => Err(err_in(place, e)), } } @@ -1175,6 +1182,9 @@ struct CheckedPages { chunk_bytes: Option, /// The footer lists the DELTA_BYTE_ARRAY encoding for the chunk. delta_declared: bool, + /// The most levels the column's values have, for a version 1 page's level streams. + max_def: i16, + max_rep: i16, note: Arc, } @@ -1188,6 +1198,135 @@ impl Iterator for CheckedPages { } } +impl CheckedPages { + /// Refuses a DELTA_BYTE_ARRAY or DELTA_LENGTH_BYTE_ARRAY data page whose streams say they hold + /// more values than the page does or its bytes can, or can't be read: the crate's decoders make + /// an array of that count (4 bytes a value) before decoding a value, and a few bytes can ask for + /// gigabytes. See [`delta_stream`] for what is checked. + fn check_delta(&self, page: &parquet::column::page::Page) -> parquet::errors::Result<()> { + use parquet::column::page::Page; + let (buf, num_values, encoding, levels) = match page { + Page::DataPage { buf, num_values, encoding, def_level_encoding, rep_level_encoding, .. } => { + let mut at = 0usize; + for (max, level_encoding) in [(self.max_rep, rep_level_encoding), (self.max_def, def_level_encoding)] { + if max > 0 { + if *level_encoding != Encoding::RLE { + return Err(delta_err("its levels are not RLE, so where its values start can't be told")); + } + let len = buf + .get(at..at.saturating_add(4)) + .and_then(|b| <[u8; 4]>::try_from(b).ok()) + .map(u32::from_le_bytes) + .and_then(|n| usize::try_from(n).ok()) + .ok_or_else(|| delta_err("its levels are cut off"))?; + at = at.saturating_add(4).saturating_add(len); + } + } + (buf, *num_values, *encoding, at) + } + Page::DataPageV2 { buf, num_values, encoding, def_levels_byte_len, rep_levels_byte_len, .. } => { + let at = (*def_levels_byte_len as usize).saturating_add(*rep_levels_byte_len as usize); + (buf, *num_values, *encoding, at) + } + Page::DictionaryPage { .. } => return Ok(()), + }; + if !matches!(encoding, Encoding::DELTA_BYTE_ARRAY | Encoding::DELTA_LENGTH_BYTE_ARRAY) { + return Ok(()); + } + let values = buf.get(levels..).ok_or_else(|| delta_err("its levels are longer than the page"))?; + let max = u64::from(num_values); + let (count, end) = delta_stream(values, max, self.limit)?; + if encoding == Encoding::DELTA_BYTE_ARRAY { + // The prefix lengths are followed by the suffixes, a DELTA_LENGTH_BYTE_ARRAY stream of as many. + let rest = values.get(end..).ok_or_else(|| delta_err("its prefix lengths run past the page"))?; + let (suffixes, _) = delta_stream(rest, max, self.limit)?; + if suffixes != count { + return Err(delta_err(&format!("it has {count} prefix lengths and {suffixes} suffixes"))); + } + } + Ok(()) + } +} + +fn delta_err(what: &str) -> parquet::errors::ParquetError { + parquet::errors::ParquetError::General(format!("a delta page is refused: {what}")) +} + +/// One ULEB128 number at `at` of `data`, moving `at` past it (`None` when it is cut off or longer +/// than the 10 bytes the crate reads: it stops with a panic at an 11th). +fn uleb(data: &[u8], at: &mut usize) -> Option { + let mut value = 0u64; + for i in 0..10u32 { + let byte = *data.get(*at)?; + *at += 1; + value |= u64::from(byte & 0x7f).checked_shl(7 * i)?; + if byte & 0x80 == 0 { + return Some(value); + } + } + None +} + +/// Reads the layout of the DELTA_BINARY_PACKED stream at the start of `data` as the crate's +/// `DeltaBitPackDecoder` does, without decoding a value: its header (block size, miniblocks per +/// block, the count of values, the first value), then each block's minimum delta and miniblock bit +/// widths, to where the stream ends. It returns the count and the end offset. The stream is refused +/// when the count is more than `max_values` (the page's value count) or more than `limit` bytes +/// make as 4-byte lengths (what the decoder allocates), when the blocks it needs don't fit in +/// `data`, or when anything is cut off or the sizes aren't the multiples the format needs. The +/// crate's decoders trust all of that when they size their arrays, and panic on some of it. +fn delta_stream(data: &[u8], max_values: u64, limit: u64) -> parquet::errors::Result<(u64, usize)> { + let mut at = 0usize; + let cut = || delta_err("a stream header is cut off or malformed"); + let block = uleb(data, &mut at).ok_or_else(cut)?; + let mini_blocks = uleb(data, &mut at).ok_or_else(cut)?; + let count = uleb(data, &mut at).ok_or_else(cut)?; + uleb(data, &mut at).ok_or_else(cut)?; + if block == 0 + || !block.is_multiple_of(128) + || mini_blocks == 0 + || !block.is_multiple_of(mini_blocks) + || !(block / mini_blocks).is_multiple_of(32) + { + return Err(delta_err(&format!("its block of {block} values in {mini_blocks} miniblocks is not one the format allows"))); + } + if count > max_values { + return Err(delta_err(&format!("a stream says it holds {count} values, more than the page's {max_values} values"))); + } + if count.saturating_mul(4) > limit { + return Err(parquet::errors::ParquetError::General(format!( + "a delta page's stream says it holds {count} values, whose lengths are more than the {limit} byte decoded-column budget" + ))); + } + let per_mini = block / mini_blocks; + let widths = usize::try_from(mini_blocks).map_err(|_| cut())?; + let mut left = count.saturating_sub(1); + while left > 0 { + uleb(data, &mut at) + .ok_or_else(|| delta_err(&format!("its {count} values need more blocks than its {} bytes can hold", data.len())))?; + let end = at.checked_add(widths).ok_or_else(cut)?; + let bits = data + .get(at..end) + .ok_or_else(|| delta_err(&format!("its {count} values need more blocks than its {} bytes can hold", data.len())))?; + at = end; + let mut packed = 0u64; + for &width in bits { + // Miniblocks past the last value have their widths taken as 0, as the crate does. + let width = if left == 0 { 0 } else { u64::from(width) }; + if width > 32 { + return Err(delta_err(&format!("a miniblock has a bit width of {width}, more than 32"))); + } + left = left.saturating_sub(per_mini); + packed = packed.saturating_add(width.saturating_mul(per_mini) / 8); + } + at = usize::try_from(packed).ok().and_then(|n| at.checked_add(n)).ok_or_else(cut)?; + if at > data.len() { + return Err(delta_err(&format!("its {count} values need more bytes than the page's {} bytes can hold", data.len()))); + } + } + Ok((count, at)) +} + impl parquet::column::page::PageReader for CheckedPages { /// The next page, or an error for a dictionary page whose count its bytes can't hold. fn get_next_page(&mut self) -> parquet::errors::Result> { @@ -1223,6 +1362,7 @@ impl parquet::column::page::PageReader for CheckedPages { "a page uses the DELTA_BYTE_ARRAY encoding, which its column chunk doesn't list".into(), )); } + self.check_delta(page)?; if let parquet::column::page::Page::DataPage { num_values, .. } | parquet::column::page::Page::DataPageV2 { num_values, .. } = page { @@ -1482,7 +1622,7 @@ fn field_type(c: &ColumnDescPtr) -> Option { /// rows not taken are skipped without being decoded into values, so a sample of a large row /// group doesn't hold all of it. fn read_column(r: &mut ColumnReaderImpl, take: &[bool], max_def: i16) -> Result>> { - read_column_with(r, take, max_def, &Pace { watch: None }, &mut |_| Ok(())) + read_column_with(r, take, max_def, &Pace { watch: None }, "", &mut |_| Ok(())) } /// Forgets the longest skip this thread has made, for tests. @@ -1518,13 +1658,14 @@ pub(crate) fn delta_pages() -> usize { DELTA_PAGES.with(std::cell::Cell::get) } -/// [`read_column`] reading as `pace` says and asking `charge` about each value +/// [`read_column`] reading as `pace` says (an error naming `place`) and asking `charge` about each value /// it keeps, before the caller copies any: a read that passes its budget stops there. fn read_column_with( r: &mut ColumnReaderImpl, take: &[bool], max_def: i16, pace: &Pace, + place: &str, charge: &mut dyn FnMut(&T::T) -> Result<()>, ) -> Result>> { let wanted = take.iter().filter(|&&t| t).count(); @@ -1545,7 +1686,7 @@ fn read_column_with( let asked = pace.skip(left); #[cfg(test)] LARGEST_SKIP.with(|largest| largest.set(largest.get().max(asked))); - let (skipped, stopped) = pace.skipped(r.skip_records(asked))?; + let (skipped, stopped) = pace.skipped(place, r.skip_records(asked))?; pace.used(skipped); left = left.saturating_sub(skipped); if skipped < asked && !stopped { @@ -1557,7 +1698,7 @@ fn read_column_with( while left > 0 { defs.clear(); values.clear(); - let (records, _, levels) = r.read_records(pace.take(left), Some(&mut defs), None, &mut values).map_err(err)?; + let (records, _, levels) = r.read_records(pace.take(left), Some(&mut defs), None, &mut values).map_err(|e| err_in(place, e))?; if records == 0 { return Ok(out); } @@ -1792,8 +1933,11 @@ fn read_binary( let ColumnReader::ByteArrayColumnReader(mut r) = reader else { return Ok(None) }; let delta = chunk.encodings().any(|e| e == Encoding::DELTA_BYTE_ARRAY); let pace = Pace { watch: delta.then_some((&*note, budget)) }; - read_column_with(&mut r, take, chunk.column_descr().max_def_level(), &pace, &mut |b: &ByteArray| budget.charge(size(b.data()), &name)) - .map(Some) + let place = format!("row group {}, column '{name}'", budget.group); + read_column_with(&mut r, take, chunk.column_descr().max_def_level(), &pace, &place, &mut |b: &ByteArray| { + budget.charge(size(b.data()), &name) + }) + .map(Some) } /// Reads every one of `n` rows of a float or double column as doubles (the covering). @@ -2453,6 +2597,8 @@ mod tests { limit, chunk_bytes, delta_declared, + max_def: 0, + max_rep: 0, note: Arc::new(PageNote::default()), } .get_next_page() @@ -2487,10 +2633,14 @@ mod tests { /// whichever version of data page it is. #[test] fn checked_pages_refuse_an_undeclared_delta_page() { - for page in [data_page as fn(usize, Encoding) -> Page, data_page_v2] { + let mut sound = delta_stream(3, 0, 1); + sound.extend(delta_stream(3, 4, 1)); + sound.extend_from_slice(b"ababab"); + for (v2, page) in [(false, data_page as fn(usize, Encoding) -> Page), (true, data_page_v2)] { let error = checked(page(4, Encoding::DELTA_BYTE_ARRAY), Some(10), u64::MAX, false).unwrap_err().to_string(); assert!(error.contains("the DELTA_BYTE_ARRAY encoding, which its column chunk doesn't list"), "{error}"); - assert!(checked(page(4, Encoding::DELTA_BYTE_ARRAY), Some(10), u64::MAX, true).unwrap().is_some()); + let declared = delta_page(0, sound.clone(), 3, Encoding::DELTA_BYTE_ARRAY, v2); + assert!(checked(declared, Some(100), u64::MAX, true).unwrap().is_some()); assert!(checked(page(4, Encoding::PLAIN), Some(10), u64::MAX, false).unwrap().is_some()); } } @@ -2506,6 +2656,8 @@ mod tests { limit: u64::MAX, chunk_bytes: None, delta_declared: false, + max_def: 0, + max_rep: 0, note: note.clone(), }; assert!(pages.get_next_page().unwrap().is_some()); @@ -2598,7 +2750,7 @@ mod tests { assert!(error.contains("more than the page's 3 values"), "v2 {v2} {levels}: {error}"); // A count the page's own value count allows, but its few bytes can't hold. let error = refused(delta_stream(1000, 0, 1), 1000, delta); - assert!(error.contains("bytes can't hold"), "v2 {v2} {levels}: {error}"); + assert!(error.contains("need more"), "v2 {v2} {levels}: {error}"); // The decoder's array of that count, more than the budget allows. let error = checked(page(delta_stream(1 << 20, 0, 1), 1 << 20, delta), None, 1 << 10, true).unwrap_err().to_string(); assert!(error.contains("decoded-column budget"), "v2 {v2} {levels}: {error}"); @@ -2662,6 +2814,8 @@ mod tests { limit: u64::MAX, chunk_bytes: None, delta_declared: true, + max_def: 0, + max_rep: 0, note: note.clone(), }; let budget = Budget::new(1 << 20, 0); @@ -2677,15 +2831,15 @@ mod tests { } // 2 values of the run are left, the next page holds 4: the skip stops there. assert!(pages.peek_next_page().is_err()); - let (skipped, stopped) = pace.skipped(Err(parquet::errors::ParquetError::General("stop".into()))).unwrap(); + let (skipped, stopped) = pace.skipped("", Err(parquet::errors::ParquetError::General("stop".into()))).unwrap(); assert_eq!((skipped, stopped), (8, true)); assert_eq!(note.skip_left.load(Ordering::Relaxed), NOT_SKIPPING); assert_eq!(pages.peek_next_page().unwrap().and_then(|m| m.num_rows), Some(4), "nothing was fetched"); assert_eq!(pace.skip(2), 1, "the page is then taken a value at a time"); // Another error is the caller's. assert_eq!(pace.skip(3), 3); - assert!(pace.skipped(Err(parquet::errors::ParquetError::General("other".into()))).is_err()); - assert_eq!(pace.skipped(Ok(3)).unwrap(), (3, false)); + assert!(pace.skipped("", Err(parquet::errors::ParquetError::General("other".into()))).is_err()); + assert_eq!(pace.skipped("", Ok(3)).unwrap(), (3, false)); } /// A DELTA_BYTE_ARRAY column takes one value at a page's start, then no more than its page diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index f65fafcaef..8dbfeaf44f 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -5355,6 +5355,29 @@ fn parquet_sampled_delta_read_does_not_fetch_the_pages_it_skips() { } } +/// Delta pages of many blocks, with nulls and lengths that need bits, pass the check of the stream +/// layout that [`CheckedPages`] makes and read back as written (#2913). +#[test] +fn parquet_delta_pages_of_many_blocks_read_back() { + let p = dir().join("decoded-delta-blocks.parquet"); + let mut ds = Dataset::new("pts", GeometryType::Point, vec![Field::new("label", FieldType::Text)]); + let text = |i: usize| (!i.is_multiple_of(11)).then(|| format!("{}{i}", "y".repeat(i % 53))); + for i in 0..3000usize { + ds.push(Some(Geometry::Point(Coord::new(-81.0, 0.0))), vec![text(i).map(Value::Text).unwrap_or(Value::Null)]); + } + let whole = Request { extent: None, limit: 5000, own: None }; + for v2 in [false, true] { + for page_bytes in [None, Some(4 << 10)] { + write_encoded_parquet_fixture(&ds, &p, 3000, false, FixturePages { delta: true, v2, page_bytes }); + let batch = parquet::ParquetSource::open_path(&p, "pts").unwrap().read(&whole).unwrap(); + assert_eq!(batch.features.len(), 3000, "v2 {v2} {page_bytes:?}"); + for (i, f) in batch.features.iter().enumerate() { + assert_eq!(f.attrs[0], text(i).map(Value::Text).unwrap_or(Value::Null), "v2 {v2} {page_bytes:?} row {i}"); + } + } + } +} + /// Data pages of version 2 read as version 1 do, with and without a budget that stops them. #[test] fn parquet_version_two_pages_read_within_the_decoded_budget() { From caada3e962e1d5e757225a736dcd28d46f881325 Mon Sep 17 00:00:00 2001 From: Li-Sheng Chou <142213184+choupeanut@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:14:26 +0800 Subject: [PATCH 12/22] data: tests for delta arrays over the budget, BIT_PACKED levels and the delta round trip (#2913) --- crates/data/src/source/parquet.rs | 121 ++++++++++++++++++++++++------ crates/data/src/source/tests.rs | 6 ++ 2 files changed, 105 insertions(+), 22 deletions(-) diff --git a/crates/data/src/source/parquet.rs b/crates/data/src/source/parquet.rs index a56f7689ef..c6c37cac0b 100644 --- a/crates/data/src/source/parquet.rs +++ b/crates/data/src/source/parquet.rs @@ -2633,8 +2633,8 @@ mod tests { /// whichever version of data page it is. #[test] fn checked_pages_refuse_an_undeclared_delta_page() { - let mut sound = delta_stream(3, 0, 1); - sound.extend(delta_stream(3, 4, 1)); + let mut sound = delta_flat(3, 0); + sound.extend(delta_flat(3, 4)); sound.extend_from_slice(b"ababab"); for (v2, page) in [(false, data_page as fn(usize, Encoding) -> Page), (true, data_page_v2)] { let error = checked(page(4, Encoding::DELTA_BYTE_ARRAY), Some(10), u64::MAX, false).unwrap_err().to_string(); @@ -2675,26 +2675,54 @@ mod tests { } } - /// A DELTA_BINARY_PACKED stream of `count` values, with `blocks` blocks of 128 values in 4 - /// miniblocks, all of bit width 0 (a run of equal values). - fn delta_stream(count: u32, first: u8, blocks: usize) -> Vec { + /// A DELTA_BINARY_PACKED stream of `count` values, written as the format lays it out: blocks of + /// 128 values in 4 miniblocks of 32, whose bit widths cycle through `widths` (a miniblock past + /// the last value has width 0 and no bytes), the packed bytes all zero. + fn delta_bits(count: u32, first: u8, widths: [u8; 4]) -> Vec { + let mut out = delta_head(count, first); + let mut left = count.saturating_sub(1); + let mut at = 0; + while left > 0 { + out.push(0); + let mut packed = 0usize; + let mut bits = Vec::new(); + for _ in 0..4 { + let width = if left == 0 { 0 } else { widths[at % 4] }; + at += 1; + left = left.saturating_sub(32); + bits.push(width); + packed += usize::from(width) * 32 / 8; + } + out.extend(bits); + out.extend(std::iter::repeat_n(0u8, packed)); + } + out + } + + /// The header of such a stream: block size 128, 4 miniblocks, the count, the first value. + fn delta_head(count: u32, first: u8) -> Vec { let mut out = vec![0x80, 0x01, 0x04]; - let mut n = count; + out.extend(uleb_bytes(u64::from(count))); + out.push(first); + out + } + + /// `delta_bits` of width 0 (a run of equal values). + fn delta_flat(count: u32, first: u8) -> Vec { + delta_bits(count, first, [0; 4]) + } + + fn uleb_bytes(mut n: u64) -> Vec { + let mut out = Vec::new(); loop { let low = (n & 0x7f) as u8; n >>= 7; if n == 0 { out.push(low); - break; + return out; } out.push(low | 0x80); } - out.push(first); - for _ in 0..blocks { - // min delta 0, then four miniblock widths of 0. - out.extend_from_slice(&[0, 0, 0, 0, 0]); - } - out } fn delta_page(levels: usize, values: Vec, num_values: u32, encoding: Encoding, v2: bool) -> Page { @@ -2730,9 +2758,9 @@ mod tests { /// count (a few bytes can say two billion values), and a sound one is handed over. #[test] fn checked_pages_refuse_a_delta_page_with_a_count_its_bytes_cannot_hold() { - let huge = delta_stream(i32::MAX as u32, 0, 0); - let mut sound = delta_stream(3, 0, 1); - sound.extend(delta_stream(3, 4, 1)); + let huge = delta_head(i32::MAX as u32, 0); + let mut sound = delta_flat(3, 0); + sound.extend(delta_flat(3, 4)); sound.extend_from_slice(b"ababab"); for v2 in [false, true] { // The two streams of DELTA_BYTE_ARRAY (levels first, in version 2 and in version 1 of a required column: none). @@ -2749,14 +2777,14 @@ mod tests { let error = refused(huge.clone(), 3, lengths); assert!(error.contains("more than the page's 3 values"), "v2 {v2} {levels}: {error}"); // A count the page's own value count allows, but its few bytes can't hold. - let error = refused(delta_stream(1000, 0, 1), 1000, delta); + let error = refused([delta_head(1000, 0), vec![0; 5]].concat(), 1000, delta); assert!(error.contains("need more"), "v2 {v2} {levels}: {error}"); // The decoder's array of that count, more than the budget allows. - let error = checked(page(delta_stream(1 << 20, 0, 1), 1 << 20, delta), None, 1 << 10, true).unwrap_err().to_string(); + let error = checked(page(delta_flat(1 << 20, 0), 1 << 20, delta), None, 1 << 10, true).unwrap_err().to_string(); assert!(error.contains("decoded-column budget"), "v2 {v2} {levels}: {error}"); // Cut off in its header, a miniblock width or its data, or not a header at all. for cut in [0, 1, 2, 4, 6, 7] { - let error = refused(delta_stream(3, 0, 1)[..cut].to_vec(), 3, delta); + let error = refused(delta_flat(3, 0)[..cut].to_vec(), 3, delta); assert!(error.contains("delta"), "v2 {v2} {levels} cut {cut}: {error}"); } let error = refused(vec![0x80; 12], 3, delta); @@ -2764,17 +2792,66 @@ mod tests { let error = refused(vec![0x81, 0x01, 0x04, 0x03, 0x00], 3, delta); assert!(error.contains("delta"), "a block size that is not a multiple of 128: {error}"); // The second stream's count must be the first's. - let mut odd = delta_stream(3, 0, 1); - odd.extend(delta_stream(2, 4, 1)); + let mut odd = delta_flat(3, 0); + odd.extend(delta_flat(2, 4)); let error = refused(odd, 3, delta); assert!(error.contains("delta"), "v2 {v2} {levels}: {error}"); // Sound pages go through. assert!(checked(page(sound.clone(), 3, delta), None, 1 << 30, true).unwrap().is_some(), "v2 {v2} {levels}"); - assert!(checked(page(delta_stream(3, 4, 1), 3, lengths), None, 1 << 30, true).unwrap().is_some(), "v2 {v2} {levels}"); + assert!(checked(page(delta_flat(3, 4), 3, lengths), None, 1 << 30, true).unwrap().is_some(), "v2 {v2} {levels}"); } } } + /// The crate's decoders make an array of 4 bytes a value for each of a DELTA_BYTE_ARRAY page's two + /// streams: a count the page and the chunk allow, but whose two arrays are more than the budget, + /// is refused. + #[test] + fn checked_pages_refuse_a_delta_count_whose_arrays_are_more_than_the_budget() { + let limit = 1u64 << 20; + // Under a quarter of the limit: one array fits, the two don't. + let count = u32::try_from(limit / 4 - 1).unwrap(); + let mut both = delta_flat(count, 0); + both.extend(delta_flat(count, 4)); + let error = checked(delta_page(0, both, count, Encoding::DELTA_BYTE_ARRAY, true), None, limit, true).unwrap_err().to_string(); + assert!(error.contains("decoded-column budget"), "{error}"); + // The one array of DELTA_LENGTH_BYTE_ARRAY fits. + let page = delta_page(0, delta_flat(count, 4), count, Encoding::DELTA_LENGTH_BYTE_ARRAY, true); + assert!(checked(page, None, limit, true).unwrap().is_some()); + } + + /// Levels written in the deprecated BIT_PACKED encoding have no length in front: the page's + /// values start after as many bytes as its values have bits, as the crate reads them. + #[test] + fn checked_pages_read_past_bit_packed_levels() { + let mut sound = delta_flat(3, 0); + sound.extend(delta_flat(3, 4)); + sound.extend_from_slice(b"ababab"); + let mut buf = vec![0b101u8]; + buf.extend(sound); + #[expect(deprecated)] + let def_level_encoding = Encoding::BIT_PACKED; + let page = Page::DataPage { + buf: Bytes::from(buf), + num_values: 3, + encoding: Encoding::DELTA_BYTE_ARRAY, + def_level_encoding, + rep_level_encoding: Encoding::RLE, + statistics: None, + }; + let mut pages = CheckedPages { + pages: Box::new(Pages(vec![page].into_iter())), + bits: 32, + limit: u64::MAX, + chunk_bytes: None, + delta_declared: true, + max_def: 1, + max_rep: 0, + note: Arc::new(PageNote::default()), + }; + assert!(pages.get_next_page().unwrap().is_some()); + } + /// Headers handed out one by one, as a file's pages would be peeked at and skipped. struct Headers(Vec); diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 5263befa13..6e5cd13c7a 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -5415,7 +5415,13 @@ fn parquet_delta_pages_of_many_blocks_read_back() { for v2 in [false, true] { for page_bytes in [None, Some(4 << 10)] { write_encoded_parquet_fixture(&ds, &p, 3000, false, FixturePages { delta: true, v2, page_bytes }); + let encodings = text_encodings(&p, "label"); + assert!(encodings.contains(&::parquet::basic::Encoding::DELTA_BYTE_ARRAY), "{encodings:?}"); + parquet::reset_delta_pages(); let batch = parquet::ParquetSource::open_path(&p, "pts").unwrap().read(&whole).unwrap(); + // The label column's pages (version 1 has a definition level stream in front of the + // values) went through the check: one page, or several of about 4 KiB. + assert!(parquet::delta_pages() >= if page_bytes.is_some() { 2 } else { 1 }, "v2 {v2} {page_bytes:?}"); assert_eq!(batch.features.len(), 3000, "v2 {v2} {page_bytes:?}"); for (i, f) in batch.features.iter().enumerate() { assert_eq!(f.attrs[0], text(i).map(Value::Text).unwrap_or(Value::Null), "v2 {v2} {page_bytes:?} row {i}"); From 6d77bd421bf1e3ff28eea993f9ad6fe2612ba3c1 Mon Sep 17 00:00:00 2001 From: Li-Sheng Chou <142213184+choupeanut@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:42:30 +0800 Subject: [PATCH 13/22] data: delta counts are held to the chunk and the budget left, BIT_PACKED levels are read past, and the check is tested against the writer (#2913) --- crates/data/src/source/parquet.rs | 366 +++++++++++++++++++++++------- crates/data/src/source/tests.rs | 22 ++ 2 files changed, 305 insertions(+), 83 deletions(-) diff --git a/crates/data/src/source/parquet.rs b/crates/data/src/source/parquet.rs index c6c37cac0b..1e13b98f81 100644 --- a/crates/data/src/source/parquet.rs +++ b/crates/data/src/source/parquet.rs @@ -1035,9 +1035,12 @@ fn err(e: parquet::errors::ParquetError) -> DataError { DataError::Format(format!("GeoParquet: {e}")) } -/// [`err`] for an error met in `place` (a row group and column, or `""` when not known). -fn err_in(place: &str, e: parquet::errors::ParquetError) -> DataError { - if place.is_empty() { err(e) } else { DataError::Format(format!("GeoParquet: {place}: {e}")) } +/// [`err`] for an error met in `place` (a row group and column), when it is known. +fn err_in(place: Option<&str>, e: parquet::errors::ParquetError) -> DataError { + match place { + Some(place) => DataError::Format(format!("GeoParquet: {place}: {e}")), + None => err(e), + } } /// The reader of a row group's column, its pages checked by [`CheckedPages`] (a page no bigger @@ -1068,6 +1071,7 @@ fn column_reader_within(rg: &dyn RowGroupReader, col: usize, limit: u64) -> Resu delta_declared: chunk.encodings().any(|e| e == Encoding::DELTA_BYTE_ARRAY), max_def: desc.max_def_level(), max_rep: desc.max_rep_level(), + chunk_values: u64::try_from(chunk.num_values()).ok().filter(|&n| n > 0).unwrap_or(u64::MAX), note: note.clone(), }; Ok((parquet::column::reader::get_column_reader(desc, Box::new(pages)), note)) @@ -1088,6 +1092,9 @@ struct PageNote { peeked: std::sync::atomic::AtomicUsize, /// Such a call was stopped at a page it would only have skipped part of. stopped: std::sync::atomic::AtomicBool, + /// What the read's budget has left, as the column's values are charged (everything until a read + /// says): the decoder's own arrays for a page are held against it. + left: std::sync::atomic::AtomicU64, } /// [`PageNote::skip_left`] when no skip is passing over whole pages. @@ -1102,6 +1109,7 @@ impl Default for PageNote { passed: Default::default(), peeked: Default::default(), stopped: Default::default(), + left: std::sync::atomic::AtomicU64::new(u64::MAX), } } } @@ -1148,7 +1156,7 @@ impl Pace<'_> { /// Ends a skip call that [`skip`](Self::skip) asked for, which `result` is the outcome of: the /// values it skipped, whether it was stopped at a page it would only have skipped part of (the /// whole pages before that count). - fn skipped(&self, place: &str, result: parquet::errors::Result) -> Result<(usize, bool)> { + fn skipped(&self, place: Option<&str>, result: parquet::errors::Result) -> Result<(usize, bool)> { let Some((note, _)) = self.watch else { return result.map(|n| (n, false)).map_err(|e| err_in(place, e)) }; note.skip_left.store(NOT_SKIPPING, Ordering::Relaxed); match result { @@ -1185,6 +1193,8 @@ struct CheckedPages { /// The most levels the column's values have, for a version 1 page's level streams. max_def: i16, max_rep: i16, + /// The values the column chunk's footer says it holds, when it says (levels included). + chunk_values: u64, note: Arc, } @@ -1200,27 +1210,38 @@ impl Iterator for CheckedPages { impl CheckedPages { /// Refuses a DELTA_BYTE_ARRAY or DELTA_LENGTH_BYTE_ARRAY data page whose streams say they hold - /// more values than the page does or its bytes can, or can't be read: the crate's decoders make - /// an array of that count (4 bytes a value) before decoding a value, and a few bytes can ask for - /// gigabytes. See [`delta_stream`] for what is checked. + /// more values than the page or the column chunk does, or whose arrays the decoder would make + /// for them (4 bytes a value for each stream, `parquet` 60.2.0 `set_data`) are more than the + /// budget has left, or can't be read as a stream: the decoders size those arrays from the count + /// in the stream before decoding a value, and a few bytes can ask for gigabytes. See + /// [`delta_stream`] for what is checked of a stream. fn check_delta(&self, page: &parquet::column::page::Page) -> parquet::errors::Result<()> { use parquet::column::page::Page; let (buf, num_values, encoding, levels) = match page { Page::DataPage { buf, num_values, encoding, def_level_encoding, rep_level_encoding, .. } => { + if !matches!(encoding, Encoding::DELTA_BYTE_ARRAY | Encoding::DELTA_LENGTH_BYTE_ARRAY) { + return Ok(()); + } + // Each level stream in front of the values, as the crate's `parse_v1_level` sizes it. let mut at = 0usize; for (max, level_encoding) in [(self.max_rep, rep_level_encoding), (self.max_def, def_level_encoding)] { - if max > 0 { - if *level_encoding != Encoding::RLE { - return Err(delta_err("its levels are not RLE, so where its values start can't be told")); - } - let len = buf - .get(at..at.saturating_add(4)) - .and_then(|b| <[u8; 4]>::try_from(b).ok()) - .map(u32::from_le_bytes) - .and_then(|n| usize::try_from(n).ok()) - .ok_or_else(|| delta_err("its levels are cut off"))?; - at = at.saturating_add(4).saturating_add(len); + if max <= 0 { + continue; } + #[expect(deprecated, reason = "BIT_PACKED levels are deprecated but still read")] + let bit_packed = Encoding::BIT_PACKED; + let len = if *level_encoding == Encoding::RLE { + let prefix = buf.get(at..at.saturating_add(4)).and_then(|b| <[u8; 4]>::try_from(b).ok()); + let len = prefix.map(u32::from_le_bytes).and_then(|n| usize::try_from(n).ok()); + len.and_then(|n| n.checked_add(4)).ok_or_else(|| delta_err("its levels are cut off"))? + } else if *level_encoding == bit_packed { + let bits = u64::from(u64::BITS - u64::try_from(max).unwrap_or(0).leading_zeros()); + let bytes = (u64::from(*num_values).saturating_mul(bits)).div_ceil(8); + usize::try_from(bytes).map_err(|_| delta_err("its levels are cut off"))? + } else { + return Err(delta_err(&format!("its levels are in the {level_encoding} encoding, which a page can't have"))); + }; + at = at.saturating_add(len); } (buf, *num_values, *encoding, at) } @@ -1234,12 +1255,19 @@ impl CheckedPages { return Ok(()); } let values = buf.get(levels..).ok_or_else(|| delta_err("its levels are longer than the page"))?; - let max = u64::from(num_values); - let (count, end) = delta_stream(values, max, self.limit)?; - if encoding == Encoding::DELTA_BYTE_ARRAY { + let delta = encoding == Encoding::DELTA_BYTE_ARRAY; + let bounds = DeltaBounds { + page: u64::from(num_values), + chunk: self.chunk_values, + left: self.limit.min(self.note.left.load(Ordering::Relaxed)), + // A DELTA_BYTE_ARRAY page makes an array for its prefix lengths and one for its suffix lengths. + per_value: if delta { 8 } else { 4 }, + }; + let (count, end) = delta_stream(values, &bounds)?; + if delta { // The prefix lengths are followed by the suffixes, a DELTA_LENGTH_BYTE_ARRAY stream of as many. let rest = values.get(end..).ok_or_else(|| delta_err("its prefix lengths run past the page"))?; - let (suffixes, _) = delta_stream(rest, max, self.limit)?; + let (suffixes, _) = delta_stream(rest, &bounds)?; if suffixes != count { return Err(delta_err(&format!("it has {count} prefix lengths and {suffixes} suffixes"))); } @@ -1252,14 +1280,26 @@ fn delta_err(what: &str) -> parquet::errors::ParquetError { parquet::errors::ParquetError::General(format!("a delta page is refused: {what}")) } +/// What a delta stream's count may be. +struct DeltaBounds { + /// The values of the page (levels included). + page: u64, + /// The values of the column chunk. + chunk: u64, + /// What the budget has left. + left: u64, + /// The bytes the decoders make an array of for each value of a page. + per_value: u64, +} + /// One ULEB128 number at `at` of `data`, moving `at` past it (`None` when it is cut off or longer -/// than the 10 bytes the crate reads: it stops with a panic at an 11th). +/// than the 10 bytes the crate reads: it panics at an 11th). fn uleb(data: &[u8], at: &mut usize) -> Option { let mut value = 0u64; - for i in 0..10u32 { + for shift in (0..70).step_by(7) { let byte = *data.get(*at)?; *at += 1; - value |= u64::from(byte & 0x7f).checked_shl(7 * i)?; + value |= u64::from(byte & 0x7f) << shift; if byte & 0x80 == 0 { return Some(value); } @@ -1268,14 +1308,13 @@ fn uleb(data: &[u8], at: &mut usize) -> Option { } /// Reads the layout of the DELTA_BINARY_PACKED stream at the start of `data` as the crate's -/// `DeltaBitPackDecoder` does, without decoding a value: its header (block size, miniblocks per -/// block, the count of values, the first value), then each block's minimum delta and miniblock bit -/// widths, to where the stream ends. It returns the count and the end offset. The stream is refused -/// when the count is more than `max_values` (the page's value count) or more than `limit` bytes -/// make as 4-byte lengths (what the decoder allocates), when the blocks it needs don't fit in -/// `data`, or when anything is cut off or the sizes aren't the multiples the format needs. The -/// crate's decoders trust all of that when they size their arrays, and panic on some of it. -fn delta_stream(data: &[u8], max_values: u64, limit: u64) -> parquet::errors::Result<(u64, usize)> { +/// `DeltaBitPackDecoder` does, without decoding a value: the header (block size, miniblocks per +/// block, count of values, first value), then each block's minimum delta and miniblock bit widths. +/// It returns the count and the offset where the stream ends. It refuses a stream whose count is +/// more than `bounds` allow, whose blocks don't fit in `data`, or that is cut off or not the sizes +/// the format needs: the crate's decoders trust all of that when they size their arrays, and panic +/// on some of it. +fn delta_stream(data: &[u8], bounds: &DeltaBounds) -> parquet::errors::Result<(u64, usize)> { let mut at = 0usize; let cut = || delta_err("a stream header is cut off or malformed"); let block = uleb(data, &mut at).ok_or_else(cut)?; @@ -1290,24 +1329,26 @@ fn delta_stream(data: &[u8], max_values: u64, limit: u64) -> parquet::errors::Re { return Err(delta_err(&format!("its block of {block} values in {mini_blocks} miniblocks is not one the format allows"))); } - if count > max_values { - return Err(delta_err(&format!("a stream says it holds {count} values, more than the page's {max_values} values"))); + if count > bounds.page { + return Err(delta_err(&format!("a stream says it holds {count} values, more than the page's {}", bounds.page))); } - if count.saturating_mul(4) > limit { - return Err(parquet::errors::ParquetError::General(format!( - "a delta page's stream says it holds {count} values, whose lengths are more than the {limit} byte decoded-column budget" + if count > bounds.chunk { + return Err(delta_err(&format!("a stream says it holds {count} values, more than the column chunk's {}", bounds.chunk))); + } + if count.saturating_mul(bounds.per_value) > bounds.left { + return Err(delta_err(&format!( + "a stream says it holds {count} values, whose arrays of {} bytes each are more than the {} bytes the decoded-column budget has left", + bounds.per_value, bounds.left ))); } let per_mini = block / mini_blocks; let widths = usize::try_from(mini_blocks).map_err(|_| cut())?; let mut left = count.saturating_sub(1); while left > 0 { - uleb(data, &mut at) - .ok_or_else(|| delta_err(&format!("its {count} values need more blocks than its {} bytes can hold", data.len())))?; + let short = || delta_err(&format!("its {count} values need more blocks than its {} bytes can hold", data.len())); + uleb(data, &mut at).ok_or_else(short)?; let end = at.checked_add(widths).ok_or_else(cut)?; - let bits = data - .get(at..end) - .ok_or_else(|| delta_err(&format!("its {count} values need more blocks than its {} bytes can hold", data.len())))?; + let bits = data.get(at..end).ok_or_else(short)?; at = end; let mut packed = 0u64; for &width in bits { @@ -1622,7 +1663,7 @@ fn field_type(c: &ColumnDescPtr) -> Option { /// rows not taken are skipped without being decoded into values, so a sample of a large row /// group doesn't hold all of it. fn read_column(r: &mut ColumnReaderImpl, take: &[bool], max_def: i16) -> Result>> { - read_column_with(r, take, max_def, &Pace { watch: None }, "", &mut |_| Ok(())) + read_column_with(r, take, max_def, &Pace { watch: None }, None, &mut |_| Ok(())) } /// Forgets the longest skip this thread has made, for tests. @@ -1665,7 +1706,7 @@ fn read_column_with( take: &[bool], max_def: i16, pace: &Pace, - place: &str, + place: Option<&str>, charge: &mut dyn FnMut(&T::T) -> Result<()>, ) -> Result>> { let wanted = take.iter().filter(|&&t| t).count(); @@ -1934,8 +1975,11 @@ fn read_binary( let delta = chunk.encodings().any(|e| e == Encoding::DELTA_BYTE_ARRAY); let pace = Pace { watch: delta.then_some((&*note, budget)) }; let place = format!("row group {}, column '{name}'", budget.group); - read_column_with(&mut r, take, chunk.column_descr().max_def_level(), &pace, &place, &mut |b: &ByteArray| { - budget.charge(size(b.data()), &name) + note.left.store(budget.left.get(), Ordering::Relaxed); + read_column_with(&mut r, take, chunk.column_descr().max_def_level(), &pace, Some(&place), &mut |b: &ByteArray| { + budget.charge(size(b.data()), &name)?; + note.left.store(budget.left.get(), Ordering::Relaxed); + Ok(()) }) .map(Some) } @@ -2599,6 +2643,7 @@ mod tests { delta_declared, max_def: 0, max_rep: 0, + chunk_values: u64::MAX, note: Arc::new(PageNote::default()), } .get_next_page() @@ -2658,6 +2703,7 @@ mod tests { delta_declared: false, max_def: 0, max_rep: 0, + chunk_values: u64::MAX, note: note.clone(), }; assert!(pages.get_next_page().unwrap().is_some()); @@ -2753,53 +2799,205 @@ mod tests { } } + /// `page` through [`CheckedPages`] of a column with `max_def` levels, in a chunk of `chunk_values` + /// values, with `left` bytes of budget. + fn checked_in(page: Page, max_def: i16, chunk_values: u64, left: u64) -> parquet::errors::Result> { + let note = Arc::new(PageNote::default()); + note.left.store(left, Ordering::Relaxed); + CheckedPages { + pages: Box::new(Pages(vec![page].into_iter())), + bits: 32, + limit: u64::MAX, + chunk_bytes: None, + delta_declared: true, + max_def, + max_rep: 0, + chunk_values, + note, + } + .get_next_page() + } + + /// A version 1 delta page of a column with a definition level, its levels `levels` in front. + fn delta_page_with_levels(levels: Vec, values: Vec, num_values: u32, def_level_encoding: Encoding) -> Page { + Page::DataPage { + buf: Bytes::from([levels, values].concat()), + num_values, + encoding: Encoding::DELTA_BYTE_ARRAY, + def_level_encoding, + rep_level_encoding: Encoding::RLE, + statistics: None, + } + } + + /// The two streams of a DELTA_BYTE_ARRAY page of `count` values, then `tail` bytes. + fn delta_bytes(count: u32, widths: [u8; 4], tail: &[u8]) -> Vec { + [delta_bits(count, 0, widths), delta_bits(count, 4, widths), tail.to_vec()].concat() + } + /// A delta page whose count is more than its values, or more than its bytes can hold, or whose /// header is cut off or malformed, is refused before the crate's decoder sizes an array from the - /// count (a few bytes can say two billion values), and a sound one is handed over. + /// count (a few bytes can say two billion values), and a sound one is handed over. Each refusal + /// says which of these it is. #[test] fn checked_pages_refuse_a_delta_page_with_a_count_its_bytes_cannot_hold() { let huge = delta_head(i32::MAX as u32, 0); - let mut sound = delta_flat(3, 0); - sound.extend(delta_flat(3, 4)); - sound.extend_from_slice(b"ababab"); + let delta = Encoding::DELTA_BYTE_ARRAY; + let lengths = Encoding::DELTA_LENGTH_BYTE_ARRAY; + let sound = delta_bytes(3, [0; 4], b"ababab"); + // Widths that need bits, over several blocks. + let wide = delta_bytes(300, [3, 0, 5, 7], b""); for v2 in [false, true] { - // The two streams of DELTA_BYTE_ARRAY (levels first, in version 2 and in version 1 of a required column: none). + // Level bytes in front, in version 2 (a version 1 page of a column without levels has none). for levels in [0, 2] { if !v2 && levels > 0 { continue; } + let at = format!("v2 {v2} levels {levels}"); let page = |values: Vec, n: u32, e| delta_page(levels, values, n, e, v2); let refused = |values: Vec, n: u32, e| checked(page(values, n, e), None, 1 << 30, true).unwrap_err().to_string(); - let delta = Encoding::DELTA_BYTE_ARRAY; - let lengths = Encoding::DELTA_LENGTH_BYTE_ARRAY; - let error = refused(huge.clone(), 3, delta); - assert!(error.contains("more than the page's 3 values"), "v2 {v2} {levels}: {error}"); - let error = refused(huge.clone(), 3, lengths); - assert!(error.contains("more than the page's 3 values"), "v2 {v2} {levels}: {error}"); + let says = |error: String, what: &str| { + assert!(error.contains(&format!("a delta page is refused: {what}")), "{at}: {error} -- wanted {what}") + }; + says(refused(huge.clone(), 3, delta), "a stream says it holds 2147483647 values, more than the page's 3"); + says(refused(huge.clone(), 3, lengths), "a stream says it holds 2147483647 values, more than the page's 3"); // A count the page's own value count allows, but its few bytes can't hold. - let error = refused([delta_head(1000, 0), vec![0; 5]].concat(), 1000, delta); - assert!(error.contains("need more"), "v2 {v2} {levels}: {error}"); - // The decoder's array of that count, more than the budget allows. - let error = checked(page(delta_flat(1 << 20, 0), 1 << 20, delta), None, 1 << 10, true).unwrap_err().to_string(); - assert!(error.contains("decoded-column budget"), "v2 {v2} {levels}: {error}"); - // Cut off in its header, a miniblock width or its data, or not a header at all. - for cut in [0, 1, 2, 4, 6, 7] { - let error = refused(delta_flat(3, 0)[..cut].to_vec(), 3, delta); - assert!(error.contains("delta"), "v2 {v2} {levels} cut {cut}: {error}"); + says( + refused([delta_head(1000, 0), vec![0; 5]].concat(), 1000, delta), + "its 1000 values need more blocks than its 11 bytes can hold", + ); + // The decoder's arrays for that count, more than the budget has. + let error = checked_in(page(delta_flat(1 << 20, 0), 1 << 20, lengths), 0, u64::MAX, 1 << 10).unwrap_err().to_string(); + says( + error, + "a stream says it holds 1048576 values, whose arrays of 4 bytes each are more than the 1024 bytes the decoded-column budget has left", + ); + // Cut off in its header, a block's minimum delta or widths, or not a header at all. + let flat = delta_flat(3, 0); + for (cut, what) in [ + (0, "a stream header is cut off or malformed"), + (2, "a stream header is cut off or malformed"), + (4, "a stream header is cut off or malformed"), + (5, "its 3 values need more blocks than its 5 bytes can hold"), + (7, "its 3 values need more blocks than its 7 bytes can hold"), + (9, "its 3 values need more blocks than its 9 bytes can hold"), + ] { + says(refused(flat[..cut].to_vec(), 3, delta), what); + } + says(refused(vec![0x80; 12], 3, delta), "a stream header is cut off or malformed"); + says( + refused(vec![0x81, 0x01, 0x04, 0x03, 0x00], 3, delta), + "its block of 129 values in 4 miniblocks is not one the format allows", + ); + says( + refused(vec![0x80, 0x01, 0x00, 0x03, 0x00], 3, delta), + "its block of 128 values in 0 miniblocks is not one the format allows", + ); + says( + refused(vec![0x80, 0x01, 0x03, 0x03, 0x00], 3, delta), + "its block of 128 values in 3 miniblocks is not one the format allows", + ); + // A width above 32, and packed bytes the page doesn't have. + let mut wide_bits = delta_flat(3, 0); + wide_bits[6] = 33; + says(refused(wide_bits, 3, delta), "a miniblock has a bit width of 33, more than 32"); + let mut packed = delta_bits(3, 0, [3, 0, 0, 0]); + packed.truncate(packed.len() - 1); + says(refused(packed, 3, delta), "its 3 values need more bytes than the page's 21 bytes can hold"); + // The two streams' counts must agree. + let odd = [delta_flat(3, 0), delta_flat(2, 4)].concat(); + says(refused(odd, 3, delta), "it has 3 prefix lengths and 2 suffixes"); + // Sound pages go through, and so does a column of nothing but nulls. + for (values, n) in + [(sound.clone(), 3), (wide.clone(), 300), (delta_bytes(0, [0; 4], b""), 3), (delta_bytes(1, [0; 4], b"a"), 1)] + { + assert!(checked(page(values, n, delta), None, 1 << 30, true).unwrap().is_some(), "{at}"); + } + assert!(checked(page(delta_flat(3, 4), 3, lengths), None, 1 << 30, true).unwrap().is_some(), "{at}"); + } + } + } + + /// Levels in front of a version 1 page's values: an RLE stream with its length, in the order + /// the crate reads them, and a page with them cut off or in no encoding a page has is refused. + #[test] + fn checked_pages_find_the_values_after_a_version_one_pages_levels() { + let sound = delta_bytes(300, [3, 0, 5, 7], b""); + let rle = |bytes: &[u8]| [u32::try_from(bytes.len()).unwrap().to_le_bytes().to_vec(), bytes.to_vec()].concat(); + let page = |levels: Vec, values: Vec, encoding| delta_page_with_levels(levels, values, 300, encoding); + // A definition level stream of 3 bytes, then the values. + assert!(checked_in(page(rle(&[1, 2, 3]), sound.clone(), Encoding::RLE), 1, u64::MAX, u64::MAX).unwrap().is_some()); + assert!(checked_in(page(rle(&[]), sound.clone(), Encoding::RLE), 1, u64::MAX, u64::MAX).unwrap().is_some()); + let error = checked_in(page(vec![9, 0], vec![], Encoding::RLE), 1, u64::MAX, u64::MAX).unwrap_err().to_string(); + assert!(error.contains("a delta page is refused: its levels are cut off"), "{error}"); + let error = checked_in(page(rle(&[1]), sound.clone(), Encoding::PLAIN), 1, u64::MAX, u64::MAX).unwrap_err().to_string(); + assert!(error.contains("its levels are in the PLAIN encoding, which a page can't have"), "{error}"); + // A level length that runs past the page. + let error = checked_in(page(vec![0xff, 0xff, 0xff, 0x7f], sound, Encoding::RLE), 1, u64::MAX, u64::MAX).unwrap_err().to_string(); + assert!(error.contains("its levels are longer than the page"), "{error}"); + } + + /// A stream says it holds more values than the column chunk does: refused, though the page's own + /// count allows it; and one the budget left can't hold the arrays of, though the whole limit could. + #[test] + fn checked_pages_hold_a_delta_count_to_the_chunk_and_the_budget_left() { + let values = delta_bytes(300, [3, 0, 5, 7], b""); + let page = || delta_page(0, values.clone(), 300, Encoding::DELTA_BYTE_ARRAY, true); + assert!(checked_in(page(), 0, 300, 2400).unwrap().is_some()); + let error = checked_in(page(), 0, 299, u64::MAX).unwrap_err().to_string(); + assert!(error.contains("more than the column chunk's 299"), "{error}"); + let error = checked_in(page(), 0, 300, 2399).unwrap_err().to_string(); + assert!(error.contains("the 2399 bytes the decoded-column budget has left"), "{error}"); + } + + /// The layout `delta_stream` reads agrees with a real writer's: the count and the end of the + /// stream (the page holds nothing else) for many shapes of values, in pages of one stream. + #[test] + fn delta_stream_ends_where_the_writer_ended_it() { + use arrow_array::{ArrayRef, Int32Array, RecordBatch}; + use arrow_schema::{DataType, Field as AField, Schema}; + use parquet::file::reader::{FileReader as _, SerializedFileReader}; + let wide: Vec = (0..5000).map(|i| (i * 7919) % 100_003 - 50_000).collect(); + let shapes: Vec> = vec![ + vec![5], + vec![5, 5], + vec![0; 127], + vec![3; 128], + vec![3; 129], + (0..300).collect(), + (0..1000).map(|i| i * i % 1009).collect(), + wide, + (0..4096).map(|i| if i % 2 == 0 { i32::MAX - i } else { i32::MIN + i }).collect(), + ]; + for values in shapes { + let schema = Arc::new(Schema::new(vec![AField::new("v", DataType::Int32, false)])); + let column: ArrayRef = Arc::new(Int32Array::from(values.clone())); + let batch = RecordBatch::try_new(schema.clone(), vec![column]).unwrap(); + let props = ::parquet::file::properties::WriterProperties::builder() + .set_dictionary_enabled(false) + .set_encoding(Encoding::DELTA_BINARY_PACKED) + .set_data_page_row_count_limit(usize::MAX) + .set_data_page_size_limit(usize::MAX) + .build(); + let mut bytes = Vec::new(); + let mut writer = ::parquet::arrow::ArrowWriter::try_new(&mut bytes, schema, Some(props)).unwrap(); + writer.write(&batch).unwrap(); + writer.close().unwrap(); + let reader = SerializedFileReader::new(Bytes::from(bytes)).unwrap(); + let mut pages = reader.get_row_group(0).unwrap().get_column_page_reader(0).unwrap(); + let mut seen = 0; + while let Some(page) = pages.get_next_page().unwrap() { + if let Page::DataPage { buf, num_values, .. } | Page::DataPageV2 { buf, num_values, .. } = &page { + let bounds = DeltaBounds { page: u64::MAX, chunk: u64::MAX, left: u64::MAX, per_value: 4 }; + let (count, end) = delta_stream(buf, &bounds).unwrap(); + assert_eq!((count, end), (u64::from(*num_values), buf.len()), "{} values", values.len()); + // With bytes after it the stream still ends in the same place. + let longer = [buf.to_vec(), vec![0xAB; 9]].concat(); + assert_eq!(delta_stream(&longer, &bounds).unwrap(), (count, end), "{} values", values.len()); + seen += 1; } - let error = refused(vec![0x80; 12], 3, delta); - assert!(error.contains("delta"), "v2 {v2} {levels}: {error}"); - let error = refused(vec![0x81, 0x01, 0x04, 0x03, 0x00], 3, delta); - assert!(error.contains("delta"), "a block size that is not a multiple of 128: {error}"); - // The second stream's count must be the first's. - let mut odd = delta_flat(3, 0); - odd.extend(delta_flat(2, 4)); - let error = refused(odd, 3, delta); - assert!(error.contains("delta"), "v2 {v2} {levels}: {error}"); - // Sound pages go through. - assert!(checked(page(sound.clone(), 3, delta), None, 1 << 30, true).unwrap().is_some(), "v2 {v2} {levels}"); - assert!(checked(page(delta_flat(3, 4), 3, lengths), None, 1 << 30, true).unwrap().is_some(), "v2 {v2} {levels}"); } + assert!(seen > 0); } } @@ -2829,7 +3027,7 @@ mod tests { sound.extend_from_slice(b"ababab"); let mut buf = vec![0b101u8]; buf.extend(sound); - #[expect(deprecated)] + #[expect(deprecated, reason = "BIT_PACKED levels are deprecated but still read")] let def_level_encoding = Encoding::BIT_PACKED; let page = Page::DataPage { buf: Bytes::from(buf), @@ -2847,6 +3045,7 @@ mod tests { delta_declared: true, max_def: 1, max_rep: 0, + chunk_values: u64::MAX, note: Arc::new(PageNote::default()), }; assert!(pages.get_next_page().unwrap().is_some()); @@ -2893,6 +3092,7 @@ mod tests { delta_declared: true, max_def: 0, max_rep: 0, + chunk_values: u64::MAX, note: note.clone(), }; let budget = Budget::new(1 << 20, 0); @@ -2908,15 +3108,15 @@ mod tests { } // 2 values of the run are left, the next page holds 4: the skip stops there. assert!(pages.peek_next_page().is_err()); - let (skipped, stopped) = pace.skipped("", Err(parquet::errors::ParquetError::General("stop".into()))).unwrap(); + let (skipped, stopped) = pace.skipped(None, Err(parquet::errors::ParquetError::General("stop".into()))).unwrap(); assert_eq!((skipped, stopped), (8, true)); assert_eq!(note.skip_left.load(Ordering::Relaxed), NOT_SKIPPING); assert_eq!(pages.peek_next_page().unwrap().and_then(|m| m.num_rows), Some(4), "nothing was fetched"); assert_eq!(pace.skip(2), 1, "the page is then taken a value at a time"); // Another error is the caller's. assert_eq!(pace.skip(3), 3); - assert!(pace.skipped("", Err(parquet::errors::ParquetError::General("other".into()))).is_err()); - assert_eq!(pace.skipped("", Ok(3)).unwrap(), (3, false)); + assert!(pace.skipped(None, Err(parquet::errors::ParquetError::General("other".into()))).is_err()); + assert_eq!(pace.skipped(None, Ok(3)).unwrap(), (3, false)); } /// A DELTA_BYTE_ARRAY column takes one value at a page's start, then no more than its page diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 6e5cd13c7a..944196e6d6 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -5430,6 +5430,28 @@ fn parquet_delta_pages_of_many_blocks_read_back() { } } +/// The decoder of a delta page makes arrays of the page's count (8 bytes a value), more than the +/// values it builds from short text: the read holds them against the budget left, so a page of 3,000 +/// one-letter values is refused with 80,000 bytes (the geometry took 63,000 of them) and read with +/// 200,000 (#2913). +#[test] +fn parquet_delta_page_arrays_count_against_the_budget() { + let p = dir().join("decoded-delta-arrays.parquet"); + let mut ds = Dataset::new("pts", GeometryType::Point, vec![Field::new("label", FieldType::Text)]); + for _ in 0..3000 { + ds.push(Some(Geometry::Point(Coord::new(-81.0, 0.0))), vec![Value::Text("a".into())]); + } + let whole = Request { extent: None, limit: 5000, own: None }; + for v2 in [false, true] { + write_encoded_parquet_fixture(&ds, &p, 3000, false, FixturePages { delta: true, v2, page_bytes: None }); + let source = parquet::ParquetSource::open_path(&p, "pts").unwrap().with_decoded_bytes(80_000); + let error = source.read(&whole).unwrap_err().to_string(); + assert!(error.contains("bytes the decoded-column budget has left") && error.contains("column 'label'"), "v2 {v2}: {error}"); + let source = parquet::ParquetSource::open_path(&p, "pts").unwrap().with_decoded_bytes(200_000); + assert_eq!(source.read(&whole).unwrap().features.len(), 3000, "v2 {v2}"); + } +} + /// Data pages of version 2 read as version 1 do, with and without a budget that stops them. #[test] fn parquet_version_two_pages_read_within_the_decoded_budget() { From e38706faa05dc28bf180f3f0c143cf16d3c16efc Mon Sep 17 00:00:00 2001 From: Li-Sheng Chou <142213184+choupeanut@users.noreply.github.com> Date: Sat, 28 Nov 2026 04:42:26 +0800 Subject: [PATCH 14/22] data: GeoParquet late-filtered views charge only chosen rows, delta length pages paced, budget tests tightened (#2913) --- crates/data/src/source/parquet.rs | 114 ++++++++++++++++++++++++-- crates/data/src/source/tests.rs | 131 ++++++++++++++++++++++++++++-- 2 files changed, 230 insertions(+), 15 deletions(-) diff --git a/crates/data/src/source/parquet.rs b/crates/data/src/source/parquet.rs index 1e13b98f81..c4dabcbc1d 100644 --- a/crates/data/src/source/parquet.rs +++ b/crates/data/src/source/parquet.rs @@ -754,15 +754,71 @@ impl FeatureSource for ParquetSource { let rg = self.reader.get_row_group(g).map_err(err)?; let budget = Budget::new(*decoded, g); let geoms = read_bytes(rg.as_ref(), self.geom_col, take, &budget)?; + let base = starts.get(g).copied().unwrap_or(0); + let wanted = take.iter().filter(|&&t| t).count(); + if late { + // The geometry test and the sampler choose the rows first; only their attributes + // are decoded, and so charged. + if geoms.len() != wanted { + return Err(DataError::Format(format!("GeoParquet: row group {g} has columns shorter than its rows"))); + } + for (k, (r, _)) in take.iter().enumerate().filter(|(_, t)| **t).enumerate() { + if unbounded { + crate::progress::step(1)?; + } + let geometry = match geoms.get(k).and_then(|b| b.as_deref()) { + Some(bytes) => { + let Some(geometry) = wkb::decode(bytes).and_then(|g| self.reproject.place(g, req)) else { + skipped += 1; + continue; + }; + Some(geometry) + } + None => None, + }; + if !geometry.as_ref().map_or(req.extent.is_none(), |g| g.inside) || !sample.wants() { + continue; + } + sample.keep(Feature { + id: base.saturating_add(r as u64 + 1), + geometry: geometry.map(|p| p.geometry), + attrs: Vec::new(), + }); + } + // The rows of this group the sample still holds, in order (it may have dropped some). + let mut chosen = vec![false; take.len()]; + let mut mine = Vec::new(); + for (i, f) in sample.items.iter().enumerate() { + if let Some(r) = f.id.checked_sub(base.saturating_add(1)).and_then(|r| usize::try_from(r).ok()) + && let Some(c) = chosen.get_mut(r) + { + *c = true; + mine.push(i); + } + } + let attrs: Vec = + self.field_cols.iter().map(|&c| read_values(rg.as_ref(), c, &chosen, &budget)).collect::>()?; + if attrs.iter().any(|a| a.values.len() != mine.len()) { + return Err(DataError::Format(format!("GeoParquet: row group {g} has columns shorter than its rows"))); + } + for (n, &i) in mine.iter().enumerate() { + if let Some(f) = sample.items.get_mut(i) { + f.attrs = attrs + .iter() + .enumerate() + .map(|(field, col)| col.value(n, field, &mut unread_dates, &mut rounded_dates)) + .collect(); + } + } + continue; + } let attrs: Vec = self.field_cols.iter().map(|&c| read_values(rg.as_ref(), c, take, &budget)).collect::>()?; // A column shorter than its row group (a truncated or corrupt file) would pair values // with the wrong rows: refuse it. - let wanted = take.iter().filter(|&&t| t).count(); if geoms.len() != wanted || attrs.iter().any(|a| a.values.len() != wanted) { return Err(DataError::Format(format!("GeoParquet: row group {g} has columns shorter than its rows"))); } - let base = starts.get(g).copied().unwrap_or(0); // The columns hold the taken rows only, in order: the k-th is row `r`. for (k, (r, _)) in take.iter().enumerate().filter(|(_, t)| **t).enumerate() { if unbounded { @@ -780,7 +836,7 @@ impl FeatureSource for ParquetSource { None => None, }; let matches_extent = geometry.as_ref().map_or(req.extent.is_none(), |g| g.inside); - if !matches_extent || (late && !sample.wants()) { + if !matches_extent { continue; } let geometry = geometry.map(|p| p.geometry); @@ -873,9 +929,53 @@ impl FeatureSource for ParquetSource { let rg = self.reader.get_row_group(g).map_err(err)?; let budget = Budget::new(*decoded, g); let geoms = read_bytes(rg.as_ref(), self.geom_col, &take, &budget)?; + let wanted = take.iter().filter(|&&t| t).count(); + if extent.is_some() { + // The geometry test chooses the rows first; only their attributes are decoded, and + // so charged. + if geoms.len() != wanted { + return Err(DataError::Format(format!("GeoParquet: row group {g} has columns shorter than its rows"))); + } + let mut chosen = vec![false; take.len()]; + let mut found = Vec::new(); + for (k, (r, _)) in take.iter().enumerate().filter(|(_, t)| **t).enumerate() { + crate::progress::step(1)?; + let geometry = match geoms.get(k).and_then(|b| b.as_deref()) { + Some(bytes) => { + let Some(geometry) = wkb::decode(bytes).and_then(|geom| self.reproject.place(geom, &req)) else { + out.skipped += 1; + continue; + }; + Some(geometry) + } + None => None, + }; + if !geometry.as_ref().map_or(req.extent.is_none(), |g| g.inside) { + continue; + } + if let Some(c) = chosen.get_mut(r) { + *c = true; + } + found.push((r, geometry.map(|p| p.geometry))); + } + let attrs: Vec = + self.field_cols.iter().map(|&c| read_values(rg.as_ref(), c, &chosen, &budget)).collect::>()?; + if attrs.iter().any(|a| a.values.len() != found.len()) { + return Err(DataError::Format(format!("GeoParquet: row group {g} has columns shorter than its rows"))); + } + for (n, (r, geometry)) in found.into_iter().enumerate() { + let values = attrs + .iter() + .enumerate() + .map(|(field, col)| col.value(n, field, &mut out.unread_dates, &mut out.rounded_dates)) + .collect(); + out.matched += 1; + chunks.push(Feature { id: start.saturating_add(r as u64 + 1), geometry, attrs: values })?; + } + continue; + } let attrs: Vec = self.field_cols.iter().map(|&c| read_values(rg.as_ref(), c, &take, &budget)).collect::>()?; - let wanted = take.iter().filter(|&&t| t).count(); if geoms.len() != wanted || attrs.iter().any(|a| a.values.len() != wanted) { return Err(DataError::Format(format!("GeoParquet: row group {g} has columns shorter than its rows"))); } @@ -1957,7 +2057,7 @@ fn text_len(bytes: &[u8]) -> usize { /// of another type). Only the rows taken count, not the /// column chunk's size; a page of more than the budget is refused, as the `parquet` crate makes /// room for a whole page. A column with DELTA_BYTE_ARRAY pages, whose values the decoder builds -/// one by one, is read at the [`Pace`] its page size and the budget left allow. +/// one by one, or DELTA_LENGTH_BYTE_ARRAY pages, whose length arrays are made as a page is fetched, is read at the [`Pace`] its page size and the budget left allow. fn read_binary( rg: &dyn RowGroupReader, col: usize, @@ -1972,7 +2072,9 @@ fn read_binary( let name = chunk.column_path().string(); let (reader, note) = column_reader_within(rg, col, budget.limit)?; let ColumnReader::ByteArrayColumnReader(mut r) = reader else { return Ok(None) }; - let delta = chunk.encodings().any(|e| e == Encoding::DELTA_BYTE_ARRAY); + // DELTA_LENGTH_BYTE_ARRAY pages are paced too: the decoder makes an array of a page's count + // when it is fetched, which must see what the values before it were charged. + let delta = chunk.encodings().any(|e| matches!(e, Encoding::DELTA_BYTE_ARRAY | Encoding::DELTA_LENGTH_BYTE_ARRAY)); let pace = Pace { watch: delta.then_some((&*note, budget)) }; let place = format!("row group {}, column '{name}'", budget.group); note.left.store(budget.left.get(), Ordering::Relaxed); diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 944196e6d6..2e88dc9427 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -5381,7 +5381,7 @@ fn parquet_sampled_delta_read_does_not_fetch_the_pages_it_skips() { ); } for v2 in [false, true] { - let pages = FixturePages { delta: true, v2, page_bytes: Some(2 << 10) }; + let pages = FixturePages { delta: true, v2, page_bytes: Some(2 << 10), ..FixturePages::default() }; write_encoded_parquet_fixture(&ds, &p, 100, false, pages); let source = parquet::ParquetSource::open_path(&p, "pts").unwrap(); // Values that start differently share no prefix, so pages of 2 KiB hold about two each. @@ -5414,7 +5414,7 @@ fn parquet_delta_pages_of_many_blocks_read_back() { let whole = Request { extent: None, limit: 5000, own: None }; for v2 in [false, true] { for page_bytes in [None, Some(4 << 10)] { - write_encoded_parquet_fixture(&ds, &p, 3000, false, FixturePages { delta: true, v2, page_bytes }); + write_encoded_parquet_fixture(&ds, &p, 3000, false, FixturePages { delta: true, v2, page_bytes, ..FixturePages::default() }); let encodings = text_encodings(&p, "label"); assert!(encodings.contains(&::parquet::basic::Encoding::DELTA_BYTE_ARRAY), "{encodings:?}"); parquet::reset_delta_pages(); @@ -5443,7 +5443,7 @@ fn parquet_delta_page_arrays_count_against_the_budget() { } let whole = Request { extent: None, limit: 5000, own: None }; for v2 in [false, true] { - write_encoded_parquet_fixture(&ds, &p, 3000, false, FixturePages { delta: true, v2, page_bytes: None }); + write_encoded_parquet_fixture(&ds, &p, 3000, false, FixturePages { delta: true, v2, page_bytes: None, ..FixturePages::default() }); let source = parquet::ParquetSource::open_path(&p, "pts").unwrap().with_decoded_bytes(80_000); let error = source.read(&whole).unwrap_err().to_string(); assert!(error.contains("bytes the decoded-column budget has left") && error.contains("column 'label'"), "v2 {v2}: {error}"); @@ -5462,7 +5462,7 @@ fn parquet_version_two_pages_read_within_the_decoded_budget() { } let whole = Request { extent: None, limit: 100, own: None }; for delta in [false, true] { - let pages = FixturePages { delta, v2: true, page_bytes: Some(2 << 10) }; + let pages = FixturePages { delta, v2: true, page_bytes: Some(2 << 10), ..FixturePages::default() }; write_encoded_parquet_fixture(&ds, &p, 100, false, pages); // The writer's own choice for version 2 text is DELTA_BYTE_ARRAY, so each case says its own. let encodings = text_encodings(&p, "label"); @@ -5510,21 +5510,128 @@ fn parquet_invalid_text_is_charged_at_its_converted_length() { assert_eq!(batch.features[0].attrs[0], Value::Text("\u{fffd}".repeat(256))); } -/// A page of more than the budget is refused, whatever the rows taken. +/// A page of more than the budget is refused, whatever the rows taken: each label fits the budget +/// alone, and the page they share does not, so the page's own refusal is the one asserted. #[test] fn parquet_page_over_the_budget_is_refused() { let p = dir().join("decoded-page.parquet"); let mut ds = Dataset::new("pts", GeometryType::Point, vec![Field::new("label", FieldType::Text)]); for i in 0..20 { - ds.push(Some(Geometry::Point(Coord::new(-81.0, 0.0))), vec![Value::Text(format!("{}{i:02}", "x".repeat(1024)))]); + ds.push(Some(Geometry::Point(Coord::new(-81.0, 0.0))), vec![Value::Text(format!("{}{i:02}", "x".repeat(98)))]); } - write_encoded_parquet_fixture(&ds, &p, 100, false, FixturePages { page_bytes: Some(2 << 10), ..FixturePages::default() }); + write_encoded_parquet_fixture(&ds, &p, 100, false, FixturePages { page_bytes: Some(1 << 10), ..FixturePages::default() }); + // 100 bytes a label, so more than ten of them (over 1 KiB) share a page. let source = parquet::ParquetSource::open_path(&p, "pts").unwrap().with_decoded_bytes(1 << 10); let one = Request { extent: None, limit: 1, own: None }; let error = source.read(&one).unwrap_err().to_string(); - assert!(error.contains("decoded-column budget"), "{error}"); + assert!(error.contains("a page holds") && error.contains("more than the 1024 byte decoded-column budget"), "{error}"); + assert!(!error.contains("exceeds"), "{error}"); // A page's refusal names the row group and the column, as the budget's does. assert!(error.contains("row group 0") && error.contains("column 'label'"), "{error}"); + // The same label read on its own is under the budget. + let source = parquet::ParquetSource::open_path(&p, "pts").unwrap().with_decoded_bytes(4 << 10); + assert_eq!(source.read(&one).unwrap().features.len(), 1); +} + +/// Late-filtered rows are charged for their attributes only once the geometry test and the sampler +/// have chosen them: a view no bounds can be made of reads a match whose label fits, among rows whose +/// labels together would not (#2913). +#[test] +fn parquet_late_view_charges_only_the_rows_it_keeps() { + let p = dir().join("decoded-late.parquet"); + let mut ds = Dataset::new("pts", GeometryType::Point, vec![Field::new("label", FieldType::Text)]); + for i in 0..20 { + // Row 7 is the one point in the view (latitude 0); the others are at latitude 40. + let (lat, label) = if i == 7 { (0.0, "hit".to_string()) } else { (40.0, "x".repeat(1024)) }; + ds.push(Some(Geometry::Point(Coord::new(-81.0, lat))), vec![Value::Text(label)]); + } + write_unbounded_view_fixture(&ds, &p); + let view = Some(Extent::new(-120.0, -30.0, 10.0, 30.0)); + let req = Request { extent: view, limit: 100, own: None }; + let source = parquet::ParquetSource::open_path(&p, "pts").unwrap().with_decoded_bytes(8 << 10); + let batch = source.read(&req).unwrap(); + assert_eq!((batch.matched, batch.features.len()), (1, 1)); + assert_eq!((batch.features[0].id, &batch.features[0].attrs[0]), (8, &Value::Text("hit".into()))); + let mut seen = Vec::new(); + let batch = source + .visit_chunks(view, 1 << 20, &mut |chunk| { + seen.extend(chunk.into_iter().map(|f| (f.id, f.attrs[0].clone()))); + Ok(()) + }) + .unwrap(); + assert_eq!((batch.matched, seen), (1, vec![(8, Value::Text("hit".into()))])); + // Every row is in the view, and the sample keeps one: only its label is charged, and the read + // is the one the default budget makes. + let mut all = Dataset::new("pts", GeometryType::Point, vec![Field::new("label", FieldType::Text)]); + for _ in 0..20 { + all.push(Some(Geometry::Point(Coord::new(-81.0, 0.0))), vec![Value::Text("x".repeat(1024))]); + } + write_unbounded_view_fixture(&all, &p); + let one = Request { extent: view, limit: 1, own: None }; + let sampled = parquet::ParquetSource::open_path(&p, "pts").unwrap().with_decoded_bytes(8 << 10).read(&one).unwrap(); + let plain = parquet::ParquetSource::open_path(&p, "pts").unwrap().read(&one).unwrap(); + assert_eq!((sampled.matched, sampled.features.len()), (20, 1)); + assert_eq!(sampled.matched, plain.matched); + let rows = |b: &Batch| b.features.iter().map(|f| (f.id, f.attrs[0].clone())).collect::>(); + assert_eq!(rows(&sampled), rows(&plain)); + // Taking every row still stops at the budget. + let error = parquet::ParquetSource::open_path(&p, "pts").unwrap().with_decoded_bytes(8 << 10).read(&req).unwrap_err().to_string(); + assert!(error.contains("decoded-column budget"), "{error}"); +} + +/// The geometry and every text field share one budget: each fits it alone, their sum does not, so +/// the last field is the one refused (#2913). +#[test] +fn parquet_geometry_and_text_fields_share_one_budget() { + let p = dir().join("decoded-two-fields.parquet"); + let mut ds = Dataset::new("pts", GeometryType::Point, vec![Field::new("a", FieldType::Text), Field::new("b", FieldType::Text)]); + for i in 0..4 { + let (a, b) = (format!("{}{i}", "a".repeat(999)), format!("{}{i}", "b".repeat(999))); + ds.push(Some(Geometry::Point(Coord::new(-81.0, 0.0))), vec![Value::Text(a), Value::Text(b)]); + } + write_encoded_parquet_fixture(&ds, &p, 100, false, FixturePages::default()); + let geometry = 4 * wkb::encode(&Geometry::Point(Coord::new(0.0, 0.0))).len() as u64; + let combined = geometry + 2 * 4 * 1000; + let whole = Request { extent: None, limit: 100, own: None }; + // Each column alone fits 6,000 bytes (84 and 4,000 and 4,000), the three together do not. + let source = parquet::ParquetSource::open_path(&p, "pts").unwrap().with_decoded_bytes(6000); + let error = source.read(&whole).unwrap_err().to_string(); + assert!(error.contains("exceeds the 6000 byte decoded-column budget in column 'b'"), "{error}"); + let source = parquet::ParquetSource::open_path(&p, "pts").unwrap().with_decoded_bytes(combined); + let batch = source.read(&whole).unwrap(); + assert_eq!(batch.features.len(), 4); + assert_eq!(batch.features[3].attrs[1], Value::Text(format!("{}3", "b".repeat(999)))); + let source = parquet::ParquetSource::open_path(&p, "pts").unwrap().with_decoded_bytes(combined - 1); + assert!(source.read(&whole).unwrap_err().to_string().contains("column 'b'")); +} + +/// DELTA_LENGTH_BYTE_ARRAY pages make an array of their count when the crate fetches them, so a +/// read goes page by page and the array is checked against what the page before left (#2913). +#[test] +fn parquet_delta_length_pages_are_checked_against_what_the_pages_before_left() { + let p = dir().join("decoded-delta-length.parquet"); + let mut ds = Dataset::new("pts", GeometryType::Point, vec![Field::new("label", FieldType::Text)]); + // One value that fills a page by itself, then many one-letter ones in pages of about 1 KiB. + ds.push(Some(Geometry::Point(Coord::new(-81.0, 0.0))), vec![Value::Text("x".repeat(3000))]); + for _ in 0..1500 { + ds.push(Some(Geometry::Point(Coord::new(-81.0, 0.0))), vec![Value::Text("a".into())]); + } + let whole = Request { extent: None, limit: 5000, own: None }; + let geometry = ds.features.len() as u64 * wkb::encode(&Geometry::Point(Coord::new(0.0, 0.0))).len() as u64; + for v2 in [false, true] { + let pages = FixturePages { lengths: true, v2, page_bytes: Some(1 << 10), ..FixturePages::default() }; + write_encoded_parquet_fixture(&ds, &p, 5000, false, pages); + let encodings = text_encodings(&p, "label"); + assert!(encodings.contains(&::parquet::basic::Encoding::DELTA_LENGTH_BYTE_ARRAY), "{encodings:?}"); + // After the first value 3,000 bytes are left: less than the 4 bytes a value that the next + // page's array takes, though all the values together (4,500 bytes) fit what was left before. + let source = parquet::ParquetSource::open_path(&p, "pts").unwrap().with_decoded_bytes(geometry + 6000); + let error = source.read(&whole).unwrap_err().to_string(); + assert!(error.contains("bytes the decoded-column budget has left") && error.contains("column 'label'"), "v2 {v2}: {error}"); + let source = parquet::ParquetSource::open_path(&p, "pts").unwrap().with_decoded_bytes(geometry + 9000); + let batch = source.read(&whole).unwrap(); + assert_eq!(batch.features.len(), 1501, "v2 {v2}"); + } } /// The same small file must remain readable with plain or dictionary-encoded binary columns. @@ -5625,6 +5732,8 @@ fn write_projected_parquet_fixture(ds: &Dataset, path: &Path, rows: usize, dicti struct FixturePages { /// The DELTA_BYTE_ARRAY encoding. delta: bool, + /// The DELTA_LENGTH_BYTE_ARRAY encoding (when `delta` is not set). + lengths: bool, /// Data pages of version 2. v2: bool, /// About this many bytes to a data page. @@ -5676,7 +5785,11 @@ fn write_encoded_parquet_fixture(ds: &Dataset, path: &Path, rows: usize, diction .set_dictionary_enabled(dictionary) .set_key_value_metadata(Some(vec![::parquet::file::metadata::KeyValue::new("geo".into(), geo.to_string())])); // Left alone, version 2 writes text as DELTA_BYTE_ARRAY, so the plain case says so. - let encoding = if pages.delta { ::parquet::basic::Encoding::DELTA_BYTE_ARRAY } else { ::parquet::basic::Encoding::PLAIN }; + let encoding = match (pages.delta, pages.lengths) { + (true, _) => ::parquet::basic::Encoding::DELTA_BYTE_ARRAY, + (false, true) => ::parquet::basic::Encoding::DELTA_LENGTH_BYTE_ARRAY, + (false, false) => ::parquet::basic::Encoding::PLAIN, + }; for field in ds.fields.iter().filter(|f| f.ty == FieldType::Text) { props = props.set_column_encoding(field.name.as_str().into(), encoding); } From 7c1c1d29f03c4becb1565fd723dd6a3a562104aa Mon Sep 17 00:00:00 2001 From: Li-Sheng Chou <142213184+choupeanut@users.noreply.github.com> Date: Sat, 28 Nov 2026 04:42:26 +0800 Subject: [PATCH 15/22] data: GeoParquet sampling docs name the page-level refusals and their remedies (#2913) --- docs/user-guide/data-formats.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 46fd3fea6f..02827eb4eb 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -39,7 +39,7 @@ export names its feature. | Geotagged photos | `.jpg`, `.jpeg` | Add Data (several at once in the web app), drop them, upload, or `layer.addPhotos` with `"paths"` or a `"folder"` | JPEGs with a GPS position in their EXIF become points in the **Photos** layer (photos added one at a time join it): each with its `name`, `file`, `time` (when it was taken), `altitude`, `direction` (where the camera faced), `camera` and a `thumbnail` of at most 160 pixels, kept with the feature so the project needs no other file. Identify shows the thumbnail. Photos without a position are named in a notice and left out; a layer holds up to 2,000 photos. A JPEG is always read as a photo unless `layer.addData` or `layer.addDataBytes` is given `"as": "scan"` (a phone photo of a paper map, say: see [Scans with no coordinates](#rasters)). | | LiDAR point clouds | `.las`, `.laz` (COPC too) | Add Data, drop the file, upload, or From URL… | LAS 1.0–1.4 (point formats 0–10) and LAZ, on desktop and web: points with `z`, `intensity`, `classification`, `return` and colour (`red`, `green`, `blue`), coloured by ASPRS class or elevation. An evenly spread sample is read once, at most 2 million points (500,000 in the web app); views use that sample, not the COPC spatial index. LAZ decompression reads at most the first 400 million points (40 million on the web), with a notice when capped. Held in the system of the file's WKT or GeoTIFF-key record, as the file holds its points; without one, coordinates are kept as longitude/latitude, with a notice when they aren't. Points with no place in longitude/latitude are kept and counted ([below](#places-with-no-longitudelatitude)); points with a coordinate that isn't a number are left out and counted. A local project keeps the path; uploads keep the file bytes. Remote files download whole. | | GeoPackage | `.gpkg` | Add Data, or upload in the web app | Local files and browser uploads add every feature table, up to 32 (with the rest counted in `skippedCount` and up to 100 named in `skipped`); `"layer"` picks one, and `info.fileLayers` lists them. Desktop byte uploads and downloads add the first table unless `"layer"` names another. Large local tables use their R-tree. Rows with no geometry (NULL or empty) are kept, with their attributes, in whole reads and exports; a read of an extent leaves them out, as they have no location. A table is read in its coordinate system: by its EPSG code, or, for a system without one (or with a code RustGIS doesn't know), by the WKT definition the file gives it (the WKT2 of GeoPackage 1.2's `definition_12_063` first, as the specification says, else `definition`). The definition also comes before the code when it gives another datum transformation than the code's, or describes another body's system. This holds on the desktop and in the web app alike (an azimuthal equidistant system opens on the desktop only, and the web app says so). Browser tables are scanned, testing each geometry header's envelope first; UTF-16 databases aren't read there. Raster tile tables aren't imported. A `BLOB` column other than the geometry is left out, with a notice counting such columns and naming the first 12. `DATE` and `DATETIME` columns are read as dates and date-times (ISO 8601 text, as GeoPackage stores them); a value that isn't one is empty and counted in a notice. | -| GeoParquet | `.parquet`, `.geoparquet` | Add Data, or upload in the web app | WKB geometry, with the CRS from the file's `geo` metadata. A binary geometry column is required; plain non-spatial Parquet tables and GeoArrow-native geometry encodings aren't read by this importer. Row groups are pruned by the bbox covering. Whole reads and exports retain rows with null geometry and their attributes; extent-filtered reads exclude them because they have no location. Snappy, gzip, LZ4 and zstd compression are read, in the browser too; Brotli isn't. Text, whole-number, floating-point and true/false columns become fields, as do decimals stored as 32- or 64-bit integers (up to 18 digits), read as floating-point numbers. Dates and times stored as 32- or 64-bit integers are read as those whole numbers (such as milliseconds since 1970). Other columns are left out: decimals stored as bytes (how many writers store every decimal), binary, lists, maps, structs, INT96 timestamps and further geometry columns. A notice gives how many were left out and names the first 12, each with its kind; another names the date and time columns with their unit. A row group whose text and geometry values, for the rows a read takes, decode to more than the decoded-column budget (512 MiB at least on the desktop, up to a quarter of the computer's memory and at most 3 GiB; 128 MiB in the browser) is refused with a message naming the group and the column: rewrite the file with smaller row groups. Only the rows a read takes count, so a view or a sample of such a file still reads; a page of more than the budget is refused too. | +| GeoParquet | `.parquet`, `.geoparquet` | Add Data, or upload in the web app | WKB geometry, with the CRS from the file's `geo` metadata. A binary geometry column is required; plain non-spatial Parquet tables and GeoArrow-native geometry encodings aren't read by this importer. Row groups are pruned by the bbox covering. Whole reads and exports retain rows with null geometry and their attributes; extent-filtered reads exclude them because they have no location. Snappy, gzip, LZ4 and zstd compression are read, in the browser too; Brotli isn't. Text, whole-number, floating-point and true/false columns become fields, as do decimals stored as 32- or 64-bit integers (up to 18 digits), read as floating-point numbers. Dates and times stored as 32- or 64-bit integers are read as those whole numbers (such as milliseconds since 1970). Other columns are left out: decimals stored as bytes (how many writers store every decimal), binary, lists, maps, structs, INT96 timestamps and further geometry columns. A notice gives how many were left out and names the first 12, each with its kind; another names the date and time columns with their unit. A row group whose text and geometry values, for the rows a read takes, decode to more than the decoded-column budget (512 MiB at least on the desktop, up to a quarter of the computer's memory and at most 3 GiB; 128 MiB in the browser) is refused with a message naming the group and the column: rewrite the file with smaller row groups. Only the rows a read takes count, so a view or a sample of such a file still reads, unless a page does not fit: a page of more than the budget is refused, and so is a DELTA_BYTE_ARRAY or DELTA_LENGTH_BYTE_ARRAY page whose length arrays (4 bytes a value, 8 for DELTA_BYTE_ARRAY) are more than the budget has left when it is fetched, even when a sample would take one short value from it. For a refusal that names the row group's budget, rewrite the file with smaller row groups; for one that names a page, rewrite it with smaller pages or another encoding for the text column (PLAIN or dictionary). | | FlatGeobuf | `.fgb` | Add Data, or upload | Read in place by its packed R-tree. Binary columns are left out, with a notice counting them and naming the first 12. Coordinates use the header's EPSG code, else its WKT, as a GeoPackage's system does: the WKT comes first when it gives another datum transformation than the code's, or another body's system, and a grid shift it gives beside the code isn't applied, with a notice. Another organization's code (an `ESRI` one, say) or a negative code without a WKT is read as longitude/latitude, with a notice. Another body's IAU code without a WKT is read with a notice, or refused when its coordinates are projected; with a WKT, the WKT is read (see coordinate systems of other bodies, below). | | Esri File Geodatabase | `.gdb` folder (desktop) | In Add Data pick a `.gdbtable` file inside it; or double-click the `.gdb` in the Browser, or drop the folder | The native reader loads up to 512 feature classes and tables, up to 2 GiB per table. Feature classes become layers and non-spatial tables standalone tables; dates are text. Coordinates use the EPSG/Esri code, else WKT; the WKT comes first when it gives another datum transformation than an EPSG code's, or another body's system. An Esri-only code still comes first, as ArcGIS keeps transformations apart from the system, with a notice when the WKT gives another one; a grid shift the WKT gives isn't applied, with a notice. `"layer"` picks one; `info.fileLayers` lists them. Binary fields, and geometry fields after the first, are left out, with a notice (by the table's name) counting them and naming the first 12. Multipatches become footprints with `z_min`, `z_max` and `height`; large or wall-only ones may use a convex hull. Curves become straight segments between their ends. Unreadable tables (compressed storage, raster fields or unsupported row indexes) are tried through GDAL when installed; otherwise they are named in a notice. | | Standalone tables | CSV, or any layer without geometry | Add Data | Listed under the map in Layers; join or relate them to layers. | From 4e1e80a19082fbd84ce02202b3bac7967ab3cca8 Mon Sep 17 00:00:00 2001 From: Li-Sheng Chou <142213184+choupeanut@users.noreply.github.com> Date: Sat, 28 Nov 2026 05:06:52 +0800 Subject: [PATCH 16/22] data: late-filtered traversal keeps no decoded geometry between passes, pairing tests across row groups, parquet_geometry_and_text_fields_share_one_budget kept (#2913) --- crates/data/src/source/parquet.rs | 19 +++++++++-- crates/data/src/source/tests.rs | 57 ++++++++++++++++++++++++++++--- docs/user-guide/data-formats.md | 2 +- 3 files changed, 69 insertions(+), 9 deletions(-) diff --git a/crates/data/src/source/parquet.rs b/crates/data/src/source/parquet.rs index c4dabcbc1d..0601cfbb9c 100644 --- a/crates/data/src/source/parquet.rs +++ b/crates/data/src/source/parquet.rs @@ -796,6 +796,9 @@ impl FeatureSource for ParquetSource { mine.push(i); } } + if mine.is_empty() { + continue; + } let attrs: Vec = self.field_cols.iter().map(|&c| read_values(rg.as_ref(), c, &chosen, &budget)).collect::>()?; if attrs.iter().any(|a| a.values.len() != mine.len()) { @@ -956,14 +959,23 @@ impl FeatureSource for ParquetSource { if let Some(c) = chosen.get_mut(r) { *c = true; } - found.push((r, geometry.map(|p| p.geometry))); + found.push((k, r)); + } + if found.is_empty() { + continue; } let attrs: Vec = self.field_cols.iter().map(|&c| read_values(rg.as_ref(), c, &chosen, &budget)).collect::>()?; if attrs.iter().any(|a| a.values.len() != found.len()) { return Err(DataError::Format(format!("GeoParquet: row group {g} has columns shorter than its rows"))); } - for (n, (r, geometry)) in found.into_iter().enumerate() { + // Decoded again for the rows found, so no decoded geometry outlives the first pass. + for (n, (k, r)) in found.into_iter().enumerate() { + let geometry = geoms + .get(k) + .and_then(|b| b.as_deref()) + .and_then(|bytes| wkb::decode(bytes).and_then(|geom| self.reproject.place(geom, &req))) + .map(|p| p.geometry); let values = attrs .iter() .enumerate() @@ -2057,7 +2069,8 @@ fn text_len(bytes: &[u8]) -> usize { /// of another type). Only the rows taken count, not the /// column chunk's size; a page of more than the budget is refused, as the `parquet` crate makes /// room for a whole page. A column with DELTA_BYTE_ARRAY pages, whose values the decoder builds -/// one by one, or DELTA_LENGTH_BYTE_ARRAY pages, whose length arrays are made as a page is fetched, is read at the [`Pace`] its page size and the budget left allow. +/// one by one, or DELTA_LENGTH_BYTE_ARRAY pages, whose length arrays are made as a page is +/// fetched, is read at the [`Pace`] its page size and the budget left allow. fn read_binary( rg: &dyn RowGroupReader, col: usize, diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 2e88dc9427..4e12d376ce 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -5542,7 +5542,7 @@ fn parquet_late_view_charges_only_the_rows_it_keeps() { let mut ds = Dataset::new("pts", GeometryType::Point, vec![Field::new("label", FieldType::Text)]); for i in 0..20 { // Row 7 is the one point in the view (latitude 0); the others are at latitude 40. - let (lat, label) = if i == 7 { (0.0, "hit".to_string()) } else { (40.0, "x".repeat(1024)) }; + let (lat, label) = if i == 7 { (0.0, "hit7".to_string()) } else { (40.0, "x".repeat(1024)) }; ds.push(Some(Geometry::Point(Coord::new(-81.0, lat))), vec![Value::Text(label)]); } write_unbounded_view_fixture(&ds, &p); @@ -5551,7 +5551,7 @@ fn parquet_late_view_charges_only_the_rows_it_keeps() { let source = parquet::ParquetSource::open_path(&p, "pts").unwrap().with_decoded_bytes(8 << 10); let batch = source.read(&req).unwrap(); assert_eq!((batch.matched, batch.features.len()), (1, 1)); - assert_eq!((batch.features[0].id, &batch.features[0].attrs[0]), (8, &Value::Text("hit".into()))); + assert_eq!((batch.features[0].id, &batch.features[0].attrs[0]), (8, &Value::Text("hit7".into()))); let mut seen = Vec::new(); let batch = source .visit_chunks(view, 1 << 20, &mut |chunk| { @@ -5559,7 +5559,7 @@ fn parquet_late_view_charges_only_the_rows_it_keeps() { Ok(()) }) .unwrap(); - assert_eq!((batch.matched, seen), (1, vec![(8, Value::Text("hit".into()))])); + assert_eq!((batch.matched, seen), (1, vec![(8, Value::Text("hit7".into()))])); // Every row is in the view, and the sample keeps one: only its label is charged, and the read // is the one the default budget makes. let mut all = Dataset::new("pts", GeometryType::Point, vec![Field::new("label", FieldType::Text)]); @@ -5579,6 +5579,52 @@ fn parquet_late_view_charges_only_the_rows_it_keeps() { assert!(error.contains("decoded-column budget"), "{error}"); } +/// A late-filtered read and traversal pair each kept row with its own label and place, across row +/// groups, when the sample halves as it goes and when only some rows of a group are hits (#2913). +#[test] +fn parquet_late_view_pairs_rows_with_their_attributes_across_row_groups() { + let p = dir().join("decoded-late-pairs.parquet"); + let label = |i: usize| format!("L{i:03}"); + let mut ds = Dataset::new("pts", GeometryType::Point, vec![Field::new("label", FieldType::Text)]); + for i in 0..40usize { + // Every third row is in the view (latitude 0), the others are at latitude 40. + let lat = if i % 3 == 0 { 0.0 } else { 40.0 }; + ds.push(Some(Geometry::Point(Coord::new(-81.0 + i as f64 * 0.01, lat))), vec![Value::Text(label(i))]); + } + // Row groups of 10 rows, plain text. + write_encoded_parquet_fixture(&ds, &p, 10, false, FixturePages::default()); + let source = parquet::ParquetSource::open_path(&p, "pts").unwrap().with_decoded_bytes(1 << 20); + let view = Some(Extent::new(-120.0, -30.0, 10.0, 30.0)); + let hits: Vec = (0..40).filter(|i| i % 3 == 0).collect(); + // Every hit is kept: its id is its row's, and its label and place are its row's too. + let all = source.read(&Request { extent: view, limit: 100, own: None }).unwrap(); + assert_eq!(all.matched, hits.len() as u64); + let ids: Vec = all.features.iter().map(|f| f.id).collect(); + assert_eq!(ids, hits.iter().map(|&i| i as u64 + 1).collect::>()); + for f in &all.features { + assert_eq!(f.attrs[0], Value::Text(label(f.id as usize - 1)), "id {}", f.id); + } + // A limit under the hits halves the sample while it crosses groups: what is kept is paired still. + for limit in [3, 4, 5] { + let sampled = source.read(&Request { extent: view, limit, own: None }).unwrap(); + assert_eq!(sampled.matched, hits.len() as u64, "limit {limit}"); + assert!(!sampled.features.is_empty() && sampled.features.len() <= limit, "limit {limit}"); + for f in &sampled.features { + assert_eq!(f.attrs[0], Value::Text(label(f.id as usize - 1)), "limit {limit} id {}", f.id); + assert!(hits.contains(&(f.id as usize - 1)), "limit {limit} id {}", f.id); + } + } + let mut seen = Vec::new(); + let batch = source + .visit_chunks(view, 1 << 20, &mut |chunk| { + seen.extend(chunk.into_iter().map(|f| (f.id, f.attrs[0].clone()))); + Ok(()) + }) + .unwrap(); + assert_eq!(batch.matched, hits.len() as u64); + assert_eq!(seen, hits.iter().map(|&i| (i as u64 + 1, Value::Text(label(i)))).collect::>()); +} + /// The geometry and every text field share one budget: each fits it alone, their sum does not, so /// the last field is the one refused (#2913). #[test] @@ -5623,8 +5669,9 @@ fn parquet_delta_length_pages_are_checked_against_what_the_pages_before_left() { write_encoded_parquet_fixture(&ds, &p, 5000, false, pages); let encodings = text_encodings(&p, "label"); assert!(encodings.contains(&::parquet::basic::Encoding::DELTA_LENGTH_BYTE_ARRAY), "{encodings:?}"); - // After the first value 3,000 bytes are left: less than the 4 bytes a value that the next - // page's array takes, though all the values together (4,500 bytes) fit what was left before. + // After the first value 3,000 bytes are left, fewer than the 4,000 the next page's array + // takes (4 bytes a value), though all the values together (4,500 bytes) fit what was left + // before it. let source = parquet::ParquetSource::open_path(&p, "pts").unwrap().with_decoded_bytes(geometry + 6000); let error = source.read(&whole).unwrap_err().to_string(); assert!(error.contains("bytes the decoded-column budget has left") && error.contains("column 'label'"), "v2 {v2}: {error}"); diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 02827eb4eb..fcca89a6ae 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -39,7 +39,7 @@ export names its feature. | Geotagged photos | `.jpg`, `.jpeg` | Add Data (several at once in the web app), drop them, upload, or `layer.addPhotos` with `"paths"` or a `"folder"` | JPEGs with a GPS position in their EXIF become points in the **Photos** layer (photos added one at a time join it): each with its `name`, `file`, `time` (when it was taken), `altitude`, `direction` (where the camera faced), `camera` and a `thumbnail` of at most 160 pixels, kept with the feature so the project needs no other file. Identify shows the thumbnail. Photos without a position are named in a notice and left out; a layer holds up to 2,000 photos. A JPEG is always read as a photo unless `layer.addData` or `layer.addDataBytes` is given `"as": "scan"` (a phone photo of a paper map, say: see [Scans with no coordinates](#rasters)). | | LiDAR point clouds | `.las`, `.laz` (COPC too) | Add Data, drop the file, upload, or From URL… | LAS 1.0–1.4 (point formats 0–10) and LAZ, on desktop and web: points with `z`, `intensity`, `classification`, `return` and colour (`red`, `green`, `blue`), coloured by ASPRS class or elevation. An evenly spread sample is read once, at most 2 million points (500,000 in the web app); views use that sample, not the COPC spatial index. LAZ decompression reads at most the first 400 million points (40 million on the web), with a notice when capped. Held in the system of the file's WKT or GeoTIFF-key record, as the file holds its points; without one, coordinates are kept as longitude/latitude, with a notice when they aren't. Points with no place in longitude/latitude are kept and counted ([below](#places-with-no-longitudelatitude)); points with a coordinate that isn't a number are left out and counted. A local project keeps the path; uploads keep the file bytes. Remote files download whole. | | GeoPackage | `.gpkg` | Add Data, or upload in the web app | Local files and browser uploads add every feature table, up to 32 (with the rest counted in `skippedCount` and up to 100 named in `skipped`); `"layer"` picks one, and `info.fileLayers` lists them. Desktop byte uploads and downloads add the first table unless `"layer"` names another. Large local tables use their R-tree. Rows with no geometry (NULL or empty) are kept, with their attributes, in whole reads and exports; a read of an extent leaves them out, as they have no location. A table is read in its coordinate system: by its EPSG code, or, for a system without one (or with a code RustGIS doesn't know), by the WKT definition the file gives it (the WKT2 of GeoPackage 1.2's `definition_12_063` first, as the specification says, else `definition`). The definition also comes before the code when it gives another datum transformation than the code's, or describes another body's system. This holds on the desktop and in the web app alike (an azimuthal equidistant system opens on the desktop only, and the web app says so). Browser tables are scanned, testing each geometry header's envelope first; UTF-16 databases aren't read there. Raster tile tables aren't imported. A `BLOB` column other than the geometry is left out, with a notice counting such columns and naming the first 12. `DATE` and `DATETIME` columns are read as dates and date-times (ISO 8601 text, as GeoPackage stores them); a value that isn't one is empty and counted in a notice. | -| GeoParquet | `.parquet`, `.geoparquet` | Add Data, or upload in the web app | WKB geometry, with the CRS from the file's `geo` metadata. A binary geometry column is required; plain non-spatial Parquet tables and GeoArrow-native geometry encodings aren't read by this importer. Row groups are pruned by the bbox covering. Whole reads and exports retain rows with null geometry and their attributes; extent-filtered reads exclude them because they have no location. Snappy, gzip, LZ4 and zstd compression are read, in the browser too; Brotli isn't. Text, whole-number, floating-point and true/false columns become fields, as do decimals stored as 32- or 64-bit integers (up to 18 digits), read as floating-point numbers. Dates and times stored as 32- or 64-bit integers are read as those whole numbers (such as milliseconds since 1970). Other columns are left out: decimals stored as bytes (how many writers store every decimal), binary, lists, maps, structs, INT96 timestamps and further geometry columns. A notice gives how many were left out and names the first 12, each with its kind; another names the date and time columns with their unit. A row group whose text and geometry values, for the rows a read takes, decode to more than the decoded-column budget (512 MiB at least on the desktop, up to a quarter of the computer's memory and at most 3 GiB; 128 MiB in the browser) is refused with a message naming the group and the column: rewrite the file with smaller row groups. Only the rows a read takes count, so a view or a sample of such a file still reads, unless a page does not fit: a page of more than the budget is refused, and so is a DELTA_BYTE_ARRAY or DELTA_LENGTH_BYTE_ARRAY page whose length arrays (4 bytes a value, 8 for DELTA_BYTE_ARRAY) are more than the budget has left when it is fetched, even when a sample would take one short value from it. For a refusal that names the row group's budget, rewrite the file with smaller row groups; for one that names a page, rewrite it with smaller pages or another encoding for the text column (PLAIN or dictionary). | +| GeoParquet | `.parquet`, `.geoparquet` | Add Data, or upload in the web app | WKB geometry, with the CRS from the file's `geo` metadata. A binary geometry column is required; plain non-spatial Parquet tables and GeoArrow-native geometry encodings aren't read by this importer. Row groups are pruned by the bbox covering. Whole reads and exports retain rows with null geometry and their attributes; extent-filtered reads exclude them because they have no location. Snappy, gzip, LZ4 and zstd compression are read, in the browser too; Brotli isn't. Text, whole-number, floating-point and true/false columns become fields, as do decimals stored as 32- or 64-bit integers (up to 18 digits), read as floating-point numbers. Dates and times stored as 32- or 64-bit integers are read as those whole numbers (such as milliseconds since 1970). Other columns are left out: decimals stored as bytes (how many writers store every decimal), binary, lists, maps, structs, INT96 timestamps and further geometry columns. A notice gives how many were left out and names the first 12, each with its kind; another names the date and time columns with their unit. A row group whose text and geometry values, for the rows a read takes, decode to more than the decoded-column budget (512 MiB at least on the desktop, up to a quarter of the computer's memory and at most 3 GiB; 128 MiB in the browser) is refused with a message naming the group and the column: rewrite the file with smaller row groups. Only the rows a read takes count for text, so a view or a sample of such a file still reads (a view tested on its geometry still charges the geometry of every candidate row, and the text only of the rows it keeps), unless a page does not fit: a page of more than the budget is refused, and so is a DELTA_BYTE_ARRAY or DELTA_LENGTH_BYTE_ARRAY page whose length arrays (4 bytes a value, 8 for DELTA_BYTE_ARRAY) are more than the budget has left when it is fetched, even when a sample would take one short value from it. For a refusal that names the row group's budget, rewrite the file with smaller row groups; for one that names a page, rewrite it with smaller pages or another encoding for the text column (PLAIN or dictionary). | | FlatGeobuf | `.fgb` | Add Data, or upload | Read in place by its packed R-tree. Binary columns are left out, with a notice counting them and naming the first 12. Coordinates use the header's EPSG code, else its WKT, as a GeoPackage's system does: the WKT comes first when it gives another datum transformation than the code's, or another body's system, and a grid shift it gives beside the code isn't applied, with a notice. Another organization's code (an `ESRI` one, say) or a negative code without a WKT is read as longitude/latitude, with a notice. Another body's IAU code without a WKT is read with a notice, or refused when its coordinates are projected; with a WKT, the WKT is read (see coordinate systems of other bodies, below). | | Esri File Geodatabase | `.gdb` folder (desktop) | In Add Data pick a `.gdbtable` file inside it; or double-click the `.gdb` in the Browser, or drop the folder | The native reader loads up to 512 feature classes and tables, up to 2 GiB per table. Feature classes become layers and non-spatial tables standalone tables; dates are text. Coordinates use the EPSG/Esri code, else WKT; the WKT comes first when it gives another datum transformation than an EPSG code's, or another body's system. An Esri-only code still comes first, as ArcGIS keeps transformations apart from the system, with a notice when the WKT gives another one; a grid shift the WKT gives isn't applied, with a notice. `"layer"` picks one; `info.fileLayers` lists them. Binary fields, and geometry fields after the first, are left out, with a notice (by the table's name) counting them and naming the first 12. Multipatches become footprints with `z_min`, `z_max` and `height`; large or wall-only ones may use a convex hull. Curves become straight segments between their ends. Unreadable tables (compressed storage, raster fields or unsupported row indexes) are tried through GDAL when installed; otherwise they are named in a notice. | | Standalone tables | CSV, or any layer without geometry | Add Data | Listed under the map in Layers; join or relate them to layers. | From cc6fb96b50d02d2993b2e79dab95f529ace5418b Mon Sep 17 00:00:00 2001 From: Li-Sheng Chou <142213184+choupeanut@users.noreply.github.com> Date: Sat, 28 Nov 2026 05:14:56 +0800 Subject: [PATCH 17/22] data: late-view pairing test also checks each kept row's place (#2913) --- crates/data/src/source/tests.rs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 4e12d376ce..ac5854a88f 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -5595,6 +5595,11 @@ fn parquet_late_view_pairs_rows_with_their_attributes_across_row_groups() { write_encoded_parquet_fixture(&ds, &p, 10, false, FixturePages::default()); let source = parquet::ParquetSource::open_path(&p, "pts").unwrap().with_decoded_bytes(1 << 20); let view = Some(Extent::new(-120.0, -30.0, 10.0, 30.0)); + // Row i is at longitude -81 + 0.01 i; the file is projected, so compare in longitude/latitude. + let at_row = |g: Option, id: u64| match lonlat_of(&source, g) { + Some(Geometry::Point(c)) => assert!((c.x - (-81.0 + 0.01 * (id as f64 - 1.0))).abs() < 1e-4, "id {id}: x {}", c.x), + other => panic!("id {id}: {other:?}"), + }; let hits: Vec = (0..40).filter(|i| i % 3 == 0).collect(); // Every hit is kept: its id is its row's, and its label and place are its row's too. let all = source.read(&Request { extent: view, limit: 100, own: None }).unwrap(); @@ -5603,6 +5608,7 @@ fn parquet_late_view_pairs_rows_with_their_attributes_across_row_groups() { assert_eq!(ids, hits.iter().map(|&i| i as u64 + 1).collect::>()); for f in &all.features { assert_eq!(f.attrs[0], Value::Text(label(f.id as usize - 1)), "id {}", f.id); + at_row(f.geometry.clone(), f.id); } // A limit under the hits halves the sample while it crosses groups: what is kept is paired still. for limit in [3, 4, 5] { @@ -5612,16 +5618,21 @@ fn parquet_late_view_pairs_rows_with_their_attributes_across_row_groups() { for f in &sampled.features { assert_eq!(f.attrs[0], Value::Text(label(f.id as usize - 1)), "limit {limit} id {}", f.id); assert!(hits.contains(&(f.id as usize - 1)), "limit {limit} id {}", f.id); + at_row(f.geometry.clone(), f.id); } } let mut seen = Vec::new(); let batch = source .visit_chunks(view, 1 << 20, &mut |chunk| { - seen.extend(chunk.into_iter().map(|f| (f.id, f.attrs[0].clone()))); + seen.extend(chunk.into_iter().map(|f| (f.id, f.attrs[0].clone(), f.geometry))); Ok(()) }) .unwrap(); assert_eq!(batch.matched, hits.len() as u64); + for (id, _, geometry) in &seen { + at_row(geometry.clone(), *id); + } + let seen: Vec<_> = seen.into_iter().map(|(id, label, _)| (id, label)).collect(); assert_eq!(seen, hits.iter().map(|&i| (i as u64 + 1, Value::Text(label(i)))).collect::>()); } From 5078304e5ddfc8a88423c6f29fb5ee96805f1fb3 Mon Sep 17 00:00:00 2001 From: Li-Sheng Chou <142213184+choupeanut@users.noreply.github.com> Date: Sat, 28 Nov 2026 06:30:49 +0800 Subject: [PATCH 18/22] data: refuse undeclared DELTA_LENGTH_BYTE_ARRAY pages like undeclared DELTA_BYTE_ARRAY ones (#2913) --- crates/data/src/source/parquet.rs | 32 +++++++++++++++++++++++-------- 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/crates/data/src/source/parquet.rs b/crates/data/src/source/parquet.rs index 0601cfbb9c..192d60eb5c 100644 --- a/crates/data/src/source/parquet.rs +++ b/crates/data/src/source/parquet.rs @@ -1180,7 +1180,7 @@ fn column_reader_within(rg: &dyn RowGroupReader, col: usize, limit: u64) -> Resu limit, // A footer that gives no size, or a negative one, bounds a page by the limit alone. chunk_bytes: u64::try_from(chunk.uncompressed_size()).ok().filter(|&n| n > 0), - delta_declared: chunk.encodings().any(|e| e == Encoding::DELTA_BYTE_ARRAY), + delta_declared: chunk.encodings().any(|e| matches!(e, Encoding::DELTA_BYTE_ARRAY | Encoding::DELTA_LENGTH_BYTE_ARRAY)), max_def: desc.max_def_level(), max_rep: desc.max_rep_level(), chunk_values: u64::try_from(chunk.num_values()).ok().filter(|&n| n > 0).unwrap_or(u64::MAX), @@ -1289,7 +1289,7 @@ impl Pace<'_> { /// A column's pages, a dictionary page refused when it says it holds more values than its bytes /// can: the `parquet` crate makes room for the count it is told before decoding any (a few bytes /// of header can ask for tens of gigabytes). A page bigger than the column chunk it belongs to or -/// than `limit`, and a data page in the DELTA_BYTE_ARRAY encoding that the chunk doesn't list, are +/// than `limit`, and a data page in the DELTA_BYTE_ARRAY or DELTA_LENGTH_BYTE_ARRAY encoding that the chunk doesn't list, are /// refused too: the pace of [`read_binary`] rests on both. The size is checked once the crate has /// the page; a header asking for more than the file holds is still allocated by the crate first. struct CheckedPages { @@ -1300,7 +1300,7 @@ struct CheckedPages { limit: u64, /// The bytes the column chunk's footer says its pages hold decoded, when it says. chunk_bytes: Option, - /// The footer lists the DELTA_BYTE_ARRAY encoding for the chunk. + /// The footer lists the DELTA_BYTE_ARRAY or DELTA_LENGTH_BYTE_ARRAY encoding for the chunk. delta_declared: bool, /// The most levels the column's values have, for a version 1 page's level streams. max_def: i16, @@ -1508,12 +1508,13 @@ impl parquet::column::page::PageReader for CheckedPages { ))); } if !self.delta_declared - && let parquet::column::page::Page::DataPage { encoding: Encoding::DELTA_BYTE_ARRAY, .. } - | parquet::column::page::Page::DataPageV2 { encoding: Encoding::DELTA_BYTE_ARRAY, .. } = page + && let parquet::column::page::Page::DataPage { encoding, .. } | parquet::column::page::Page::DataPageV2 { encoding, .. } = + page + && matches!(encoding, Encoding::DELTA_BYTE_ARRAY | Encoding::DELTA_LENGTH_BYTE_ARRAY) { - return Err(parquet::errors::ParquetError::General( - "a page uses the DELTA_BYTE_ARRAY encoding, which its column chunk doesn't list".into(), - )); + return Err(parquet::errors::ParquetError::General(format!( + "a page uses the {encoding} encoding, which its column chunk doesn't list" + ))); } self.check_delta(page)?; if let parquet::column::page::Page::DataPage { num_values, .. } | parquet::column::page::Page::DataPageV2 { num_values, .. } = @@ -2805,6 +2806,21 @@ mod tests { } } + /// A DELTA_LENGTH_BYTE_ARRAY page, like a DELTA_BYTE_ARRAY one, must be in the chunk's list: the + /// pace is only on for a column that lists one, so an unlisted page would be checked against a + /// budget the values before it have not been charged to. + #[test] + fn checked_pages_refuse_an_undeclared_delta_length_page() { + let mut sound = delta_flat(3, 4); + sound.extend_from_slice(b"ababab"); + for v2 in [false, true] { + let page = || delta_page(0, sound.clone(), 3, Encoding::DELTA_LENGTH_BYTE_ARRAY, v2); + let error = checked(page(), Some(100), u64::MAX, false).unwrap_err().to_string(); + assert!(error.contains("the DELTA_LENGTH_BYTE_ARRAY encoding, which its column chunk doesn't list"), "v2 {v2}: {error}"); + assert!(checked(page(), Some(100), u64::MAX, true).unwrap().is_some(), "v2 {v2}"); + } + } + /// A data page tells the pace its size and its values. #[test] fn checked_pages_note_the_data_page_they_hand_over() { From 95ed66922230663c2ee6a2dec4378a5027b3e620 Mon Sep 17 00:00:00 2001 From: Li-Sheng Chou <142213184+choupeanut@users.noreply.github.com> Date: Sat, 28 Nov 2026 07:27:58 +0800 Subject: [PATCH 19/22] data: refuse a delta page whose own encoding the chunk doesn't list (#2913) --- crates/data/src/source/parquet.rs | 68 ++++++++++++++++++++++++------- 1 file changed, 54 insertions(+), 14 deletions(-) diff --git a/crates/data/src/source/parquet.rs b/crates/data/src/source/parquet.rs index 192d60eb5c..8a9ceaabc7 100644 --- a/crates/data/src/source/parquet.rs +++ b/crates/data/src/source/parquet.rs @@ -1180,7 +1180,7 @@ fn column_reader_within(rg: &dyn RowGroupReader, col: usize, limit: u64) -> Resu limit, // A footer that gives no size, or a negative one, bounds a page by the limit alone. chunk_bytes: u64::try_from(chunk.uncompressed_size()).ok().filter(|&n| n > 0), - delta_declared: chunk.encodings().any(|e| matches!(e, Encoding::DELTA_BYTE_ARRAY | Encoding::DELTA_LENGTH_BYTE_ARRAY)), + delta_listed: [Encoding::DELTA_BYTE_ARRAY, Encoding::DELTA_LENGTH_BYTE_ARRAY].map(|listed| chunk.encodings().any(|e| e == listed)), max_def: desc.max_def_level(), max_rep: desc.max_rep_level(), chunk_values: u64::try_from(chunk.num_values()).ok().filter(|&n| n > 0).unwrap_or(u64::MAX), @@ -1289,7 +1289,7 @@ impl Pace<'_> { /// A column's pages, a dictionary page refused when it says it holds more values than its bytes /// can: the `parquet` crate makes room for the count it is told before decoding any (a few bytes /// of header can ask for tens of gigabytes). A page bigger than the column chunk it belongs to or -/// than `limit`, and a data page in the DELTA_BYTE_ARRAY or DELTA_LENGTH_BYTE_ARRAY encoding that the chunk doesn't list, are +/// than `limit`, and a data page in the DELTA_BYTE_ARRAY or DELTA_LENGTH_BYTE_ARRAY encoding that the chunk doesn't list (each encoding on its own), are /// refused too: the pace of [`read_binary`] rests on both. The size is checked once the crate has /// the page; a header asking for more than the file holds is still allocated by the crate first. struct CheckedPages { @@ -1300,8 +1300,8 @@ struct CheckedPages { limit: u64, /// The bytes the column chunk's footer says its pages hold decoded, when it says. chunk_bytes: Option, - /// The footer lists the DELTA_BYTE_ARRAY or DELTA_LENGTH_BYTE_ARRAY encoding for the chunk. - delta_declared: bool, + /// Whether the footer lists the DELTA_BYTE_ARRAY, and the DELTA_LENGTH_BYTE_ARRAY, encoding for the chunk. + delta_listed: [bool; 2], /// The most levels the column's values have, for a version 1 page's level streams. max_def: i16, max_rep: i16, @@ -1507,10 +1507,9 @@ impl parquet::column::page::PageReader for CheckedPages { self.limit ))); } - if !self.delta_declared - && let parquet::column::page::Page::DataPage { encoding, .. } | parquet::column::page::Page::DataPageV2 { encoding, .. } = - page - && matches!(encoding, Encoding::DELTA_BYTE_ARRAY | Encoding::DELTA_LENGTH_BYTE_ARRAY) + if let parquet::column::page::Page::DataPage { encoding, .. } | parquet::column::page::Page::DataPageV2 { encoding, .. } = page + && let Some(at) = [Encoding::DELTA_BYTE_ARRAY, Encoding::DELTA_LENGTH_BYTE_ARRAY].iter().position(|e| e == encoding) + && !self.delta_listed.get(at).copied().unwrap_or(false) { return Err(parquet::errors::ParquetError::General(format!( "a page uses the {encoding} encoding, which its column chunk doesn't list" @@ -1521,7 +1520,7 @@ impl parquet::column::page::PageReader for CheckedPages { page { #[cfg(test)] - if self.delta_declared { + if self.delta_listed.contains(&true) { DELTA_PAGES.with(|pages| pages.set(pages.get() + 1)); } self.note.page.store(len, Ordering::Relaxed); @@ -2756,7 +2755,7 @@ mod tests { bits: 32, limit, chunk_bytes, - delta_declared, + delta_listed: [delta_declared; 2], max_def: 0, max_rep: 0, chunk_values: u64::MAX, @@ -2821,6 +2820,47 @@ mod tests { } } + /// `page` through [`CheckedPages`] of a chunk whose footer lists exactly `listed` among the encodings. + fn checked_listing(page: Page, listed: &[Encoding]) -> parquet::errors::Result> { + CheckedPages { + pages: Box::new(Pages(vec![page].into_iter())), + bits: 32, + limit: u64::MAX, + chunk_bytes: Some(100), + delta_listed: [Encoding::DELTA_BYTE_ARRAY, Encoding::DELTA_LENGTH_BYTE_ARRAY].map(|e| listed.contains(&e)), + max_def: 0, + max_rep: 0, + chunk_values: u64::MAX, + note: Arc::new(PageNote::default()), + } + .get_next_page() + } + + /// The page's own encoding must be in the chunk's list: a chunk that lists one delta encoding + /// doesn't make a page in the other one declared. + #[test] + fn checked_pages_refuse_a_delta_page_of_the_other_delta_encoding() { + let mut flat = delta_flat(3, 4); + flat.extend_from_slice(b"ababab"); + let mut both = delta_flat(3, 0); + both.extend(delta_flat(3, 4)); + both.extend_from_slice(b"ababab"); + for v2 in [false, true] { + let length = || delta_page(0, flat.clone(), 3, Encoding::DELTA_LENGTH_BYTE_ARRAY, v2); + let prefixed = || delta_page(0, both.clone(), 3, Encoding::DELTA_BYTE_ARRAY, v2); + let error = checked_listing(length(), &[Encoding::DELTA_BYTE_ARRAY]).unwrap_err().to_string(); + assert!(error.contains("the DELTA_LENGTH_BYTE_ARRAY encoding, which its column chunk doesn't list"), "v2 {v2}: {error}"); + let error = checked_listing(prefixed(), &[Encoding::DELTA_LENGTH_BYTE_ARRAY]).unwrap_err().to_string(); + assert!(error.contains("the DELTA_BYTE_ARRAY encoding, which its column chunk doesn't list"), "v2 {v2}: {error}"); + assert!(checked_listing(length(), &[Encoding::DELTA_LENGTH_BYTE_ARRAY]).unwrap().is_some(), "v2 {v2}"); + assert!(checked_listing(prefixed(), &[Encoding::DELTA_BYTE_ARRAY]).unwrap().is_some(), "v2 {v2}"); + assert!( + checked_listing(length(), &[Encoding::DELTA_BYTE_ARRAY, Encoding::DELTA_LENGTH_BYTE_ARRAY]).unwrap().is_some(), + "v2 {v2}" + ); + } + } + /// A data page tells the pace its size and its values. #[test] fn checked_pages_note_the_data_page_they_hand_over() { @@ -2831,7 +2871,7 @@ mod tests { bits: 32, limit: u64::MAX, chunk_bytes: None, - delta_declared: false, + delta_listed: [false; 2], max_def: 0, max_rep: 0, chunk_values: u64::MAX, @@ -2940,7 +2980,7 @@ mod tests { bits: 32, limit: u64::MAX, chunk_bytes: None, - delta_declared: true, + delta_listed: [true; 2], max_def, max_rep: 0, chunk_values, @@ -3173,7 +3213,7 @@ mod tests { bits: 32, limit: u64::MAX, chunk_bytes: None, - delta_declared: true, + delta_listed: [true; 2], max_def: 1, max_rep: 0, chunk_values: u64::MAX, @@ -3220,7 +3260,7 @@ mod tests { bits: 32, limit: u64::MAX, chunk_bytes: None, - delta_declared: true, + delta_listed: [true; 2], max_def: 0, max_rep: 0, chunk_values: u64::MAX, From 99025c6ae41a3cd900dfc8245551159ba34b1fe5 Mon Sep 17 00:00:00 2001 From: Li-Sheng Chou <142213184+choupeanut@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:45:42 +0800 Subject: [PATCH 20/22] data: late view finds a group's kept rows by id order, not by rescanning the sample (#2913) --- crates/data/src/source/parquet.rs | 56 +++++++++++++++++++++++++------ 1 file changed, 46 insertions(+), 10 deletions(-) diff --git a/crates/data/src/source/parquet.rs b/crates/data/src/source/parquet.rs index 8a9ceaabc7..d2a6407074 100644 --- a/crates/data/src/source/parquet.rs +++ b/crates/data/src/source/parquet.rs @@ -786,16 +786,7 @@ impl FeatureSource for ParquetSource { }); } // The rows of this group the sample still holds, in order (it may have dropped some). - let mut chosen = vec![false; take.len()]; - let mut mine = Vec::new(); - for (i, f) in sample.items.iter().enumerate() { - if let Some(r) = f.id.checked_sub(base.saturating_add(1)).and_then(|r| usize::try_from(r).ok()) - && let Some(c) = chosen.get_mut(r) - { - *c = true; - mine.push(i); - } - } + let (chosen, mine) = rows_held(&sample.items, |f| f.id, base, take.len()); if mine.is_empty() { continue; } @@ -2693,6 +2684,23 @@ pub(crate) fn write_features( Ok((w.into_inner().map_err(err)?, unfit_counts, layout.notes(fields, ""))) } +/// The rows of a group (ids from `base + 1`, `rows` of them) that the sample still holds, and +/// where in the sample each one sits. The sample is in id order (groups are read in order and +/// the sampler keeps order), so the search starts at the group's first possible id and stops at its last. +fn rows_held(items: &[T], id: impl Fn(&T) -> u64, base: u64, rows: usize) -> (Vec, Vec) { + let mut chosen = vec![false; rows]; + let mut mine = Vec::new(); + let first = base.saturating_add(1); + let from = items.partition_point(|f| id(f) < first); + for (i, f) in items.iter().enumerate().skip(from) { + let Some(r) = id(f).checked_sub(first).and_then(|r| usize::try_from(r).ok()) else { continue }; + let Some(c) = chosen.get_mut(r) else { break }; + *c = true; + mine.push(i); + } + (chosen, mine) +} + #[cfg(test)] mod tests { use super::*; @@ -2836,6 +2844,34 @@ mod tests { .get_next_page() } + /// A late-filtered read looks only at the sample's rows from the current group on, not at every + /// row kept from earlier groups: the work stays linear in the groups. + #[test] + fn rows_held_inspects_only_the_current_groups_suffix() { + use std::cell::Cell; + let groups = 2_000u64; + let per = 4u64; + let mut items: Vec = Vec::new(); + let looked = Cell::new(0u64); + for g in 0..groups { + let base = g * per; + items.extend((1..=per).map(|r| base + r)); + let (chosen, mine) = rows_held( + &items, + |&id| { + looked.set(looked.get() + 1); + id + }, + base, + per as usize, + ); + assert_eq!(chosen, vec![true; per as usize]); + assert_eq!(mine, (items.len() - per as usize..items.len()).collect::>()); + } + // Binary search plus the suffix: far below the quadratic groups * rows / 2 of a full scan. + assert!(looked.get() < groups * (per + 16), "inspected {} entries", looked.get()); + } + /// The page's own encoding must be in the chunk's list: a chunk that lists one delta encoding /// doesn't make a page in the other one declared. #[test] From c6495f31a85e0be56d50e6b722eadc901c8baee8 Mon Sep 17 00:00:00 2001 From: Li-Sheng Chou <142213184+choupeanut@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:33:19 +0800 Subject: [PATCH 21/22] data: charge TIME text, stop reads after the last wanted row, check cancel in the traversal's second pass, test projected extents by geometry before decoding labels (#2913) --- crates/data/src/source/parquet.rs | 63 ++++++++++++++++++- crates/data/src/source/tests.rs | 101 +++++++++++++++++++++++++++++- 2 files changed, 160 insertions(+), 4 deletions(-) diff --git a/crates/data/src/source/parquet.rs b/crates/data/src/source/parquet.rs index d2a6407074..23e075cc04 100644 --- a/crates/data/src/source/parquet.rs +++ b/crates/data/src/source/parquet.rs @@ -711,7 +711,11 @@ impl FeatureSource for ParquetSource { // Without a covering, or with nullable inferred bounds, test geometry before sampling // for the whole request. Otherwise the match count is known, and every `step`-th is read. // An extent the file's system couldn't bound (`native` is `None`) is tested on every row. - let late = req.extent.is_some() && (native.is_none() || groups.iter().any(|&g| self.needs_geometry_filter(md, g))); + // So is one whose native rectangle differs from the extent (a projected file): it holds + // places the extent doesn't, so the covering alone doesn't say which rows match, and + // their attributes aren't read (and charged) before the geometry has. + let late = + req.extent.is_some() && (native.is_none() || native != req.extent || groups.iter().any(|&g| self.needs_geometry_filter(md, g))); let mut sample = if late { Sampler::new(limit) } else { Sampler::with_total(limit, matched) }; // The rows of each group the sample takes, decided before anything else is read. let takes: Vec> = groups @@ -962,6 +966,7 @@ impl FeatureSource for ParquetSource { } // Decoded again for the rows found, so no decoded geometry outlives the first pass. for (n, (k, r)) in found.into_iter().enumerate() { + crate::progress::check()?; let geometry = geoms .get(k) .and_then(|b| b.as_deref()) @@ -1713,6 +1718,27 @@ fn clock_kind(c: &ColumnDescPtr) -> Option<(parquet::basic::TimeUnit, bool)> { } } +/// The bytes [`clock_value`] makes of `n` as text, counted without building it; `None` for a +/// value that is no time of day. +fn clock_len(n: i64, (unit, utc): (parquet::basic::TimeUnit, bool)) -> Option { + use parquet::basic::TimeUnit; + let (scale, width): (i128, usize) = match unit { + TimeUnit::MILLIS => (1_000_000, 3), + TimeUnit::MICROS => (1000, 6), + TimeUnit::NANOS => (1, 9), + }; + let ns = i128::from(n) * scale; + if !(0..86_400_000_000_000).contains(&ns) { + return None; + } + // "hh:mm:ss", then ".Z" at a fixed width, or the fraction without its trailing zeros. + Some(match (utc, ns % 1_000_000_000) { + (true, _) => 8 + 1 + width + 1, + (false, 0) => 8, + (false, fraction) => 8 + 1 + format!("{fraction:09}").trim_end_matches('0').len(), + }) +} + /// A time without a day is text rather than a date. Its fractional precision is retained. fn clock_value(n: i64, (unit, utc): (parquet::basic::TimeUnit, bool)) -> Value { use parquet::basic::TimeUnit; @@ -1817,7 +1843,7 @@ fn read_column_with( let mut defs = Vec::new(); let mut values = Vec::new(); let mut i = 0; - while i < take.len() { + while i < take.len() && out.len() < wanted { let on = take.get(i).copied().unwrap_or(false); let mut j = i; while j < take.len() && take.get(j).copied().unwrap_or(false) == on { @@ -1932,11 +1958,24 @@ fn read_values(rg: &dyn RowGroupReader, col: usize, take: &[bool], budget: &Budg let clock = clock_kind(&desc); let temporal = matches!(field_type(&desc), Some(FieldType::Date | FieldType::DateTime)); let mut flags = Vec::new(); + // The first refusal of a time's text, which the budget couldn't take. + let mut refused: Option = None; + let name = rg.metadata().column(col).column_path().string(); let mut int = |v: Option| { flags.push(0u8); if let Some(unit) = clock { return v .map(|n| { + // Charged by its length before the text is made; a time that is none is not. + if refused.is_some() { + return Value::Null; + } + if let Some(len) = clock_len(n, unit) + && let Err(e) = budget.charge(len, &name) + { + refused = Some(e); + return Value::Null; + } let value = clock_value(n, unit); if value.is_null() && let Some(flag) = flags.last_mut() @@ -2015,6 +2054,9 @@ fn read_values(rg: &dyn RowGroupReader, col: usize, take: &[bool], budget: &Budg _ => Vec::new(), } }; + if let Some(e) = refused { + return Err(e); + } Ok(ColumnValues { values, flags }) } @@ -2928,6 +2970,23 @@ mod tests { } } + /// The length of a time's text as `clock_value` makes it, and none for one it can't. + #[test] + fn clock_len_is_the_length_of_the_time_text() { + use parquet::basic::TimeUnit; + for unit in [TimeUnit::MILLIS, TimeUnit::MICROS, TimeUnit::NANOS] { + for utc in [true, false] { + for n in [-1, 0, 1, 500, 1000, 1_500, 86_399_999, 3_723_004_005_006, 86_399_999_999_999, 86_400_000_000_000, i64::MAX] { + let want = match clock_value(n, (unit, utc)) { + Value::Text(t) => Some(t.len()), + _ => None, + }; + assert_eq!(clock_len(n, (unit, utc)), want, "{n} {utc}"); + } + } + } + } + /// A DELTA_BINARY_PACKED stream of `count` values, written as the format lays it out: blocks of /// 128 values in 4 miniblocks of 32, whose bit widths cycle through `widths` (a miniblock past /// the last value has width 0 and no bytes), the packed bytes all zero. diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index ac5854a88f..bde623b951 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -5361,12 +5361,109 @@ fn parquet_sampled_read_skips_a_long_run_in_one_call() { write_projected_parquet_fixture(&ds, &p, 30_000, false); let source = parquet::ParquetSource::open_path(&p, "pts").unwrap(); parquet::reset_largest_skip(); - let one = Request { extent: None, limit: 1, own: None }; + // The last row alone, which the covering finds. + let one = Request { extent: Some(Extent::new(-81.00005, -0.1, -80.9999, 0.1)), limit: 1, own: None }; assert_eq!(source.read(&one).unwrap().features.len(), 1); - // Most of the 30,000 rows aren't taken: one run of well over a batch of 8,192. + // Most of the 30,000 rows aren't taken: one run before it of well over a batch of 8,192. assert!(parquet::largest_skip() > 8192, "{}", parquet::largest_skip()); } +/// A read stops at its last wanted row: the run of rows after it is not skipped, so no page past +/// the last one taken is fetched (#2913). +#[test] +fn parquet_selection_read_stops_after_the_last_wanted_row() { + let p = dir().join("selection-trailing.parquet"); + let mut ds = Dataset::new("pts", GeometryType::Point, vec![]); + for i in 0..30_000 { + ds.push(Some(Geometry::Point(Coord::new(-82.0 + f64::from(i) / 30_000.0, 0.0))), vec![]); + } + write_projected_parquet_fixture(&ds, &p, 30_000, false); + let source = parquet::ParquetSource::open_path(&p, "pts").unwrap(); + // The first row alone: nothing before it, and everything after it is left unread. + parquet::reset_largest_skip(); + let first = Request { extent: Some(Extent::new(-82.0001, -0.1, -81.99999, 0.1)), limit: 10, own: None }; + assert_eq!(source.read(&first).unwrap().features.len(), 1); + assert_eq!(parquet::largest_skip(), 0, "a run after the last wanted row was skipped"); +} + +/// An extent traversal stops when asked in its second pass too, whose rows are handed to the +/// visitor, as it does in the first (#2913). +#[test] +fn parquet_extent_traversal_checks_cancel_in_its_second_pass() { + let p = dir().join("traversal-cancel.parquet"); + let mut ds = Dataset::new("pts", GeometryType::Point, vec![]); + for i in 0..4 { + ds.push(Some(Geometry::Point(Coord::new(-81.0 + f64::from(i) * 0.01, 0.0))), vec![]); + } + write_projected_parquet_fixture(&ds, &p, 100, false); + let source = parquet::ParquetSource::open_path(&p, "pts").unwrap(); + let view = Some(Extent::new(-84.0, -1.0, -78.0, 1.0)); + // Asked once the first pass has counted its 4 rows, with one group, so no later check sees it. + let probe = crate::progress::tests::Counted::cancelling_after(4); + let _guard = crate::progress::install(Some(probe.clone())); + let mut seen = 0; + let result = source.visit_chunks(view, 1 << 20, &mut |chunk| { + seen += chunk.len(); + Ok(()) + }); + assert!(matches!(result, Err(DataError::Cancelled)), "{result:?}"); + assert_eq!(seen, 0); +} + +/// A projected file's search rectangle holds points outside the extent; their labels are not +/// charged, only those of the points the extent holds (#2913). +#[test] +fn parquet_projected_extent_read_charges_only_the_points_in_the_extent() { + let p = dir().join("rectangle-labels.parquet"); + let mut ds = Dataset::new("pts", GeometryType::Point, vec![Field::new("label", FieldType::Text)]); + // In the extent, and a point in its native rectangle (the box of its converted corners) but + // east of the extent's edge at this latitude. + ds.push(Some(Geometry::Point(Coord::new(-79.0, 1.0))), vec![Value::Text("a".repeat(600))]); + ds.push(Some(Geometry::Point(Coord::new(-76.0, 59.0))), vec![Value::Text("b".repeat(600))]); + // A page to each value, so the budget is about what is taken, not what a page holds. + write_encoded_parquet_fixture(&ds, &p, 100, false, FixturePages { page_bytes: Some(100), ..FixturePages::default() }); + let source = parquet::ParquetSource::open_path(&p, "pts").unwrap().with_decoded_bytes(1 << 10); + let req = Request { extent: Some(Extent::new(-84.0, 0.0, -78.0, 60.0)), limit: 100, own: None }; + let batch = source.read(&req).unwrap(); + assert_eq!(batch.features.len(), 1); + assert_eq!(batch.features[0].attrs[0], Value::Text("a".repeat(600))); +} + +/// A time of day read as text is charged what its text takes, as other text is; a null or an +/// invalid one is not (#2913). +#[test] +fn parquet_time_text_is_charged_against_the_budget() { + use ::parquet::data_type::{ByteArray, ByteArrayType, Int64Type}; + use ::parquet::file::writer::SerializedFileWriter; + let schema = + ::parquet::schema::parser::parse_message_type("message m { REQUIRED BINARY geometry; OPTIONAL INT64 t (TIME(NANOS,true)); }") + .unwrap(); + let mut bytes = Vec::new(); + let mut w = SerializedFileWriter::new(&mut bytes, Arc::new(schema), Arc::default()).unwrap(); + let point = wkb::encode(&Geometry::Point(Coord::new(0.0, 0.0))); + assert_eq!(point.len(), 21); + let mut rg = w.next_row_group().unwrap(); + let mut col = rg.next_column().unwrap().unwrap(); + col.typed::() + .write_batch(&[ByteArray::from(point.clone()), ByteArray::from(point.clone()), ByteArray::from(point)], None, None) + .unwrap(); + col.close().unwrap(); + // Zero, a null and minus one (no such time of day): only the zero is text. + let mut col = rg.next_column().unwrap().unwrap(); + col.typed::().write_batch(&[0, -1], Some(&[1, 0, 1]), None).unwrap(); + col.close().unwrap(); + rg.close().unwrap(); + w.close().unwrap(); + let whole = Request { extent: None, limit: 100, own: None }; + // Three points of 21 bytes and "00:00:00.000000000Z" of 19. + let fits = parquet::ParquetSource::open_bytes(bytes.clone(), "m").unwrap().with_decoded_bytes(3 * 21 + 19); + let batch = fits.read(&whole).unwrap(); + assert_eq!(batch.features[0].attrs[0], Value::Text("00:00:00.000000000Z".into())); + let short = parquet::ParquetSource::open_bytes(bytes, "m").unwrap().with_decoded_bytes(3 * 21 + 18); + let error = short.read(&whole).unwrap_err().to_string(); + assert!(error.contains("decoded-column budget") && error.contains("column 't'"), "{error}"); +} + /// A sampled read of a DELTA_BYTE_ARRAY column passes over the pages it takes no row of without /// fetching them, as it does a column of another encoding, so the crate sets no decoder up for a /// page it only skips (its decoder sizes arrays from a count in the page) (#2913). From 1440fd691759888ee276896d8b54134925f06e74 Mon Sep 17 00:00:00 2001 From: Li-Sheng Chou <142213184+choupeanut@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:33:26 +0800 Subject: [PATCH 22/22] docs: say a single oversized GeoParquet geometry needs simplifying, not smaller row groups (#2913) --- docs/user-guide/data-formats.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index fcca89a6ae..9581907288 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -39,7 +39,7 @@ export names its feature. | Geotagged photos | `.jpg`, `.jpeg` | Add Data (several at once in the web app), drop them, upload, or `layer.addPhotos` with `"paths"` or a `"folder"` | JPEGs with a GPS position in their EXIF become points in the **Photos** layer (photos added one at a time join it): each with its `name`, `file`, `time` (when it was taken), `altitude`, `direction` (where the camera faced), `camera` and a `thumbnail` of at most 160 pixels, kept with the feature so the project needs no other file. Identify shows the thumbnail. Photos without a position are named in a notice and left out; a layer holds up to 2,000 photos. A JPEG is always read as a photo unless `layer.addData` or `layer.addDataBytes` is given `"as": "scan"` (a phone photo of a paper map, say: see [Scans with no coordinates](#rasters)). | | LiDAR point clouds | `.las`, `.laz` (COPC too) | Add Data, drop the file, upload, or From URL… | LAS 1.0–1.4 (point formats 0–10) and LAZ, on desktop and web: points with `z`, `intensity`, `classification`, `return` and colour (`red`, `green`, `blue`), coloured by ASPRS class or elevation. An evenly spread sample is read once, at most 2 million points (500,000 in the web app); views use that sample, not the COPC spatial index. LAZ decompression reads at most the first 400 million points (40 million on the web), with a notice when capped. Held in the system of the file's WKT or GeoTIFF-key record, as the file holds its points; without one, coordinates are kept as longitude/latitude, with a notice when they aren't. Points with no place in longitude/latitude are kept and counted ([below](#places-with-no-longitudelatitude)); points with a coordinate that isn't a number are left out and counted. A local project keeps the path; uploads keep the file bytes. Remote files download whole. | | GeoPackage | `.gpkg` | Add Data, or upload in the web app | Local files and browser uploads add every feature table, up to 32 (with the rest counted in `skippedCount` and up to 100 named in `skipped`); `"layer"` picks one, and `info.fileLayers` lists them. Desktop byte uploads and downloads add the first table unless `"layer"` names another. Large local tables use their R-tree. Rows with no geometry (NULL or empty) are kept, with their attributes, in whole reads and exports; a read of an extent leaves them out, as they have no location. A table is read in its coordinate system: by its EPSG code, or, for a system without one (or with a code RustGIS doesn't know), by the WKT definition the file gives it (the WKT2 of GeoPackage 1.2's `definition_12_063` first, as the specification says, else `definition`). The definition also comes before the code when it gives another datum transformation than the code's, or describes another body's system. This holds on the desktop and in the web app alike (an azimuthal equidistant system opens on the desktop only, and the web app says so). Browser tables are scanned, testing each geometry header's envelope first; UTF-16 databases aren't read there. Raster tile tables aren't imported. A `BLOB` column other than the geometry is left out, with a notice counting such columns and naming the first 12. `DATE` and `DATETIME` columns are read as dates and date-times (ISO 8601 text, as GeoPackage stores them); a value that isn't one is empty and counted in a notice. | -| GeoParquet | `.parquet`, `.geoparquet` | Add Data, or upload in the web app | WKB geometry, with the CRS from the file's `geo` metadata. A binary geometry column is required; plain non-spatial Parquet tables and GeoArrow-native geometry encodings aren't read by this importer. Row groups are pruned by the bbox covering. Whole reads and exports retain rows with null geometry and their attributes; extent-filtered reads exclude them because they have no location. Snappy, gzip, LZ4 and zstd compression are read, in the browser too; Brotli isn't. Text, whole-number, floating-point and true/false columns become fields, as do decimals stored as 32- or 64-bit integers (up to 18 digits), read as floating-point numbers. Dates and times stored as 32- or 64-bit integers are read as those whole numbers (such as milliseconds since 1970). Other columns are left out: decimals stored as bytes (how many writers store every decimal), binary, lists, maps, structs, INT96 timestamps and further geometry columns. A notice gives how many were left out and names the first 12, each with its kind; another names the date and time columns with their unit. A row group whose text and geometry values, for the rows a read takes, decode to more than the decoded-column budget (512 MiB at least on the desktop, up to a quarter of the computer's memory and at most 3 GiB; 128 MiB in the browser) is refused with a message naming the group and the column: rewrite the file with smaller row groups. Only the rows a read takes count for text, so a view or a sample of such a file still reads (a view tested on its geometry still charges the geometry of every candidate row, and the text only of the rows it keeps), unless a page does not fit: a page of more than the budget is refused, and so is a DELTA_BYTE_ARRAY or DELTA_LENGTH_BYTE_ARRAY page whose length arrays (4 bytes a value, 8 for DELTA_BYTE_ARRAY) are more than the budget has left when it is fetched, even when a sample would take one short value from it. For a refusal that names the row group's budget, rewrite the file with smaller row groups; for one that names a page, rewrite it with smaller pages or another encoding for the text column (PLAIN or dictionary). | +| GeoParquet | `.parquet`, `.geoparquet` | Add Data, or upload in the web app | WKB geometry, with the CRS from the file's `geo` metadata. A binary geometry column is required; plain non-spatial Parquet tables and GeoArrow-native geometry encodings aren't read by this importer. Row groups are pruned by the bbox covering. Whole reads and exports retain rows with null geometry and their attributes; extent-filtered reads exclude them because they have no location. Snappy, gzip, LZ4 and zstd compression are read, in the browser too; Brotli isn't. Text, whole-number, floating-point and true/false columns become fields, as do decimals stored as 32- or 64-bit integers (up to 18 digits), read as floating-point numbers. Dates and times stored as 32- or 64-bit integers are read as those whole numbers (such as milliseconds since 1970). Other columns are left out: decimals stored as bytes (how many writers store every decimal), binary, lists, maps, structs, INT96 timestamps and further geometry columns. A notice gives how many were left out and names the first 12, each with its kind; another names the date and time columns with their unit. A row group whose text (times of day read as text too) and geometry values, for the rows a read takes, decode to more than the decoded-column budget (512 MiB at least on the desktop, up to a quarter of the computer's memory and at most 3 GiB; 128 MiB in the browser) is refused with a message naming the group and the column: rewrite the file with smaller row groups. Only the rows a read takes count for text, so a view or a sample of such a file still reads (a view tested on its geometry still charges the geometry of every candidate row, and the text only of the rows it keeps), unless a page does not fit: a page of more than the budget is refused, and so is a DELTA_BYTE_ARRAY or DELTA_LENGTH_BYTE_ARRAY page whose length arrays (4 bytes a value, 8 for DELTA_BYTE_ARRAY) are more than the budget has left when it is fetched, even when a sample would take one short value from it. Where the values fit the budget one by one, a refusal that names the row group's budget is met by rewriting the file with smaller row groups, and one that names a page by rewriting it with smaller pages or another encoding for the text column (PLAIN or dictionary). A single WKB geometry (or text value) larger than the budget by itself is not: smaller row groups or pages can't split it, so simplify the geometry or split it into several features before writing the file. | | FlatGeobuf | `.fgb` | Add Data, or upload | Read in place by its packed R-tree. Binary columns are left out, with a notice counting them and naming the first 12. Coordinates use the header's EPSG code, else its WKT, as a GeoPackage's system does: the WKT comes first when it gives another datum transformation than the code's, or another body's system, and a grid shift it gives beside the code isn't applied, with a notice. Another organization's code (an `ESRI` one, say) or a negative code without a WKT is read as longitude/latitude, with a notice. Another body's IAU code without a WKT is read with a notice, or refused when its coordinates are projected; with a WKT, the WKT is read (see coordinate systems of other bodies, below). | | Esri File Geodatabase | `.gdb` folder (desktop) | In Add Data pick a `.gdbtable` file inside it; or double-click the `.gdb` in the Browser, or drop the folder | The native reader loads up to 512 feature classes and tables, up to 2 GiB per table. Feature classes become layers and non-spatial tables standalone tables; dates are text. Coordinates use the EPSG/Esri code, else WKT; the WKT comes first when it gives another datum transformation than an EPSG code's, or another body's system. An Esri-only code still comes first, as ArcGIS keeps transformations apart from the system, with a notice when the WKT gives another one; a grid shift the WKT gives isn't applied, with a notice. `"layer"` picks one; `info.fileLayers` lists them. Binary fields, and geometry fields after the first, are left out, with a notice (by the table's name) counting them and naming the first 12. Multipatches become footprints with `z_min`, `z_max` and `height`; large or wall-only ones may use a convex hull. Curves become straight segments between their ends. Unreadable tables (compressed storage, raster fields or unsupported row indexes) are tried through GDAL when installed; otherwise they are named in a notice. | | Standalone tables | CSV, or any layer without geometry | Add Data | Listed under the map in Layers; join or relate them to layers. |