adriangb commented on code in PR #11549: URL: https://github.com/apache/arrow-rs/pull/11549#discussion_r4304744537
########## parquet/src/arrow/bloom_filter.rs: ########## @@ -0,0 +1,612 @@ +// 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::cast::AsArray; +use arrow_array::types::{Float32Type, Float64Type}; +use arrow_array::{Array, BooleanArray}; +use arrow_buffer::BooleanBuffer; +use arrow_schema::DataType; + +use crate::arrow::arrow_writer::{ + FixedLenByteArrayVisitor, PrimitiveVisitor, visit_fixed_len_byte_array, visit_i32, visit_i64, +}; +use crate::basic::{ConvertedType, LogicalType, Type as PhysicalType}; +use crate::bloom_filter::Sbbf; +use crate::data_type::AsBytes; +use crate::errors::{ParquetError, Result}; +use crate::schema::types::ColumnDescriptor; + +/// A Parquet bloom filter ([`Sbbf`]) that can be checked with Arrow arrays +/// +/// [`ArrowWriter`] converts some Arrow types to a different Parquet physical +/// type before writing them, for example `Int8` and `UInt16` are stored as +/// `INT32`, and the bloom filter is built from the converted values. Checking +/// such a filter with [`Sbbf::check`] and the original Arrow value hashes +/// different bytes, and so reports values that are present as absent. +/// +/// [`ArrowSbbf::check`] applies the same conversion 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(); +/// +/// // Checking the Arrow value directly hashes a single byte, not the INT32 that was written +/// assert!(!sbbf.check(&1_i8)); +/// +/// let found = ArrowSbbf::new(sbbf, column) +/// .check(&Int8Array::from(vec![1, 3, 4])) +/// .unwrap(); +/// assert!(found.value(0)); +/// assert!(found.value(1)); +/// assert!(!found.value(2)); +/// ``` +/// +/// [`ArrowWriter`]: crate::arrow::ArrowWriter +#[derive(Debug, Clone, Copy)] +pub struct ArrowSbbf<'a> { + sbbf: &'a Sbbf, + physical_type: PhysicalType, + /// The length of the column's values if it is a `FIXED_LEN_BYTE_ARRAY` column + type_length: i32, Review Comment: This is cast `as usize` later. Do the conversion once in `new` and store a `usize`: ```suggestion type_length: usize, ``` ########## parquet/src/arrow/arrow_writer/mod.rs: ########## @@ -1752,66 +1598,359 @@ fn write_leaf( ColumnWriter::ByteArrayColumnWriter(_) => { unreachable!("should use ByteArrayWriter") } - ColumnWriter::FixedLenByteArrayColumnWriter(typed) => { - let bytes = match column.data_type() { - ArrowDataType::Interval(interval_unit) => match interval_unit { - IntervalUnit::YearMonth => { - let array = column.as_primitive::<IntervalYearMonthType>(); - get_interval_ym_array_slice(array, indices.iter().copied()) - } - IntervalUnit::DayTime => { - let array = column.as_primitive::<IntervalDayTimeType>(); - get_interval_dt_array_slice(array, indices.iter().copied()) - } - IntervalUnit::MonthDayNano => { - return Err(ParquetError::NYI(format!( - "Attempting to write an Arrow interval type {interval_unit:?} to parquet that is not yet implemented" - ))); - } - }, - ArrowDataType::FixedSizeBinary(_) => { - let array = column.as_fixed_size_binary(); - get_fsb_array_slice(array, indices.iter().copied()) - } - ArrowDataType::Decimal32(_, _) => { - let array = column.as_primitive::<Decimal32Type>(); - get_decimal_array_slice(array, indices.iter().copied()) - } - ArrowDataType::Decimal64(_, _) => { - let array = column.as_primitive::<Decimal64Type>(); - get_decimal_array_slice(array, indices.iter().copied()) - } - ArrowDataType::Decimal128(_, _) => { - let array = column.as_primitive::<Decimal128Type>(); - get_decimal_array_slice(array, indices.iter().copied()) - } - ArrowDataType::Decimal256(_, _) => { - let array = column.as_primitive::<Decimal256Type>(); - get_decimal_array_slice(array, indices.iter().copied()) - } - ArrowDataType::Float16 => { - let array = column.as_primitive::<Float16Type>(); - get_float_16_array_slice(array, indices.iter().copied()) - } - _ => { - return Err(ParquetError::NYI( - "Attempting to write an Arrow type that is not yet implemented".to_string(), - )); - } + ColumnWriter::FixedLenByteArrayColumnWriter(typed) => visit_fixed_len_byte_array( + column, + WriteFixedLenByteArray { + writer: typed, + levels, + }, + )?, + } +} + +/// Receives the values [`ArrowWriter`] stores for an Arrow array in an `INT32` +/// (`T = i32`) or `INT64` (`T = i64`) column, which are also the values hashed +/// into the column's bloom filter +/// +/// [`visit_i32`] and [`visit_i64`] hold the conversion from each Arrow type, and +/// call [`Self::slice`] when the Arrow values are stored as they are, or +/// [`Self::map`] when each value is converted. This lets the writer borrow the +/// Arrow buffer when no conversion is needed, and lets +/// [`ArrowSbbf`](crate::arrow::bloom_filter::ArrowSbbf) check converted values +/// one at a time without collecting them. +pub(crate) trait PrimitiveVisitor<T> { + type Output; + + /// Receives values that are stored as they are + fn slice(self, values: &[T]) -> Self::Output; + + /// Receives values that are each stored as `convert(value)` + fn map<S: Copy>(self, values: &[S], convert: impl Fn(S) -> T) -> Self::Output; +} + +/// Passes the values [`ArrowWriter`] stores for `column` in an `INT32` column to `visitor` +pub(crate) fn visit_i32<V: PrimitiveVisitor<i32>>( + column: &dyn arrow_array::Array, + visitor: V, +) -> Result<V::Output> { + // Note: this should match the contents of arrow_to_parquet_type + let output = match column.data_type() { + ArrowDataType::Null => visitor.slice(Int32Array::new_null(column.len()).values()), + ArrowDataType::Int8 => { + visitor.map(column.as_primitive::<Int8Type>().values(), |x| x as i32) + } + ArrowDataType::Int16 => { + visitor.map(column.as_primitive::<Int16Type>().values(), |x| x as i32) + } + ArrowDataType::Int32 => visitor.slice(column.as_primitive::<Int32Type>().values()), + ArrowDataType::UInt8 => { + visitor.map(column.as_primitive::<UInt8Type>().values(), |x| x as i32) + } + ArrowDataType::UInt16 => { + visitor.map(column.as_primitive::<UInt16Type>().values(), |x| x as i32) + } + ArrowDataType::UInt32 => { + // follow C++ implementation and use overflow/reinterpret cast from u32 to i32 which will map + // `(i32::MAX as u32)..u32::MAX` to `i32::MIN..0` + let values = column.as_primitive::<UInt32Type>().values(); + visitor.slice(values.inner().typed_data()) + } + ArrowDataType::Date32 => visitor.slice(column.as_primitive::<Date32Type>().values()), + ArrowDataType::Time32(TimeUnit::Second) => { + visitor.slice(column.as_primitive::<Time32SecondType>().values()) + } + ArrowDataType::Time32(TimeUnit::Millisecond) => { + visitor.slice(column.as_primitive::<Time32MillisecondType>().values()) + } + ArrowDataType::Date64 => { + // If the column is a Date64, we truncate it + visitor.map(column.as_primitive::<Date64Type>().values(), |x| { + (x / 86_400_000) as i32 + }) + } + ArrowDataType::Decimal32(_, _) => { + visitor.slice(column.as_primitive::<Decimal32Type>().values()) + } + ArrowDataType::Decimal64(_, _) => { + // use the int32 to represent the decimal with low precision + visitor.map(column.as_primitive::<Decimal64Type>().values(), |v| { + v as i32 + }) + } + ArrowDataType::Decimal128(_, _) => { + // use the int32 to represent the decimal with low precision + visitor.map(column.as_primitive::<Decimal128Type>().values(), |v| { + v as i32 + }) + } + ArrowDataType::Decimal256(_, _) => { + // use the int32 to represent the decimal with low precision + visitor.map(column.as_primitive::<Decimal256Type>().values(), |v| { + v.as_i128() as i32 + }) + } + d => return Err(ParquetError::General(format!("Cannot coerce {d} to I32"))), + }; + Ok(output) +} + +/// Passes the values [`ArrowWriter`] stores for `column` in an `INT64` column to `visitor` +pub(crate) fn visit_i64<V: PrimitiveVisitor<i64>>( + column: &dyn arrow_array::Array, + visitor: V, +) -> Result<V::Output> { + // Note: this should match the contents of arrow_to_parquet_type + let output = match column.data_type() { + ArrowDataType::Date64 => visitor.slice(column.as_primitive::<Date64Type>().values()), + ArrowDataType::Int64 => visitor.slice(column.as_primitive::<Int64Type>().values()), + ArrowDataType::UInt64 => { + // follow C++ implementation and use overflow/reinterpret cast from u64 to i64 which will map + // `(i64::MAX as u64)..u64::MAX` to `i64::MIN..0` + let values = column.as_primitive::<UInt64Type>().values(); + visitor.slice(values.inner().typed_data()) + } + ArrowDataType::Time64(TimeUnit::Microsecond) => { + visitor.slice(column.as_primitive::<Time64MicrosecondType>().values()) + } + ArrowDataType::Time64(TimeUnit::Nanosecond) => { + visitor.slice(column.as_primitive::<Time64NanosecondType>().values()) + } + ArrowDataType::Timestamp(unit, _) => match unit { + TimeUnit::Second => { + visitor.slice(column.as_primitive::<TimestampSecondType>().values()) + } + TimeUnit::Millisecond => { + visitor.slice(column.as_primitive::<TimestampMillisecondType>().values()) + } + TimeUnit::Microsecond => { + visitor.slice(column.as_primitive::<TimestampMicrosecondType>().values()) + } + TimeUnit::Nanosecond => { + visitor.slice(column.as_primitive::<TimestampNanosecondType>().values()) + } + }, + ArrowDataType::Duration(unit) => match unit { + TimeUnit::Second => visitor.slice(column.as_primitive::<DurationSecondType>().values()), + TimeUnit::Millisecond => { + visitor.slice(column.as_primitive::<DurationMillisecondType>().values()) + } + TimeUnit::Microsecond => { + visitor.slice(column.as_primitive::<DurationMicrosecondType>().values()) + } + TimeUnit::Nanosecond => { + visitor.slice(column.as_primitive::<DurationNanosecondType>().values()) + } + }, + ArrowDataType::Decimal64(_, _) => { + visitor.slice(column.as_primitive::<Decimal64Type>().values()) + } + ArrowDataType::Decimal128(_, _) => { + // use the int64 to represent the decimal with low precision + visitor.map(column.as_primitive::<Decimal128Type>().values(), |v| { + v as i64 + }) + } + ArrowDataType::Decimal256(_, _) => { + // use the int64 to represent the decimal with low precision + visitor.map(column.as_primitive::<Decimal256Type>().values(), |v| { + v.as_i128() as i64 + }) + } + d => return Err(ParquetError::General(format!("Cannot coerce {d} to I64"))), + }; + Ok(output) +} + +/// Writes the values passed to it to an `INT32` or `INT64` column +struct WritePrimitive<'a, 'b, E: ColumnValueEncoder> { + writer: &'a mut GenericColumnWriter<'b, E>, + levels: &'a ArrayLevels, +} + +impl<T, E> PrimitiveVisitor<T> for WritePrimitive<'_, '_, E> +where + E: ColumnValueEncoder<Values = [T]>, +{ + type Output = Result<usize>; + + fn slice(self, values: &[T]) -> Result<usize> { + write_primitive(self.writer, values, self.levels) + } + + fn map<S: Copy>(self, values: &[S], convert: impl Fn(S) -> T) -> Result<usize> { + let values: Vec<T> = values.iter().map(|v| convert(*v)).collect(); + write_primitive(self.writer, &values, self.levels) + } +} + +/// Receives the values [`ArrowWriter`] stores for an Arrow array in a +/// `FIXED_LEN_BYTE_ARRAY` column, which are also the values hashed into the +/// column's bloom filter +/// +/// [`visit_fixed_len_byte_array`] holds the conversion from each Arrow type +pub(crate) trait FixedLenByteArrayVisitor { + type Output; + + /// Returns the length of the values that decimals of `precision` are stored as + fn decimal_length(&self, precision: u8) -> usize; + + /// Receives values that are `length` bytes long + /// + /// `fill(i, value)` writes the value at index `i` of the array to `value`, + /// which is `length` zeroed bytes. It returns `false` if the value does not + /// fit in `length` bytes, which can only happen for decimals. + fn values(self, length: usize, fill: impl Fn(usize, &mut [u8]) -> bool) -> Self::Output; +} + +/// Passes the values [`ArrowWriter`] stores for `column` in a `FIXED_LEN_BYTE_ARRAY` +/// column to `visitor` +pub(crate) fn visit_fixed_len_byte_array<V: FixedLenByteArrayVisitor>( + column: &dyn arrow_array::Array, + visitor: V, +) -> Result<V::Output> { + let output = match column.data_type() { + ArrowDataType::Interval(interval_unit) => match interval_unit { + IntervalUnit::YearMonth => { + // 12 bytes of months, days and milliseconds (4 bytes each). An Arrow + // YearMonth interval only stores months, so only the first 4 bytes are set. + let array = column.as_primitive::<IntervalYearMonthType>(); + visitor.values(12, |i, value| { + value[0..4].copy_from_slice(&array.value(i).to_le_bytes()); + true + }) + } + IntervalUnit::DayTime => { + // 12 bytes of months, days and milliseconds (4 bytes each). An Arrow + // DayTime interval only stores days and milliseconds, so the first 4 + // bytes are not set. + let array = column.as_primitive::<IntervalDayTimeType>(); + visitor.values(12, |i, value| { + let interval = array.value(i); + value[4..8].copy_from_slice(&interval.days.to_le_bytes()); + value[8..12].copy_from_slice(&interval.milliseconds.to_le_bytes()); + true + }) + } + IntervalUnit::MonthDayNano => { + return Err(ParquetError::NYI(format!( + "Attempting to write an Arrow interval type {interval_unit:?} to parquet that is not yet implemented" + ))); + } + }, + ArrowDataType::FixedSizeBinary(_) => { + let array = column.as_fixed_size_binary(); + visitor.values(array.value_size(), |i, value| { + value.copy_from_slice(array.value(i)); + true + }) + } + ArrowDataType::Decimal32(_, _) => { + visit_decimal(column.as_primitive::<Decimal32Type>(), visitor) + } + ArrowDataType::Decimal64(_, _) => { + visit_decimal(column.as_primitive::<Decimal64Type>(), visitor) + } + ArrowDataType::Decimal128(_, _) => { + visit_decimal(column.as_primitive::<Decimal128Type>(), visitor) + } + ArrowDataType::Decimal256(_, _) => { + visit_decimal(column.as_primitive::<Decimal256Type>(), visitor) + } + ArrowDataType::Float16 => { + let array = column.as_primitive::<Float16Type>(); + visitor.values(2, |i, value| { + value.copy_from_slice(&array.value(i).to_le_bytes()); + true + }) + } + _ => { + return Err(ParquetError::NYI( + "Attempting to write an Arrow type that is not yet implemented".to_string(), + )); + } + }; + Ok(output) +} + +/// Passes the big-endian two's complement bytes of the values of `array` to `visitor` +fn visit_decimal<T: NativeDecimalType, V: FixedLenByteArrayVisitor>( + array: &PrimitiveArray<T>, + visitor: V, +) -> V::Output { + let length = visitor.decimal_length(array.precision()); + visitor.values(length, |i, value| { + resize_twos_complement(T::to_be_bytes(array.value(i)).as_ref(), value) + }) +} + +/// Writes the big-endian two's complement integer `bytes` to `out`, which may be +/// shorter or longer than `bytes` +/// +/// Drops leading bytes when `out` is shorter and sign-extends when it is longer. +/// Returns `false` if a dropped byte was not sign extension, that is, if the +/// integer does not fit in `out`. +#[inline] +fn resize_twos_complement(bytes: &[u8], out: &mut [u8]) -> bool { + match out.len().checked_sub(bytes.len()) { + // Same length, which lets the compiler inline the copy + Some(0) => { + out.copy_from_slice(bytes); + true + } + Some(extension) => { + let sign = if bytes.first().is_some_and(|b| (*b as i8) < 0) { + 0xFF + } else { + 0 }; - typed.write_batch_internal( - bytes.as_slice(), - None, - levels.def_level_data().as_ref(), - levels.rep_level_data().as_ref(), - None, - None, - None, - ) + out[..extension].fill(sign); + out[extension..].copy_from_slice(bytes); + true + } + None => { + let (dropped, kept) = bytes.split_at(bytes.len() - out.len()); + out.copy_from_slice(kept); + let sign = if kept.first().is_some_and(|b| (*b as i8) < 0) { + 0xFF + } else { + 0 Review Comment: This sign-byte expression is also used above. A small helper removes the duplicate: ```suggestion let sign = sign_byte(kept); ``` ```rust fn sign_byte(bytes: &[u8]) -> u8 { if bytes.first().is_some_and(|b| (*b as i8) < 0) { 0xFF } else { 0 } } ``` ########## parquet/src/arrow/bloom_filter.rs: ########## @@ -0,0 +1,612 @@ +// 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::cast::AsArray; +use arrow_array::types::{Float32Type, Float64Type}; +use arrow_array::{Array, BooleanArray}; +use arrow_buffer::BooleanBuffer; +use arrow_schema::DataType; + +use crate::arrow::arrow_writer::{ + FixedLenByteArrayVisitor, PrimitiveVisitor, visit_fixed_len_byte_array, visit_i32, visit_i64, +}; +use crate::basic::{ConvertedType, LogicalType, Type as PhysicalType}; +use crate::bloom_filter::Sbbf; +use crate::data_type::AsBytes; +use crate::errors::{ParquetError, Result}; +use crate::schema::types::ColumnDescriptor; + +/// A Parquet bloom filter ([`Sbbf`]) that can be checked with Arrow arrays +/// +/// [`ArrowWriter`] converts some Arrow types to a different Parquet physical +/// type before writing them, for example `Int8` and `UInt16` are stored as +/// `INT32`, and the bloom filter is built from the converted values. Checking +/// such a filter with [`Sbbf::check`] and the original Arrow value hashes +/// different bytes, and so reports values that are present as absent. +/// +/// [`ArrowSbbf::check`] applies the same conversion 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(); +/// +/// // Checking the Arrow value directly hashes a single byte, not the INT32 that was written +/// assert!(!sbbf.check(&1_i8)); +/// +/// let found = ArrowSbbf::new(sbbf, column) +/// .check(&Int8Array::from(vec![1, 3, 4])) +/// .unwrap(); +/// assert!(found.value(0)); +/// assert!(found.value(1)); +/// assert!(!found.value(2)); +/// ``` +/// +/// [`ArrowWriter`]: crate::arrow::ArrowWriter +#[derive(Debug, Clone, Copy)] +pub struct ArrowSbbf<'a> { + sbbf: &'a Sbbf, + physical_type: PhysicalType, + /// The length of the column's values if it is a `FIXED_LEN_BYTE_ARRAY` column + type_length: i32, + /// The scale of the column's values if it is a decimal column + decimal_scale: Option<i32>, +} + +impl<'a> ArrowSbbf<'a> { + /// Create a new [`ArrowSbbf`] for the bloom filter of the column described by `column` + pub fn new(sbbf: &'a Sbbf, column: &ColumnDescriptor) -> Self { + let decimal_scale = match column.logical_type_ref() { + Some(LogicalType::Decimal(decimal)) => Some(decimal.scale), + _ if column.converted_type() == ConvertedType::DECIMAL => Some(column.type_scale()), + _ => None, + }; + Self { + sbbf, + physical_type: column.physical_type(), + type_length: column.type_length(), + decimal_scale, + } + } + + /// 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. + /// + /// Decimal values of any precision can be checked against a decimal column + /// of the same scale. They are converted to the column's physical type and, + /// for a `FIXED_LEN_BYTE_ARRAY` column, to the column's length; a value too + /// large for that length is reported as absent. + /// + /// Returns an error if [`ArrowWriter`] cannot write `array`'s data type to a + /// column of this physical type, if `array` is a decimal array and the + /// column is not a decimal column of the same scale, or if `array` is a + /// `FixedSizeBinary` array whose values have a different length than the + /// column's. + /// + /// [`ArrowWriter`]: crate::arrow::ArrowWriter + 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()); + } + + match array.data_type() { + DataType::Null => return Ok(BooleanArray::new_null(array.len())), + DataType::Decimal32(_, scale) + | DataType::Decimal64(_, scale) + | DataType::Decimal128(_, scale) + | DataType::Decimal256(_, scale) => self.validate_decimal_scale(*scale)?, Review Comment: The check rejects decimal values for a non-decimal column. But the reverse is not rejected: an `Int8` array checked against an `INT32` decimal or `Date32` column is hashed with no error. This cannot give a false negative, but the behavior is not symmetric. Should a decimal column also require a decimal array? ########## parquet/src/arrow/arrow_writer/mod.rs: ########## @@ -1752,66 +1598,359 @@ fn write_leaf( ColumnWriter::ByteArrayColumnWriter(_) => { unreachable!("should use ByteArrayWriter") } - ColumnWriter::FixedLenByteArrayColumnWriter(typed) => { - let bytes = match column.data_type() { - ArrowDataType::Interval(interval_unit) => match interval_unit { - IntervalUnit::YearMonth => { - let array = column.as_primitive::<IntervalYearMonthType>(); - get_interval_ym_array_slice(array, indices.iter().copied()) - } - IntervalUnit::DayTime => { - let array = column.as_primitive::<IntervalDayTimeType>(); - get_interval_dt_array_slice(array, indices.iter().copied()) - } - IntervalUnit::MonthDayNano => { - return Err(ParquetError::NYI(format!( - "Attempting to write an Arrow interval type {interval_unit:?} to parquet that is not yet implemented" - ))); - } - }, - ArrowDataType::FixedSizeBinary(_) => { - let array = column.as_fixed_size_binary(); - get_fsb_array_slice(array, indices.iter().copied()) - } - ArrowDataType::Decimal32(_, _) => { - let array = column.as_primitive::<Decimal32Type>(); - get_decimal_array_slice(array, indices.iter().copied()) - } - ArrowDataType::Decimal64(_, _) => { - let array = column.as_primitive::<Decimal64Type>(); - get_decimal_array_slice(array, indices.iter().copied()) - } - ArrowDataType::Decimal128(_, _) => { - let array = column.as_primitive::<Decimal128Type>(); - get_decimal_array_slice(array, indices.iter().copied()) - } - ArrowDataType::Decimal256(_, _) => { - let array = column.as_primitive::<Decimal256Type>(); - get_decimal_array_slice(array, indices.iter().copied()) - } - ArrowDataType::Float16 => { - let array = column.as_primitive::<Float16Type>(); - get_float_16_array_slice(array, indices.iter().copied()) - } - _ => { - return Err(ParquetError::NYI( - "Attempting to write an Arrow type that is not yet implemented".to_string(), - )); - } + ColumnWriter::FixedLenByteArrayColumnWriter(typed) => visit_fixed_len_byte_array( + column, + WriteFixedLenByteArray { + writer: typed, + levels, + }, + )?, + } +} + +/// Receives the values [`ArrowWriter`] stores for an Arrow array in an `INT32` +/// (`T = i32`) or `INT64` (`T = i64`) column, which are also the values hashed +/// into the column's bloom filter +/// +/// [`visit_i32`] and [`visit_i64`] hold the conversion from each Arrow type, and +/// call [`Self::slice`] when the Arrow values are stored as they are, or +/// [`Self::map`] when each value is converted. This lets the writer borrow the +/// Arrow buffer when no conversion is needed, and lets +/// [`ArrowSbbf`](crate::arrow::bloom_filter::ArrowSbbf) check converted values +/// one at a time without collecting them. +pub(crate) trait PrimitiveVisitor<T> { + type Output; + + /// Receives values that are stored as they are + fn slice(self, values: &[T]) -> Self::Output; + + /// Receives values that are each stored as `convert(value)` + fn map<S: Copy>(self, values: &[S], convert: impl Fn(S) -> T) -> Self::Output; +} + +/// Passes the values [`ArrowWriter`] stores for `column` in an `INT32` column to `visitor` +pub(crate) fn visit_i32<V: PrimitiveVisitor<i32>>( + column: &dyn arrow_array::Array, + visitor: V, +) -> Result<V::Output> { + // Note: this should match the contents of arrow_to_parquet_type + let output = match column.data_type() { + ArrowDataType::Null => visitor.slice(Int32Array::new_null(column.len()).values()), + ArrowDataType::Int8 => { + visitor.map(column.as_primitive::<Int8Type>().values(), |x| x as i32) + } + ArrowDataType::Int16 => { + visitor.map(column.as_primitive::<Int16Type>().values(), |x| x as i32) + } + ArrowDataType::Int32 => visitor.slice(column.as_primitive::<Int32Type>().values()), + ArrowDataType::UInt8 => { + visitor.map(column.as_primitive::<UInt8Type>().values(), |x| x as i32) + } + ArrowDataType::UInt16 => { + visitor.map(column.as_primitive::<UInt16Type>().values(), |x| x as i32) + } + ArrowDataType::UInt32 => { + // follow C++ implementation and use overflow/reinterpret cast from u32 to i32 which will map + // `(i32::MAX as u32)..u32::MAX` to `i32::MIN..0` + let values = column.as_primitive::<UInt32Type>().values(); + visitor.slice(values.inner().typed_data()) + } + ArrowDataType::Date32 => visitor.slice(column.as_primitive::<Date32Type>().values()), + ArrowDataType::Time32(TimeUnit::Second) => { + visitor.slice(column.as_primitive::<Time32SecondType>().values()) + } + ArrowDataType::Time32(TimeUnit::Millisecond) => { + visitor.slice(column.as_primitive::<Time32MillisecondType>().values()) + } + ArrowDataType::Date64 => { + // If the column is a Date64, we truncate it + visitor.map(column.as_primitive::<Date64Type>().values(), |x| { + (x / 86_400_000) as i32 Review Comment: A mutation test that changes `/` to `*` here is not detected by the tests. Please add a test that writes Date64 `5 * 86_400_000` and `-1`, and checks that the bloom filter contains `5i32` and `0i32`. ########## parquet/src/arrow/arrow_writer/mod.rs: ########## @@ -1752,66 +1598,359 @@ fn write_leaf( ColumnWriter::ByteArrayColumnWriter(_) => { unreachable!("should use ByteArrayWriter") } - ColumnWriter::FixedLenByteArrayColumnWriter(typed) => { - let bytes = match column.data_type() { - ArrowDataType::Interval(interval_unit) => match interval_unit { - IntervalUnit::YearMonth => { - let array = column.as_primitive::<IntervalYearMonthType>(); - get_interval_ym_array_slice(array, indices.iter().copied()) - } - IntervalUnit::DayTime => { - let array = column.as_primitive::<IntervalDayTimeType>(); - get_interval_dt_array_slice(array, indices.iter().copied()) - } - IntervalUnit::MonthDayNano => { - return Err(ParquetError::NYI(format!( - "Attempting to write an Arrow interval type {interval_unit:?} to parquet that is not yet implemented" - ))); - } - }, - ArrowDataType::FixedSizeBinary(_) => { - let array = column.as_fixed_size_binary(); - get_fsb_array_slice(array, indices.iter().copied()) - } - ArrowDataType::Decimal32(_, _) => { - let array = column.as_primitive::<Decimal32Type>(); - get_decimal_array_slice(array, indices.iter().copied()) - } - ArrowDataType::Decimal64(_, _) => { - let array = column.as_primitive::<Decimal64Type>(); - get_decimal_array_slice(array, indices.iter().copied()) - } - ArrowDataType::Decimal128(_, _) => { - let array = column.as_primitive::<Decimal128Type>(); - get_decimal_array_slice(array, indices.iter().copied()) - } - ArrowDataType::Decimal256(_, _) => { - let array = column.as_primitive::<Decimal256Type>(); - get_decimal_array_slice(array, indices.iter().copied()) - } - ArrowDataType::Float16 => { - let array = column.as_primitive::<Float16Type>(); - get_float_16_array_slice(array, indices.iter().copied()) - } - _ => { - return Err(ParquetError::NYI( - "Attempting to write an Arrow type that is not yet implemented".to_string(), - )); - } + ColumnWriter::FixedLenByteArrayColumnWriter(typed) => visit_fixed_len_byte_array( + column, + WriteFixedLenByteArray { + writer: typed, + levels, + }, + )?, + } +} + +/// Receives the values [`ArrowWriter`] stores for an Arrow array in an `INT32` +/// (`T = i32`) or `INT64` (`T = i64`) column, which are also the values hashed +/// into the column's bloom filter +/// +/// [`visit_i32`] and [`visit_i64`] hold the conversion from each Arrow type, and +/// call [`Self::slice`] when the Arrow values are stored as they are, or +/// [`Self::map`] when each value is converted. This lets the writer borrow the +/// Arrow buffer when no conversion is needed, and lets +/// [`ArrowSbbf`](crate::arrow::bloom_filter::ArrowSbbf) check converted values +/// one at a time without collecting them. +pub(crate) trait PrimitiveVisitor<T> { + type Output; + + /// Receives values that are stored as they are + fn slice(self, values: &[T]) -> Self::Output; + + /// Receives values that are each stored as `convert(value)` + fn map<S: Copy>(self, values: &[S], convert: impl Fn(S) -> T) -> Self::Output; +} + +/// Passes the values [`ArrowWriter`] stores for `column` in an `INT32` column to `visitor` +pub(crate) fn visit_i32<V: PrimitiveVisitor<i32>>( + column: &dyn arrow_array::Array, + visitor: V, +) -> Result<V::Output> { + // Note: this should match the contents of arrow_to_parquet_type + let output = match column.data_type() { + ArrowDataType::Null => visitor.slice(Int32Array::new_null(column.len()).values()), + ArrowDataType::Int8 => { + visitor.map(column.as_primitive::<Int8Type>().values(), |x| x as i32) + } + ArrowDataType::Int16 => { + visitor.map(column.as_primitive::<Int16Type>().values(), |x| x as i32) + } + ArrowDataType::Int32 => visitor.slice(column.as_primitive::<Int32Type>().values()), + ArrowDataType::UInt8 => { + visitor.map(column.as_primitive::<UInt8Type>().values(), |x| x as i32) + } + ArrowDataType::UInt16 => { + visitor.map(column.as_primitive::<UInt16Type>().values(), |x| x as i32) + } + ArrowDataType::UInt32 => { + // follow C++ implementation and use overflow/reinterpret cast from u32 to i32 which will map + // `(i32::MAX as u32)..u32::MAX` to `i32::MIN..0` + let values = column.as_primitive::<UInt32Type>().values(); + visitor.slice(values.inner().typed_data()) + } + ArrowDataType::Date32 => visitor.slice(column.as_primitive::<Date32Type>().values()), + ArrowDataType::Time32(TimeUnit::Second) => { + visitor.slice(column.as_primitive::<Time32SecondType>().values()) + } + ArrowDataType::Time32(TimeUnit::Millisecond) => { + visitor.slice(column.as_primitive::<Time32MillisecondType>().values()) + } + ArrowDataType::Date64 => { + // If the column is a Date64, we truncate it + visitor.map(column.as_primitive::<Date64Type>().values(), |x| { + (x / 86_400_000) as i32 + }) + } + ArrowDataType::Decimal32(_, _) => { + visitor.slice(column.as_primitive::<Decimal32Type>().values()) + } + ArrowDataType::Decimal64(_, _) => { + // use the int32 to represent the decimal with low precision + visitor.map(column.as_primitive::<Decimal64Type>().values(), |v| { + v as i32 + }) + } + ArrowDataType::Decimal128(_, _) => { + // use the int32 to represent the decimal with low precision + visitor.map(column.as_primitive::<Decimal128Type>().values(), |v| { + v as i32 + }) + } + ArrowDataType::Decimal256(_, _) => { + // use the int32 to represent the decimal with low precision + visitor.map(column.as_primitive::<Decimal256Type>().values(), |v| { + v.as_i128() as i32 + }) + } + d => return Err(ParquetError::General(format!("Cannot coerce {d} to I32"))), + }; + Ok(output) +} + +/// Passes the values [`ArrowWriter`] stores for `column` in an `INT64` column to `visitor` +pub(crate) fn visit_i64<V: PrimitiveVisitor<i64>>( + column: &dyn arrow_array::Array, + visitor: V, +) -> Result<V::Output> { + // Note: this should match the contents of arrow_to_parquet_type + let output = match column.data_type() { + ArrowDataType::Date64 => visitor.slice(column.as_primitive::<Date64Type>().values()), + ArrowDataType::Int64 => visitor.slice(column.as_primitive::<Int64Type>().values()), + ArrowDataType::UInt64 => { + // follow C++ implementation and use overflow/reinterpret cast from u64 to i64 which will map + // `(i64::MAX as u64)..u64::MAX` to `i64::MIN..0` + let values = column.as_primitive::<UInt64Type>().values(); + visitor.slice(values.inner().typed_data()) + } + ArrowDataType::Time64(TimeUnit::Microsecond) => { + visitor.slice(column.as_primitive::<Time64MicrosecondType>().values()) + } + ArrowDataType::Time64(TimeUnit::Nanosecond) => { + visitor.slice(column.as_primitive::<Time64NanosecondType>().values()) + } + ArrowDataType::Timestamp(unit, _) => match unit { + TimeUnit::Second => { + visitor.slice(column.as_primitive::<TimestampSecondType>().values()) + } + TimeUnit::Millisecond => { + visitor.slice(column.as_primitive::<TimestampMillisecondType>().values()) + } + TimeUnit::Microsecond => { + visitor.slice(column.as_primitive::<TimestampMicrosecondType>().values()) + } + TimeUnit::Nanosecond => { + visitor.slice(column.as_primitive::<TimestampNanosecondType>().values()) + } + }, + ArrowDataType::Duration(unit) => match unit { + TimeUnit::Second => visitor.slice(column.as_primitive::<DurationSecondType>().values()), + TimeUnit::Millisecond => { + visitor.slice(column.as_primitive::<DurationMillisecondType>().values()) + } + TimeUnit::Microsecond => { + visitor.slice(column.as_primitive::<DurationMicrosecondType>().values()) + } + TimeUnit::Nanosecond => { + visitor.slice(column.as_primitive::<DurationNanosecondType>().values()) + } + }, + ArrowDataType::Decimal64(_, _) => { + visitor.slice(column.as_primitive::<Decimal64Type>().values()) + } Review Comment: `visit_i64` has no `Decimal32` arm. Thus `check` with a `Decimal32(9, 2)` array against a `Decimal64(12, 2)` column returns `Cannot coerce Decimal32(9, 2) to I64`. The `ArrowSbbf` docs say that decimals of any precision can be checked against a column of the same scale. ```suggestion } ArrowDataType::Decimal32(_, _) => { visitor.map(column.as_primitive::<Decimal32Type>().values(), |v| v as i64) } ``` ########## parquet/src/arrow/bloom_filter.rs: ########## @@ -0,0 +1,612 @@ +// 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::cast::AsArray; +use arrow_array::types::{Float32Type, Float64Type}; +use arrow_array::{Array, BooleanArray}; +use arrow_buffer::BooleanBuffer; +use arrow_schema::DataType; + +use crate::arrow::arrow_writer::{ + FixedLenByteArrayVisitor, PrimitiveVisitor, visit_fixed_len_byte_array, visit_i32, visit_i64, +}; +use crate::basic::{ConvertedType, LogicalType, Type as PhysicalType}; +use crate::bloom_filter::Sbbf; +use crate::data_type::AsBytes; +use crate::errors::{ParquetError, Result}; +use crate::schema::types::ColumnDescriptor; + +/// A Parquet bloom filter ([`Sbbf`]) that can be checked with Arrow arrays +/// +/// [`ArrowWriter`] converts some Arrow types to a different Parquet physical +/// type before writing them, for example `Int8` and `UInt16` are stored as +/// `INT32`, and the bloom filter is built from the converted values. Checking +/// such a filter with [`Sbbf::check`] and the original Arrow value hashes +/// different bytes, and so reports values that are present as absent. +/// +/// [`ArrowSbbf::check`] applies the same conversion 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(); +/// +/// // Checking the Arrow value directly hashes a single byte, not the INT32 that was written +/// assert!(!sbbf.check(&1_i8)); +/// +/// let found = ArrowSbbf::new(sbbf, column) +/// .check(&Int8Array::from(vec![1, 3, 4])) +/// .unwrap(); +/// assert!(found.value(0)); +/// assert!(found.value(1)); +/// assert!(!found.value(2)); +/// ``` +/// +/// [`ArrowWriter`]: crate::arrow::ArrowWriter +#[derive(Debug, Clone, Copy)] +pub struct ArrowSbbf<'a> { + sbbf: &'a Sbbf, + physical_type: PhysicalType, + /// The length of the column's values if it is a `FIXED_LEN_BYTE_ARRAY` column + type_length: i32, + /// The scale of the column's values if it is a decimal column + decimal_scale: Option<i32>, +} + +impl<'a> ArrowSbbf<'a> { + /// Create a new [`ArrowSbbf`] for the bloom filter of the column described by `column` + pub fn new(sbbf: &'a Sbbf, column: &ColumnDescriptor) -> Self { + let decimal_scale = match column.logical_type_ref() { + Some(LogicalType::Decimal(decimal)) => Some(decimal.scale), + _ if column.converted_type() == ConvertedType::DECIMAL => Some(column.type_scale()), + _ => None, + }; + Self { + sbbf, + physical_type: column.physical_type(), + type_length: column.type_length(), + decimal_scale, + } + } + + /// 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. + /// + /// Decimal values of any precision can be checked against a decimal column + /// of the same scale. They are converted to the column's physical type and, + /// for a `FIXED_LEN_BYTE_ARRAY` column, to the column's length; a value too + /// large for that length is reported as absent. + /// + /// Returns an error if [`ArrowWriter`] cannot write `array`'s data type to a + /// column of this physical type, if `array` is a decimal array and the + /// column is not a decimal column of the same scale, or if `array` is a + /// `FixedSizeBinary` array whose values have a different length than the + /// column's. + /// + /// [`ArrowWriter`]: crate::arrow::ArrowWriter + 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()); + } + + match array.data_type() { + DataType::Null => return Ok(BooleanArray::new_null(array.len())), + DataType::Decimal32(_, scale) + | DataType::Decimal64(_, scale) + | DataType::Decimal128(_, scale) + | DataType::Decimal256(_, scale) => self.validate_decimal_scale(*scale)?, + _ => {} Review Comment: Two small points: - The writer accepts `RunEndEncoded` columns, but `check` returns `Cannot coerce RunEndEncoded(..) to I32`. Please support REE (check the values, then map by run ends), or document this. - A type mismatch against a `FIXED_LEN_BYTE_ARRAY` column returns `NYI: Attempting to write an Arrow type that is not yet implemented`. That message is incorrect for a check. ########## parquet/src/arrow/bloom_filter.rs: ########## @@ -0,0 +1,612 @@ +// 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::cast::AsArray; +use arrow_array::types::{Float32Type, Float64Type}; +use arrow_array::{Array, BooleanArray}; +use arrow_buffer::BooleanBuffer; +use arrow_schema::DataType; + +use crate::arrow::arrow_writer::{ + FixedLenByteArrayVisitor, PrimitiveVisitor, visit_fixed_len_byte_array, visit_i32, visit_i64, +}; +use crate::basic::{ConvertedType, LogicalType, Type as PhysicalType}; +use crate::bloom_filter::Sbbf; +use crate::data_type::AsBytes; +use crate::errors::{ParquetError, Result}; +use crate::schema::types::ColumnDescriptor; + +/// A Parquet bloom filter ([`Sbbf`]) that can be checked with Arrow arrays +/// +/// [`ArrowWriter`] converts some Arrow types to a different Parquet physical +/// type before writing them, for example `Int8` and `UInt16` are stored as +/// `INT32`, and the bloom filter is built from the converted values. Checking +/// such a filter with [`Sbbf::check`] and the original Arrow value hashes +/// different bytes, and so reports values that are present as absent. +/// +/// [`ArrowSbbf::check`] applies the same conversion 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(); +/// +/// // Checking the Arrow value directly hashes a single byte, not the INT32 that was written +/// assert!(!sbbf.check(&1_i8)); +/// +/// let found = ArrowSbbf::new(sbbf, column) +/// .check(&Int8Array::from(vec![1, 3, 4])) +/// .unwrap(); +/// assert!(found.value(0)); +/// assert!(found.value(1)); +/// assert!(!found.value(2)); +/// ``` +/// +/// [`ArrowWriter`]: crate::arrow::ArrowWriter +#[derive(Debug, Clone, Copy)] +pub struct ArrowSbbf<'a> { + sbbf: &'a Sbbf, + physical_type: PhysicalType, + /// The length of the column's values if it is a `FIXED_LEN_BYTE_ARRAY` column + type_length: i32, + /// The scale of the column's values if it is a decimal column + decimal_scale: Option<i32>, +} + +impl<'a> ArrowSbbf<'a> { + /// Create a new [`ArrowSbbf`] for the bloom filter of the column described by `column` + pub fn new(sbbf: &'a Sbbf, column: &ColumnDescriptor) -> Self { + let decimal_scale = match column.logical_type_ref() { + Some(LogicalType::Decimal(decimal)) => Some(decimal.scale), + _ if column.converted_type() == ConvertedType::DECIMAL => Some(column.type_scale()), + _ => None, + }; + Self { + sbbf, + physical_type: column.physical_type(), + type_length: column.type_length(), + decimal_scale, + } + } + + /// 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. + /// + /// Decimal values of any precision can be checked against a decimal column + /// of the same scale. They are converted to the column's physical type and, + /// for a `FIXED_LEN_BYTE_ARRAY` column, to the column's length; a value too + /// large for that length is reported as absent. + /// + /// Returns an error if [`ArrowWriter`] cannot write `array`'s data type to a + /// column of this physical type, if `array` is a decimal array and the + /// column is not a decimal column of the same scale, or if `array` is a + /// `FixedSizeBinary` array whose values have a different length than the + /// column's. + /// + /// [`ArrowWriter`]: crate::arrow::ArrowWriter + 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()); + } + + match array.data_type() { + DataType::Null => return Ok(BooleanArray::new_null(array.len())), Review Comment: The tests pass if this arm is removed, because they check `Null` only against an `INT32` column. Please add a test that checks `NullArray::new(2)` against a `Float64` or `Utf8` column and expects `[None, None]`. ########## parquet/src/arrow/arrow_writer/mod.rs: ########## @@ -1752,66 +1598,359 @@ fn write_leaf( ColumnWriter::ByteArrayColumnWriter(_) => { unreachable!("should use ByteArrayWriter") } - ColumnWriter::FixedLenByteArrayColumnWriter(typed) => { - let bytes = match column.data_type() { - ArrowDataType::Interval(interval_unit) => match interval_unit { - IntervalUnit::YearMonth => { - let array = column.as_primitive::<IntervalYearMonthType>(); - get_interval_ym_array_slice(array, indices.iter().copied()) - } - IntervalUnit::DayTime => { - let array = column.as_primitive::<IntervalDayTimeType>(); - get_interval_dt_array_slice(array, indices.iter().copied()) - } - IntervalUnit::MonthDayNano => { - return Err(ParquetError::NYI(format!( - "Attempting to write an Arrow interval type {interval_unit:?} to parquet that is not yet implemented" - ))); - } - }, - ArrowDataType::FixedSizeBinary(_) => { - let array = column.as_fixed_size_binary(); - get_fsb_array_slice(array, indices.iter().copied()) - } - ArrowDataType::Decimal32(_, _) => { - let array = column.as_primitive::<Decimal32Type>(); - get_decimal_array_slice(array, indices.iter().copied()) - } - ArrowDataType::Decimal64(_, _) => { - let array = column.as_primitive::<Decimal64Type>(); - get_decimal_array_slice(array, indices.iter().copied()) - } - ArrowDataType::Decimal128(_, _) => { - let array = column.as_primitive::<Decimal128Type>(); - get_decimal_array_slice(array, indices.iter().copied()) - } - ArrowDataType::Decimal256(_, _) => { - let array = column.as_primitive::<Decimal256Type>(); - get_decimal_array_slice(array, indices.iter().copied()) - } - ArrowDataType::Float16 => { - let array = column.as_primitive::<Float16Type>(); - get_float_16_array_slice(array, indices.iter().copied()) - } - _ => { - return Err(ParquetError::NYI( - "Attempting to write an Arrow type that is not yet implemented".to_string(), - )); - } + ColumnWriter::FixedLenByteArrayColumnWriter(typed) => visit_fixed_len_byte_array( + column, + WriteFixedLenByteArray { + writer: typed, + levels, + }, + )?, + } +} + +/// Receives the values [`ArrowWriter`] stores for an Arrow array in an `INT32` +/// (`T = i32`) or `INT64` (`T = i64`) column, which are also the values hashed +/// into the column's bloom filter +/// +/// [`visit_i32`] and [`visit_i64`] hold the conversion from each Arrow type, and +/// call [`Self::slice`] when the Arrow values are stored as they are, or +/// [`Self::map`] when each value is converted. This lets the writer borrow the +/// Arrow buffer when no conversion is needed, and lets +/// [`ArrowSbbf`](crate::arrow::bloom_filter::ArrowSbbf) check converted values +/// one at a time without collecting them. +pub(crate) trait PrimitiveVisitor<T> { + type Output; + + /// Receives values that are stored as they are + fn slice(self, values: &[T]) -> Self::Output; + + /// Receives values that are each stored as `convert(value)` + fn map<S: Copy>(self, values: &[S], convert: impl Fn(S) -> T) -> Self::Output; +} + +/// Passes the values [`ArrowWriter`] stores for `column` in an `INT32` column to `visitor` +pub(crate) fn visit_i32<V: PrimitiveVisitor<i32>>( + column: &dyn arrow_array::Array, + visitor: V, +) -> Result<V::Output> { + // Note: this should match the contents of arrow_to_parquet_type + let output = match column.data_type() { + ArrowDataType::Null => visitor.slice(Int32Array::new_null(column.len()).values()), + ArrowDataType::Int8 => { + visitor.map(column.as_primitive::<Int8Type>().values(), |x| x as i32) + } + ArrowDataType::Int16 => { + visitor.map(column.as_primitive::<Int16Type>().values(), |x| x as i32) + } + ArrowDataType::Int32 => visitor.slice(column.as_primitive::<Int32Type>().values()), + ArrowDataType::UInt8 => { + visitor.map(column.as_primitive::<UInt8Type>().values(), |x| x as i32) + } + ArrowDataType::UInt16 => { + visitor.map(column.as_primitive::<UInt16Type>().values(), |x| x as i32) + } + ArrowDataType::UInt32 => { + // follow C++ implementation and use overflow/reinterpret cast from u32 to i32 which will map + // `(i32::MAX as u32)..u32::MAX` to `i32::MIN..0` + let values = column.as_primitive::<UInt32Type>().values(); + visitor.slice(values.inner().typed_data()) + } + ArrowDataType::Date32 => visitor.slice(column.as_primitive::<Date32Type>().values()), + ArrowDataType::Time32(TimeUnit::Second) => { + visitor.slice(column.as_primitive::<Time32SecondType>().values()) + } + ArrowDataType::Time32(TimeUnit::Millisecond) => { + visitor.slice(column.as_primitive::<Time32MillisecondType>().values()) + } + ArrowDataType::Date64 => { + // If the column is a Date64, we truncate it + visitor.map(column.as_primitive::<Date64Type>().values(), |x| { + (x / 86_400_000) as i32 + }) + } + ArrowDataType::Decimal32(_, _) => { + visitor.slice(column.as_primitive::<Decimal32Type>().values()) + } + ArrowDataType::Decimal64(_, _) => { + // use the int32 to represent the decimal with low precision + visitor.map(column.as_primitive::<Decimal64Type>().values(), |v| { + v as i32 + }) + } + ArrowDataType::Decimal128(_, _) => { + // use the int32 to represent the decimal with low precision + visitor.map(column.as_primitive::<Decimal128Type>().values(), |v| { + v as i32 + }) + } + ArrowDataType::Decimal256(_, _) => { + // use the int32 to represent the decimal with low precision + visitor.map(column.as_primitive::<Decimal256Type>().values(), |v| { + v.as_i128() as i32 + }) + } + d => return Err(ParquetError::General(format!("Cannot coerce {d} to I32"))), + }; + Ok(output) +} + +/// Passes the values [`ArrowWriter`] stores for `column` in an `INT64` column to `visitor` +pub(crate) fn visit_i64<V: PrimitiveVisitor<i64>>( + column: &dyn arrow_array::Array, + visitor: V, +) -> Result<V::Output> { + // Note: this should match the contents of arrow_to_parquet_type + let output = match column.data_type() { + ArrowDataType::Date64 => visitor.slice(column.as_primitive::<Date64Type>().values()), + ArrowDataType::Int64 => visitor.slice(column.as_primitive::<Int64Type>().values()), + ArrowDataType::UInt64 => { + // follow C++ implementation and use overflow/reinterpret cast from u64 to i64 which will map + // `(i64::MAX as u64)..u64::MAX` to `i64::MIN..0` + let values = column.as_primitive::<UInt64Type>().values(); + visitor.slice(values.inner().typed_data()) + } + ArrowDataType::Time64(TimeUnit::Microsecond) => { + visitor.slice(column.as_primitive::<Time64MicrosecondType>().values()) + } + ArrowDataType::Time64(TimeUnit::Nanosecond) => { + visitor.slice(column.as_primitive::<Time64NanosecondType>().values()) + } + ArrowDataType::Timestamp(unit, _) => match unit { + TimeUnit::Second => { + visitor.slice(column.as_primitive::<TimestampSecondType>().values()) + } + TimeUnit::Millisecond => { + visitor.slice(column.as_primitive::<TimestampMillisecondType>().values()) + } + TimeUnit::Microsecond => { + visitor.slice(column.as_primitive::<TimestampMicrosecondType>().values()) + } + TimeUnit::Nanosecond => { + visitor.slice(column.as_primitive::<TimestampNanosecondType>().values()) + } + }, + ArrowDataType::Duration(unit) => match unit { + TimeUnit::Second => visitor.slice(column.as_primitive::<DurationSecondType>().values()), + TimeUnit::Millisecond => { + visitor.slice(column.as_primitive::<DurationMillisecondType>().values()) + } + TimeUnit::Microsecond => { + visitor.slice(column.as_primitive::<DurationMicrosecondType>().values()) + } + TimeUnit::Nanosecond => { + visitor.slice(column.as_primitive::<DurationNanosecondType>().values()) + } + }, + ArrowDataType::Decimal64(_, _) => { + visitor.slice(column.as_primitive::<Decimal64Type>().values()) + } + ArrowDataType::Decimal128(_, _) => { + // use the int64 to represent the decimal with low precision + visitor.map(column.as_primitive::<Decimal128Type>().values(), |v| { + v as i64 + }) + } + ArrowDataType::Decimal256(_, _) => { + // use the int64 to represent the decimal with low precision + visitor.map(column.as_primitive::<Decimal256Type>().values(), |v| { + v.as_i128() as i64 + }) + } + d => return Err(ParquetError::General(format!("Cannot coerce {d} to I64"))), + }; + Ok(output) +} + +/// Writes the values passed to it to an `INT32` or `INT64` column +struct WritePrimitive<'a, 'b, E: ColumnValueEncoder> { + writer: &'a mut GenericColumnWriter<'b, E>, + levels: &'a ArrayLevels, +} + +impl<T, E> PrimitiveVisitor<T> for WritePrimitive<'_, '_, E> +where + E: ColumnValueEncoder<Values = [T]>, +{ + type Output = Result<usize>; + + fn slice(self, values: &[T]) -> Result<usize> { + write_primitive(self.writer, values, self.levels) + } + + fn map<S: Copy>(self, values: &[S], convert: impl Fn(S) -> T) -> Result<usize> { + let values: Vec<T> = values.iter().map(|v| convert(*v)).collect(); + write_primitive(self.writer, &values, self.levels) + } +} + +/// Receives the values [`ArrowWriter`] stores for an Arrow array in a +/// `FIXED_LEN_BYTE_ARRAY` column, which are also the values hashed into the +/// column's bloom filter +/// +/// [`visit_fixed_len_byte_array`] holds the conversion from each Arrow type +pub(crate) trait FixedLenByteArrayVisitor { + type Output; + + /// Returns the length of the values that decimals of `precision` are stored as + fn decimal_length(&self, precision: u8) -> usize; + + /// Receives values that are `length` bytes long + /// + /// `fill(i, value)` writes the value at index `i` of the array to `value`, + /// which is `length` zeroed bytes. It returns `false` if the value does not + /// fit in `length` bytes, which can only happen for decimals. + fn values(self, length: usize, fill: impl Fn(usize, &mut [u8]) -> bool) -> Self::Output; +} + +/// Passes the values [`ArrowWriter`] stores for `column` in a `FIXED_LEN_BYTE_ARRAY` +/// column to `visitor` +pub(crate) fn visit_fixed_len_byte_array<V: FixedLenByteArrayVisitor>( + column: &dyn arrow_array::Array, + visitor: V, +) -> Result<V::Output> { + let output = match column.data_type() { + ArrowDataType::Interval(interval_unit) => match interval_unit { + IntervalUnit::YearMonth => { + // 12 bytes of months, days and milliseconds (4 bytes each). An Arrow + // YearMonth interval only stores months, so only the first 4 bytes are set. + let array = column.as_primitive::<IntervalYearMonthType>(); + visitor.values(12, |i, value| { + value[0..4].copy_from_slice(&array.value(i).to_le_bytes()); + true + }) + } + IntervalUnit::DayTime => { + // 12 bytes of months, days and milliseconds (4 bytes each). An Arrow + // DayTime interval only stores days and milliseconds, so the first 4 + // bytes are not set. + let array = column.as_primitive::<IntervalDayTimeType>(); + visitor.values(12, |i, value| { + let interval = array.value(i); + value[4..8].copy_from_slice(&interval.days.to_le_bytes()); + value[8..12].copy_from_slice(&interval.milliseconds.to_le_bytes()); + true + }) + } + IntervalUnit::MonthDayNano => { + return Err(ParquetError::NYI(format!( + "Attempting to write an Arrow interval type {interval_unit:?} to parquet that is not yet implemented" + ))); + } + }, + ArrowDataType::FixedSizeBinary(_) => { + let array = column.as_fixed_size_binary(); + visitor.values(array.value_size(), |i, value| { + value.copy_from_slice(array.value(i)); + true + }) + } + ArrowDataType::Decimal32(_, _) => { + visit_decimal(column.as_primitive::<Decimal32Type>(), visitor) + } + ArrowDataType::Decimal64(_, _) => { + visit_decimal(column.as_primitive::<Decimal64Type>(), visitor) + } + ArrowDataType::Decimal128(_, _) => { + visit_decimal(column.as_primitive::<Decimal128Type>(), visitor) + } + ArrowDataType::Decimal256(_, _) => { + visit_decimal(column.as_primitive::<Decimal256Type>(), visitor) + } + ArrowDataType::Float16 => { + let array = column.as_primitive::<Float16Type>(); + visitor.values(2, |i, value| { + value.copy_from_slice(&array.value(i).to_le_bytes()); + true + }) + } + _ => { + return Err(ParquetError::NYI( + "Attempting to write an Arrow type that is not yet implemented".to_string(), + )); + } + }; + Ok(output) +} + +/// Passes the big-endian two's complement bytes of the values of `array` to `visitor` +fn visit_decimal<T: NativeDecimalType, V: FixedLenByteArrayVisitor>( + array: &PrimitiveArray<T>, + visitor: V, +) -> V::Output { + let length = visitor.decimal_length(array.precision()); + visitor.values(length, |i, value| { + resize_twos_complement(T::to_be_bytes(array.value(i)).as_ref(), value) + }) +} + +/// Writes the big-endian two's complement integer `bytes` to `out`, which may be +/// shorter or longer than `bytes` +/// +/// Drops leading bytes when `out` is shorter and sign-extends when it is longer. +/// Returns `false` if a dropped byte was not sign extension, that is, if the +/// integer does not fit in `out`. +#[inline] +fn resize_twos_complement(bytes: &[u8], out: &mut [u8]) -> bool { + match out.len().checked_sub(bytes.len()) { + // Same length, which lets the compiler inline the copy + Some(0) => { + out.copy_from_slice(bytes); + true + } + Some(extension) => { + let sign = if bytes.first().is_some_and(|b| (*b as i8) < 0) { + 0xFF + } else { + 0 }; - typed.write_batch_internal( - bytes.as_slice(), - None, - levels.def_level_data().as_ref(), - levels.rep_level_data().as_ref(), - None, - None, - None, - ) + out[..extension].fill(sign); + out[extension..].copy_from_slice(bytes); + true + } + None => { + let (dropped, kept) = bytes.split_at(bytes.len() - out.len()); + out.copy_from_slice(kept); + let sign = if kept.first().is_some_and(|b| (*b as i8) < 0) { + 0xFF + } else { + 0 + }; + dropped.iter().all(|b| *b == sign) } } } +/// Writes the values passed to it to a `FIXED_LEN_BYTE_ARRAY` column +struct WriteFixedLenByteArray<'a, 'b> { + writer: &'a mut ColumnWriterImpl<'b, FixedLenByteArrayType>, + levels: &'a ArrayLevels, +} + +impl FixedLenByteArrayVisitor for WriteFixedLenByteArray<'_, '_> { + type Output = Result<usize>; + + fn decimal_length(&self, precision: u8) -> usize { + decimal_length_from_precision(precision) + } + + fn values(self, length: usize, fill: impl Fn(usize, &mut [u8]) -> bool) -> Result<usize> { + let indices = self.levels.non_null_indices().iter().copied(); + // A value that does not fit is truncated, as the writer has always done + let values = chunk_array_slice(length, indices, |i, value| { + fill(i, value); Review Comment: The writer ignores the `bool`, but it still pays for the overflow check on each value (`dropped.iter().all(..)`). Before this PR the width check was done once, outside the loop. Please confirm with a benchmark that this has no cost for `Decimal128` to `FIXED_LEN_BYTE_ARRAY`. Also, the old `assert!(chunk_size <= T::BYTE_LENGTH)` is gone. Was that intentional? ########## parquet/src/arrow/bloom_filter.rs: ########## @@ -0,0 +1,612 @@ +// 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::cast::AsArray; +use arrow_array::types::{Float32Type, Float64Type}; +use arrow_array::{Array, BooleanArray}; +use arrow_buffer::BooleanBuffer; +use arrow_schema::DataType; + +use crate::arrow::arrow_writer::{ + FixedLenByteArrayVisitor, PrimitiveVisitor, visit_fixed_len_byte_array, visit_i32, visit_i64, +}; +use crate::basic::{ConvertedType, LogicalType, Type as PhysicalType}; +use crate::bloom_filter::Sbbf; +use crate::data_type::AsBytes; +use crate::errors::{ParquetError, Result}; +use crate::schema::types::ColumnDescriptor; + +/// A Parquet bloom filter ([`Sbbf`]) that can be checked with Arrow arrays +/// +/// [`ArrowWriter`] converts some Arrow types to a different Parquet physical +/// type before writing them, for example `Int8` and `UInt16` are stored as +/// `INT32`, and the bloom filter is built from the converted values. Checking +/// such a filter with [`Sbbf::check`] and the original Arrow value hashes +/// different bytes, and so reports values that are present as absent. +/// +/// [`ArrowSbbf::check`] applies the same conversion 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(); +/// +/// // Checking the Arrow value directly hashes a single byte, not the INT32 that was written +/// assert!(!sbbf.check(&1_i8)); +/// +/// let found = ArrowSbbf::new(sbbf, column) +/// .check(&Int8Array::from(vec![1, 3, 4])) +/// .unwrap(); +/// assert!(found.value(0)); +/// assert!(found.value(1)); +/// assert!(!found.value(2)); +/// ``` +/// +/// [`ArrowWriter`]: crate::arrow::ArrowWriter +#[derive(Debug, Clone, Copy)] +pub struct ArrowSbbf<'a> { + sbbf: &'a Sbbf, + physical_type: PhysicalType, + /// The length of the column's values if it is a `FIXED_LEN_BYTE_ARRAY` column + type_length: i32, + /// The scale of the column's values if it is a decimal column + decimal_scale: Option<i32>, +} + +impl<'a> ArrowSbbf<'a> { + /// Create a new [`ArrowSbbf`] for the bloom filter of the column described by `column` + pub fn new(sbbf: &'a Sbbf, column: &ColumnDescriptor) -> Self { + let decimal_scale = match column.logical_type_ref() { + Some(LogicalType::Decimal(decimal)) => Some(decimal.scale), + _ if column.converted_type() == ConvertedType::DECIMAL => Some(column.type_scale()), + _ => None, + }; + Self { + sbbf, + physical_type: column.physical_type(), + type_length: column.type_length(), + decimal_scale, + } + } + + /// 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. + /// + /// Decimal values of any precision can be checked against a decimal column + /// of the same scale. They are converted to the column's physical type and, + /// for a `FIXED_LEN_BYTE_ARRAY` column, to the column's length; a value too + /// large for that length is reported as absent. + /// + /// Returns an error if [`ArrowWriter`] cannot write `array`'s data type to a + /// column of this physical type, if `array` is a decimal array and the + /// column is not a decimal column of the same scale, or if `array` is a + /// `FixedSizeBinary` array whose values have a different length than the + /// column's. + /// + /// [`ArrowWriter`]: crate::arrow::ArrowWriter + 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()); + } + + match array.data_type() { + DataType::Null => return Ok(BooleanArray::new_null(array.len())), + DataType::Decimal32(_, scale) + | DataType::Decimal64(_, scale) + | DataType::Decimal128(_, scale) + | DataType::Decimal256(_, scale) => self.validate_decimal_scale(*scale)?, + _ => {} + } + + let sbbf = self.sbbf; + let found = match (self.physical_type, array.data_type()) { + (PhysicalType::INT32, _) => visit_i32(array, CheckPrimitive { sbbf })?, + (PhysicalType::INT64, _) => visit_i64(array, CheckPrimitive { sbbf })?, + (PhysicalType::FLOAT, DataType::Float32) => { + CheckPrimitive { sbbf }.slice(array.as_primitive::<Float32Type>().values()) + } + (PhysicalType::DOUBLE, DataType::Float64) => { + CheckPrimitive { sbbf }.slice(array.as_primitive::<Float64Type>().values()) + } + (PhysicalType::BOOLEAN, DataType::Boolean) => array + .as_boolean() + .values() + .iter() + .map(|v| sbbf.check(&v)) + .collect(), + (PhysicalType::BYTE_ARRAY, DataType::Utf8) => { + check_bytes(sbbf, array.as_string::<i32>()) + } + (PhysicalType::BYTE_ARRAY, DataType::LargeUtf8) => { + check_bytes(sbbf, array.as_string::<i64>()) + } + (PhysicalType::BYTE_ARRAY, DataType::Utf8View) => { + check_bytes(sbbf, array.as_string_view()) + } + (PhysicalType::BYTE_ARRAY, DataType::Binary) => { + check_bytes(sbbf, array.as_binary::<i32>()) + } + (PhysicalType::BYTE_ARRAY, DataType::LargeBinary) => { + check_bytes(sbbf, array.as_binary::<i64>()) + } + (PhysicalType::BYTE_ARRAY, DataType::BinaryView) => { + check_bytes(sbbf, array.as_binary_view()) + } + (PhysicalType::FIXED_LEN_BYTE_ARRAY, _) => { + let visitor = CheckFixedLenByteArray { + sbbf, + array, + // Never negative for a FIXED_LEN_BYTE_ARRAY column, which the schema checks + type_length: self.type_length as usize, + }; + visit_fixed_len_byte_array(array, visitor)?? Review Comment: Nit: the double `??` is hard to read. Maybe make the visitor `Output` the inner type, or add a short comment that explains the two layers of `Result`. ########## parquet/src/arrow/bloom_filter.rs: ########## @@ -0,0 +1,612 @@ +// 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::cast::AsArray; +use arrow_array::types::{Float32Type, Float64Type}; +use arrow_array::{Array, BooleanArray}; +use arrow_buffer::BooleanBuffer; +use arrow_schema::DataType; + +use crate::arrow::arrow_writer::{ + FixedLenByteArrayVisitor, PrimitiveVisitor, visit_fixed_len_byte_array, visit_i32, visit_i64, +}; +use crate::basic::{ConvertedType, LogicalType, Type as PhysicalType}; +use crate::bloom_filter::Sbbf; +use crate::data_type::AsBytes; +use crate::errors::{ParquetError, Result}; +use crate::schema::types::ColumnDescriptor; + +/// A Parquet bloom filter ([`Sbbf`]) that can be checked with Arrow arrays +/// +/// [`ArrowWriter`] converts some Arrow types to a different Parquet physical +/// type before writing them, for example `Int8` and `UInt16` are stored as +/// `INT32`, and the bloom filter is built from the converted values. Checking +/// such a filter with [`Sbbf::check`] and the original Arrow value hashes +/// different bytes, and so reports values that are present as absent. +/// +/// [`ArrowSbbf::check`] applies the same conversion 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(); +/// +/// // Checking the Arrow value directly hashes a single byte, not the INT32 that was written +/// assert!(!sbbf.check(&1_i8)); +/// +/// let found = ArrowSbbf::new(sbbf, column) +/// .check(&Int8Array::from(vec![1, 3, 4])) +/// .unwrap(); +/// assert!(found.value(0)); +/// assert!(found.value(1)); +/// assert!(!found.value(2)); +/// ``` +/// +/// [`ArrowWriter`]: crate::arrow::ArrowWriter +#[derive(Debug, Clone, Copy)] +pub struct ArrowSbbf<'a> { + sbbf: &'a Sbbf, + physical_type: PhysicalType, + /// The length of the column's values if it is a `FIXED_LEN_BYTE_ARRAY` column + type_length: i32, + /// The scale of the column's values if it is a decimal column + decimal_scale: Option<i32>, +} + +impl<'a> ArrowSbbf<'a> { + /// Create a new [`ArrowSbbf`] for the bloom filter of the column described by `column` + pub fn new(sbbf: &'a Sbbf, column: &ColumnDescriptor) -> Self { + let decimal_scale = match column.logical_type_ref() { + Some(LogicalType::Decimal(decimal)) => Some(decimal.scale), + _ if column.converted_type() == ConvertedType::DECIMAL => Some(column.type_scale()), + _ => None, + }; + Self { + sbbf, + physical_type: column.physical_type(), + type_length: column.type_length(), + decimal_scale, + } + } + + /// 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. + /// + /// Decimal values of any precision can be checked against a decimal column + /// of the same scale. They are converted to the column's physical type and, + /// for a `FIXED_LEN_BYTE_ARRAY` column, to the column's length; a value too + /// large for that length is reported as absent. + /// + /// Returns an error if [`ArrowWriter`] cannot write `array`'s data type to a + /// column of this physical type, if `array` is a decimal array and the + /// column is not a decimal column of the same scale, or if `array` is a + /// `FixedSizeBinary` array whose values have a different length than the + /// column's. + /// + /// [`ArrowWriter`]: crate::arrow::ArrowWriter + 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()); + } + + match array.data_type() { + DataType::Null => return Ok(BooleanArray::new_null(array.len())), + DataType::Decimal32(_, scale) + | DataType::Decimal64(_, scale) + | DataType::Decimal128(_, scale) + | DataType::Decimal256(_, scale) => self.validate_decimal_scale(*scale)?, + _ => {} + } + + let sbbf = self.sbbf; + let found = match (self.physical_type, array.data_type()) { + (PhysicalType::INT32, _) => visit_i32(array, CheckPrimitive { sbbf })?, + (PhysicalType::INT64, _) => visit_i64(array, CheckPrimitive { sbbf })?, + (PhysicalType::FLOAT, DataType::Float32) => { + CheckPrimitive { sbbf }.slice(array.as_primitive::<Float32Type>().values()) + } + (PhysicalType::DOUBLE, DataType::Float64) => { + CheckPrimitive { sbbf }.slice(array.as_primitive::<Float64Type>().values()) + } + (PhysicalType::BOOLEAN, DataType::Boolean) => array + .as_boolean() + .values() + .iter() + .map(|v| sbbf.check(&v)) + .collect(), + (PhysicalType::BYTE_ARRAY, DataType::Utf8) => { + check_bytes(sbbf, array.as_string::<i32>()) + } + (PhysicalType::BYTE_ARRAY, DataType::LargeUtf8) => { + check_bytes(sbbf, array.as_string::<i64>()) + } + (PhysicalType::BYTE_ARRAY, DataType::Utf8View) => { + check_bytes(sbbf, array.as_string_view()) + } + (PhysicalType::BYTE_ARRAY, DataType::Binary) => { + check_bytes(sbbf, array.as_binary::<i32>()) + } + (PhysicalType::BYTE_ARRAY, DataType::LargeBinary) => { + check_bytes(sbbf, array.as_binary::<i64>()) + } + (PhysicalType::BYTE_ARRAY, DataType::BinaryView) => { + check_bytes(sbbf, array.as_binary_view()) + } + (PhysicalType::FIXED_LEN_BYTE_ARRAY, _) => { + let visitor = CheckFixedLenByteArray { + sbbf, + array, + // Never negative for a FIXED_LEN_BYTE_ARRAY column, which the schema checks + type_length: self.type_length as usize, + }; + visit_fixed_len_byte_array(array, visitor)?? + } + (physical_type, data_type) => { + return Err(ParquetError::NYI(format!( + "Checking a bloom filter of a {physical_type} column with {data_type} values is not supported" + ))); + } + }; + Ok(BooleanArray::new(found, array.logical_nulls())) + } + + /// Returns an error unless the column is a decimal column of `scale` + /// + /// Decimal values are stored as unscaled integers, so a value of another + /// scale is a different integer. Converting it to the column's scale could + /// lose digits, so it is not supported. + fn validate_decimal_scale(&self, scale: i8) -> Result<()> { + match self.decimal_scale { + Some(column_scale) if column_scale == i32::from(scale) => Ok(()), + Some(column_scale) => Err(ParquetError::General(format!( + "Cannot check a bloom filter of a decimal column with scale {column_scale} with decimal values with scale {scale}" + ))), + None => Err(ParquetError::General( + "Cannot check a bloom filter of a column that is not a decimal with decimal values" + .to_string(), + )), + } + } +} + +/// Checks the `INT32`, `INT64`, `FLOAT` or `DOUBLE` values passed to it against a bloom filter +struct CheckPrimitive<'a> { + sbbf: &'a Sbbf, +} + +impl<T: AsBytes> PrimitiveVisitor<T> for CheckPrimitive<'_> { + type Output = BooleanBuffer; + + fn slice(self, values: &[T]) -> BooleanBuffer { + values.iter().map(|v| self.sbbf.check(v)).collect() + } + + fn map<S: Copy>(self, values: &[S], convert: impl Fn(S) -> T) -> BooleanBuffer { + values + .iter() + .map(|v| self.sbbf.check(&convert(*v))) + .collect() + } +} + +/// Checks the `FIXED_LEN_BYTE_ARRAY` values of `array` passed to it against a bloom filter +struct CheckFixedLenByteArray<'a> { + sbbf: &'a Sbbf, + array: &'a dyn Array, + type_length: usize, +} + +impl FixedLenByteArrayVisitor for CheckFixedLenByteArray<'_> { + type Output = Result<BooleanBuffer>; + + fn decimal_length(&self, _precision: u8) -> usize { Review Comment: Arrow does not validate decimal precision, so `Decimal128(20, 2)` can hold `i128::MAX / 3`. For a `FIXED_LEN_BYTE_ARRAY` column the writer truncates this value, but `check` on the same array returns `false`. For `INT32` and `INT64` columns, `check` truncates like the writer and returns `true`. Please make the two paths the same, or document the difference. -- 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]
