mbutrovich commented on code in PR #11549: URL: https://github.com/apache/arrow-rs/pull/11549#discussion_r4447589753
########## parquet/src/arrow/bloom_filter.rs: ########## @@ -0,0 +1,1287 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Check Arrow arrays against Parquet bloom filters + +use arrow_array::builder::BooleanBuilder; +use arrow_array::cast::AsArray; +use arrow_array::types::{Float32Type, Float64Type, RunEndIndexType}; +use arrow_array::{Array, BooleanArray, RunArray, downcast_run_array}; +use arrow_buffer::{ArrowNativeType, BooleanBuffer}; +use arrow_schema::{DataType, Field, TimeUnit as ArrowTimeUnit}; + +use crate::arrow::arrow_writer::{ + FixedLenByteArrayVisitor, PrimitiveVisitor, visit_fixed_len_byte_array, visit_i32, visit_i64, +}; +use crate::arrow::schema::{arrow_to_parquet_type, parquet_to_arrow_field}; +use crate::basic::{ConvertedType, LogicalType, TimeUnit, Type as PhysicalType}; +use crate::bloom_filter::Sbbf; +use crate::data_type::AsBytes; +use crate::errors::{ParquetError, Result}; +use crate::schema::types::{ColumnDescriptor, Type}; + +/// A Parquet bloom filter ([`Sbbf`]) that can be checked with Arrow arrays +/// +/// [`ArrowWriter`] may store an Arrow value as a different Parquet value, and +/// the bloom filter holds the stored value, so [`Sbbf::check`] with the Arrow +/// value can report a value that is present as absent. [`ArrowSbbf::check`] +/// converts Arrow values in the same way as [`ArrowWriter`] before checking the +/// filter. +/// +/// ``` +/// # use std::sync::Arc; +/// # use bytes::Bytes; +/// # use arrow_array::{ArrayRef, Int8Array, RecordBatch}; +/// # use parquet::arrow::ArrowWriter; +/// # use parquet::arrow::bloom_filter::ArrowSbbf; +/// # use parquet::file::properties::{ReaderProperties, WriterProperties}; +/// # use parquet::file::reader::{FileReader, SerializedFileReader}; +/// # use parquet::file::serialized_reader::ReadOptionsBuilder; +/// let array: ArrayRef = Arc::new(Int8Array::from(vec![1, 2, 3])); +/// let batch = RecordBatch::try_from_iter([("c", array)]).unwrap(); +/// +/// let props = WriterProperties::builder() +/// .set_bloom_filter_enabled(true) +/// .build(); +/// let mut buffer = Vec::new(); +/// let mut writer = ArrowWriter::try_new(&mut buffer, batch.schema(), Some(props)).unwrap(); +/// writer.write(&batch).unwrap(); +/// writer.close().unwrap(); +/// +/// let options = ReadOptionsBuilder::new() +/// .with_reader_properties( +/// ReaderProperties::builder() +/// .set_read_bloom_filter(true) +/// .build(), +/// ) +/// .build(); +/// let reader = SerializedFileReader::new_with_options(Bytes::from(buffer), options).unwrap(); +/// let row_group = reader.get_row_group(0).unwrap(); +/// let sbbf = row_group.get_column_bloom_filter(0).unwrap(); +/// let column = reader.metadata().row_group(0).column(0).column_descr(); +/// +/// // The Int8 values were written as INT32, so checking an i8 misses them +/// assert!(!sbbf.check(&1_i8)); +/// +/// // Use the column's Arrow type, here Int8, from the file's Arrow schema +/// let arrow_type = batch.schema().field(0).data_type().clone(); +/// let sbbf = ArrowSbbf::try_new(sbbf, column, Some(arrow_type)).unwrap(); +/// let found = sbbf.check(&Int8Array::from(vec![1, 3, 4])).unwrap(); +/// assert_eq!(found, vec![Some(true), Some(true), Some(false)].into()); +/// ``` +/// +/// [`ArrowWriter`]: crate::arrow::ArrowWriter +#[derive(Debug, Clone)] +pub struct ArrowSbbf<'a> { + sbbf: &'a Sbbf, + /// The Arrow type of the arrays to check + arrow_type: DataType, + physical_type: PhysicalType, + /// The length of the column's values if it is a `FIXED_LEN_BYTE_ARRAY` + /// column, otherwise 0 + /// + /// Decimals are converted to this length, as other writers can store + /// decimals in more bytes than their precision needs. + type_length: usize, +} + +impl<'a> ArrowSbbf<'a> { + /// Create a new [`ArrowSbbf`] for the bloom filter `sbbf` of `column` + /// + /// `arrow_type` is the Arrow type of the arrays that will be checked, for + /// example the type of the column in the file's Arrow schema. If `None`, the + /// type is derived from `column` in the same way as when reading a file + /// without an Arrow schema. + /// + /// Returns an error if values of `arrow_type` cannot be stored in `column`, + /// if `arrow_type` is a decimal and `column` is not a decimal of the same + /// scale, or the other way around, or if `arrow_type` is a time or timestamp + /// in a different unit than `column`. + pub fn try_new( + sbbf: &'a Sbbf, + column: &ColumnDescriptor, + arrow_type: Option<DataType>, + ) -> Result<Self> { + let arrow_type = match arrow_type { + Some(arrow_type) => arrow_type, + None => parquet_to_arrow_field(column)?.data_type().clone(), + }; + validate(column.self_type(), &arrow_type)?; + Ok(Self { + sbbf, + arrow_type, + physical_type: column.physical_type(), + // The schema checks that the length of a FIXED_LEN_BYTE_ARRAY column + // is positive, and other columns have no length + type_length: column.type_length().try_into().unwrap_or(0), + }) + } + + /// Returns the Arrow type of the arrays this [`ArrowSbbf`] checks + pub fn arrow_type(&self) -> &DataType { + &self.arrow_type + } + + /// Check each value of `array` against the bloom filter + /// + /// Returns `true` if the value may be present, and `false` if it is + /// definitely absent. Nulls in `array` are null in the result. + /// + /// `array` must have the type returned by [`Self::arrow_type`], or be a + /// dictionary or run-end encoded array of values of that type, or a + /// [`NullArray`](arrow_array::NullArray). + pub fn check(&self, array: &dyn Array) -> Result<BooleanArray> { + if let Some(dictionary) = array.as_any_dictionary_opt() { + let values = self.check(dictionary.values().as_ref())?; + let found = arrow_select::take::take(&values, dictionary.keys(), None)?; + return Ok(found.as_boolean().clone()); + } + let value_type = value_type(&self.arrow_type); + match array.data_type() { + DataType::Null => return Ok(BooleanArray::new_null(array.len())), + DataType::RunEndEncoded(_, _) => { + return downcast_run_array!( + array => self.check_run_array(array), + _ => unreachable!("RunEndEncoded array is not a RunArray"), + ); + } + data_type if data_type != value_type => { + return Err(ParquetError::General(format!( + "Cannot check {data_type} values with an ArrowSbbf for {value_type} values" + ))); + } + _ => {} + } + + // `try_new` checked that ArrowWriter stores values of this type in a + // column of this physical type, so the conversions below accept them + let sbbf = self.sbbf; + let found = match self.physical_type { + PhysicalType::INT32 => visit_i32(array, CheckPrimitive { sbbf })?, + PhysicalType::INT64 => visit_i64(array, CheckPrimitive { sbbf })?, + PhysicalType::FLOAT => { + CheckPrimitive { sbbf }.slice(array.as_primitive::<Float32Type>().values())? + } + PhysicalType::DOUBLE => { + CheckPrimitive { sbbf }.slice(array.as_primitive::<Float64Type>().values())? + } + PhysicalType::BOOLEAN => array + .as_boolean() + .values() + .iter() + .map(|v| sbbf.check(&v)) + .collect(), + PhysicalType::BYTE_ARRAY => check_byte_array(sbbf, array), + PhysicalType::FIXED_LEN_BYTE_ARRAY => { + let visitor = CheckFixedLenByteArray { + sbbf, + len: array.len(), + type_length: self.type_length, + }; + visit_fixed_len_byte_array(array, visitor)? + } + PhysicalType::INT96 => unreachable!("ArrowWriter does not write INT96 columns"), + }; + Ok(BooleanArray::new(found, array.logical_nulls())) + } + + /// Checks the values of a run-end encoded array, and repeats each result for its run + fn check_run_array<R: RunEndIndexType>(&self, array: &RunArray<R>) -> Result<BooleanArray> { + let found = self.check(array.values_slice().as_ref())?; + let mut builder = BooleanBuilder::with_capacity(array.len()); + let mut run_start = 0; + for (i, run_end) in array.run_ends().sliced_values().enumerate() { + let run_end = run_end.as_usize(); + match found.is_valid(i) { + true => builder.append_n(run_end - run_start, found.value(i)), + false => builder.append_nulls(run_end - run_start), + } + run_start = run_end; + } + Ok(builder.finish()) + } +} + +/// Returns the type of the values of a dictionary or run-end encoded `data_type`, +/// or `data_type` itself +fn value_type(data_type: &DataType) -> &DataType { + match data_type { + DataType::Dictionary(_, values) => value_type(values), + DataType::RunEndEncoded(_, values) => value_type(values.data_type()), + _ => data_type, + } +} + +/// Returns an error unless [`ArrowWriter`] stores values of `arrow_type` in the +/// same way as values of `column`, so that they can be checked against its +/// bloom filter +/// +/// [`ArrowWriter`]: crate::arrow::ArrowWriter +fn validate(column: &Type, arrow_type: &DataType) -> Result<()> { + // ArrowWriter stores seconds without a unit, so they cannot be told apart + // from values in a column that has one + let seconds = matches!( + value_type(arrow_type), + DataType::Timestamp(ArrowTimeUnit::Second, _) | DataType::Time32(ArrowTimeUnit::Second) + ); + if seconds && time_unit(column).is_some() { + return Err(type_mismatch(column, arrow_type)); + } + if !arrow_type.is_nested() { + let field = Field::new(column.name(), arrow_type.clone(), true); + // Only Date64 depends on `coerce_types`, which is stored as INT32 days + // or INT64 milliseconds + for coerce_types in [false, true] { + let written = arrow_to_parquet_type(&field, coerce_types)?; + if is_stored_as(&written, column) { + return Ok(()); + } + } + } + Err(type_mismatch(column, arrow_type)) +} + +fn type_mismatch(column: &Type, arrow_type: &DataType) -> ParquetError { + ParquetError::General(format!( + "Cannot check a bloom filter of type {} with {arrow_type} values", + describe(column) + )) +} + +/// Returns whether values written to a column of type `written` can be checked +/// against the bloom filter of a column of type `column` +fn is_stored_as(written: &Type, column: &Type) -> bool { + let physical_type = column.get_physical_type(); + match (decimal_scale(written), decimal_scale(column)) { + // Decimals are stored as unscaled integers, which are converted to the + // column's physical type and length + (Some(written_scale), Some(scale)) => { + written_scale == scale && physical_type != PhysicalType::BYTE_ARRAY + } + (None, None) => { + written.get_physical_type() == physical_type + && (physical_type != PhysicalType::FIXED_LEN_BYTE_ARRAY + || type_length(written) == type_length(column)) + // The same values mean different instants in different units + && match (time_unit(written), time_unit(column)) { + (Some(written_unit), Some(unit)) => written_unit == unit, + _ => true, + } Review Comment: Not blocking, and fine as a follow-up: should a column without a unit also reject an Arrow type that has one? This arm accepts it, so a plain `INT64` column written from `Timestamp(Second)` accepts `Timestamp(Millisecond)`, and `check` then returns `false` for instants that are in the file. `ArrowWriter` always writes a unit for millisecond, microsecond, and nanosecond timestamps, so as I read it such a column was not written from that type. Rejecting it would break a caller that checks a plain `INT64` column, such as epoch milliseconds stored as a `long`, with a timestamp type. If that case should keep working, a sentence in the `try_new` docs would make it explicit. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
