Phoenix500526 commented on code in PR #11285: URL: https://github.com/apache/arrow-rs/pull/11285#discussion_r4782303471
########## parquet/src/arrow/arrow_reader/statistics/page_index.rs: ########## @@ -0,0 +1,1594 @@ +// 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. + +//! Reads the page statistics stored in a Parquet `ColumnIndex` and puts them +//! straight into Arrow arrays. +//! +//! The usual route first builds a [`ColumnIndexMetaData`] and then copies its +//! values into Arrow arrays one by one. This module skips the middle step: it +//! reads the stored bytes once and writes each value directly into the memory +//! that will become the final Arrow array. +//! +//! [`ColumnIndexMetaData`]: crate::file::page_index::column_index::ColumnIndexMetaData + +use super::{DataPageStatistics, from_bytes_to_i256}; +use super::{from_bytes_to_f16, from_bytes_to_i32, from_bytes_to_i64, from_bytes_to_i128}; +use crate::basic::{BoundaryOrder, Type as PhysicalType}; +use crate::errors::{ParquetError, Result}; +use crate::parquet_thrift::{ + ElementType, FieldType, ReadThrift, ThriftCompactInputProtocol, ThriftSliceInputProtocol, + validate_list_type, +}; +use arrow_array::types::{ + Date32Type, Date64Type, Decimal32Type, Decimal64Type, Decimal128Type, Decimal256Type, Int8Type, + Int16Type, Time32MillisecondType, Time32SecondType, Time64MicrosecondType, + Time64NanosecondType, TimestampMicrosecondType, TimestampMillisecondType, + TimestampNanosecondType, TimestampSecondType, UInt8Type, UInt16Type, UInt32Type, UInt64Type, +}; +use arrow_array::{ + Array, ArrayRef, BinaryArray, BinaryViewArray, BooleanArray, Decimal32Array, Decimal64Array, + Decimal128Array, Decimal256Array, FixedSizeBinaryArray, Float16Array, Float32Array, + Float64Array, Int32Array, Int64Array, LargeBinaryArray, LargeStringArray, StringArray, + StringViewArray, UInt64Array, new_null_array, +}; +use arrow_buffer::{ + BooleanBuffer, BooleanBufferBuilder, NullBuffer, OffsetBuffer, ScalarBuffer, i256, +}; +use arrow_schema::{DataType, TimeUnit}; +use std::sync::Arc; + +/// The min or max values of every page, kept in the form Parquet stores them in +/// (its "physical type"), before they are turned into the Arrow type the +/// caller asked for. +#[derive(Debug)] +enum PhysicalValues { + Boolean(Vec<bool>), + Int32(Vec<i32>), + Int64(Vec<i64>), + Float(Vec<f32>), + Double(Vec<f64>), + /// Used for both `BYTE_ARRAY` and `FIXED_LEN_BYTE_ARRAY`. Fixed length + /// values are kept here too, because a stored min or max may have been + /// shortened and so may not have the expected length. + Bytes { + offsets: Vec<i32>, + values: Vec<u8>, + /// `true` for `FIXED_LEN_BYTE_ARRAY` + fixed_len: bool, + }, + /// `INT96` values are only counted, not kept. No Arrow type is read + /// from them, so their mins and maxes always come out as nulls. They are + /// still checked for length, as the older decoder does. + Int96(Vec<()>), + /// Decimals stored as bytes (in either kind of byte column), turned + /// into numbers while reading, with their precision and scale. This skips + /// keeping a copy of the bytes and converting them afterwards, which is + /// much faster. + Decimal32(Vec<i32>, u8, i8), + Decimal64(Vec<i64>, u8, i8), + Decimal128(Vec<i128>, u8, i8), + Decimal256(Vec<i256>, u8, i8), +} + +impl PhysicalValues { + /// `data_type` is the Arrow type the caller wants. It only matters for + /// decimals stored as bytes, which are turned into numbers right away. + fn new(physical_type: PhysicalType, data_type: &DataType, capacity: usize) -> Self { + use PhysicalType::{BYTE_ARRAY, FIXED_LEN_BYTE_ARRAY}; + match (physical_type, data_type) { + (BYTE_ARRAY | FIXED_LEN_BYTE_ARRAY, &DataType::Decimal32(p, s)) => { + Self::Decimal32(Vec::with_capacity(capacity), p, s) + } + (BYTE_ARRAY | FIXED_LEN_BYTE_ARRAY, &DataType::Decimal64(p, s)) => { + Self::Decimal64(Vec::with_capacity(capacity), p, s) + } + (BYTE_ARRAY | FIXED_LEN_BYTE_ARRAY, &DataType::Decimal128(p, s)) => { + Self::Decimal128(Vec::with_capacity(capacity), p, s) + } + (BYTE_ARRAY | FIXED_LEN_BYTE_ARRAY, &DataType::Decimal256(p, s)) => { + Self::Decimal256(Vec::with_capacity(capacity), p, s) + } + (BYTE_ARRAY | FIXED_LEN_BYTE_ARRAY, _) => { + let mut offsets = Vec::with_capacity(capacity + 1); + offsets.push(0); + Self::Bytes { + offsets, + values: Vec::new(), + fixed_len: physical_type == FIXED_LEN_BYTE_ARRAY, + } + } + (PhysicalType::BOOLEAN, _) => Self::Boolean(Vec::with_capacity(capacity)), + (PhysicalType::INT32, _) => Self::Int32(Vec::with_capacity(capacity)), + (PhysicalType::INT64, _) => Self::Int64(Vec::with_capacity(capacity)), + (PhysicalType::FLOAT, _) => Self::Float(Vec::with_capacity(capacity)), + (PhysicalType::DOUBLE, _) => Self::Double(Vec::with_capacity(capacity)), + (PhysicalType::INT96, _) => Self::Int96(Vec::new()), + } + } + + /// Adds `n` filler values, for pages that have no min or max. + fn append_nulls(&mut self, n: usize) { + match self { + Self::Boolean(v) => pad(v, n), + Self::Int32(v) => pad(v, n), + Self::Int64(v) => pad(v, n), + Self::Float(v) => pad(v, n), + Self::Double(v) => pad(v, n), + Self::Bytes { + offsets, values, .. + } => { + // an empty entry: it starts and ends where the data ends now + offsets.resize(offsets.len() + n, values.len() as i32) + } + Self::Int96(v) => pad(v, n), + Self::Decimal32(v, ..) => pad(v, n), + Self::Decimal64(v, ..) => pad(v, n), + Self::Decimal128(v, ..) => pad(v, n), + Self::Decimal256(v, ..) => pad(v, n), + } + } + + /// Reads one value per page from the list of binary values at the start + /// of `buf`, and returns how many bytes the list took. + /// + /// `has_min_max` holds one entry for each page in the list. Pages marked + /// `false` get a filler value, and their stored bytes are not looked at. + /// + /// The value kind is picked once for the whole list rather than once per + /// value, which is much faster. + fn read_list(&mut self, mut buf: &[u8], has_min_max: &[bool]) -> Result<usize> { + // `buf` is a local copy of the unread bytes, so the compiler can keep + // the read position in a register rather than in memory. This makes + // these loops much faster. + let start = buf.len(); + let buf = &mut buf; + match self { + Self::Boolean(v) => read_fixed(buf, v, has_min_max, |b: [u8; 1]| b[0] != 0)?, + Self::Int32(v) => read_fixed(buf, v, has_min_max, i32::from_le_bytes)?, + Self::Int64(v) => read_fixed(buf, v, has_min_max, i64::from_le_bytes)?, + Self::Float(v) => read_fixed(buf, v, has_min_max, f32::from_le_bytes)?, + Self::Double(v) => read_fixed(buf, v, has_min_max, f64::from_le_bytes)?, + Self::Bytes { + offsets, values, .. + } => { + offsets.reserve(has_min_max.len()); + for &has_value in has_min_max { + let (bytes, rest) = split_binary(buf)?; + *buf = rest; + if has_value { + values.extend_from_slice(bytes); + } + // checked once below: the data only grows, so if its + // final size fits, so does every offset before it + offsets.push(values.len() as i32); Review Comment: Could we use i64 offsets here for LargeUtf8 and LargeBinary, as the old path does? FYI: https://github.com/apache/arrow-rs/blob/f70c9679a75ff056afbad9d5334409e41b1d53c8/arrow-array/src/builder/mod.rs#L430-L440 ########## parquet/src/arrow/arrow_reader/statistics/page_index.rs: ########## @@ -0,0 +1,1594 @@ +// 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. + +//! Reads the page statistics stored in a Parquet `ColumnIndex` and puts them +//! straight into Arrow arrays. +//! +//! The usual route first builds a [`ColumnIndexMetaData`] and then copies its +//! values into Arrow arrays one by one. This module skips the middle step: it +//! reads the stored bytes once and writes each value directly into the memory +//! that will become the final Arrow array. +//! +//! [`ColumnIndexMetaData`]: crate::file::page_index::column_index::ColumnIndexMetaData + +use super::{DataPageStatistics, from_bytes_to_i256}; +use super::{from_bytes_to_f16, from_bytes_to_i32, from_bytes_to_i64, from_bytes_to_i128}; +use crate::basic::{BoundaryOrder, Type as PhysicalType}; +use crate::errors::{ParquetError, Result}; +use crate::parquet_thrift::{ + ElementType, FieldType, ReadThrift, ThriftCompactInputProtocol, ThriftSliceInputProtocol, + validate_list_type, +}; +use arrow_array::types::{ + Date32Type, Date64Type, Decimal32Type, Decimal64Type, Decimal128Type, Decimal256Type, Int8Type, + Int16Type, Time32MillisecondType, Time32SecondType, Time64MicrosecondType, + Time64NanosecondType, TimestampMicrosecondType, TimestampMillisecondType, + TimestampNanosecondType, TimestampSecondType, UInt8Type, UInt16Type, UInt32Type, UInt64Type, +}; +use arrow_array::{ + Array, ArrayRef, BinaryArray, BinaryViewArray, BooleanArray, Decimal32Array, Decimal64Array, + Decimal128Array, Decimal256Array, FixedSizeBinaryArray, Float16Array, Float32Array, + Float64Array, Int32Array, Int64Array, LargeBinaryArray, LargeStringArray, StringArray, + StringViewArray, UInt64Array, new_null_array, +}; +use arrow_buffer::{ + BooleanBuffer, BooleanBufferBuilder, NullBuffer, OffsetBuffer, ScalarBuffer, i256, +}; +use arrow_schema::{DataType, TimeUnit}; +use std::sync::Arc; + +/// The min or max values of every page, kept in the form Parquet stores them in +/// (its "physical type"), before they are turned into the Arrow type the +/// caller asked for. +#[derive(Debug)] +enum PhysicalValues { + Boolean(Vec<bool>), + Int32(Vec<i32>), + Int64(Vec<i64>), + Float(Vec<f32>), + Double(Vec<f64>), + /// Used for both `BYTE_ARRAY` and `FIXED_LEN_BYTE_ARRAY`. Fixed length + /// values are kept here too, because a stored min or max may have been + /// shortened and so may not have the expected length. + Bytes { + offsets: Vec<i32>, + values: Vec<u8>, + /// `true` for `FIXED_LEN_BYTE_ARRAY` + fixed_len: bool, + }, + /// `INT96` values are only counted, not kept. No Arrow type is read + /// from them, so their mins and maxes always come out as nulls. They are + /// still checked for length, as the older decoder does. + Int96(Vec<()>), + /// Decimals stored as bytes (in either kind of byte column), turned + /// into numbers while reading, with their precision and scale. This skips + /// keeping a copy of the bytes and converting them afterwards, which is + /// much faster. + Decimal32(Vec<i32>, u8, i8), + Decimal64(Vec<i64>, u8, i8), + Decimal128(Vec<i128>, u8, i8), + Decimal256(Vec<i256>, u8, i8), +} + +impl PhysicalValues { + /// `data_type` is the Arrow type the caller wants. It only matters for + /// decimals stored as bytes, which are turned into numbers right away. + fn new(physical_type: PhysicalType, data_type: &DataType, capacity: usize) -> Self { + use PhysicalType::{BYTE_ARRAY, FIXED_LEN_BYTE_ARRAY}; + match (physical_type, data_type) { + (BYTE_ARRAY | FIXED_LEN_BYTE_ARRAY, &DataType::Decimal32(p, s)) => { + Self::Decimal32(Vec::with_capacity(capacity), p, s) + } + (BYTE_ARRAY | FIXED_LEN_BYTE_ARRAY, &DataType::Decimal64(p, s)) => { + Self::Decimal64(Vec::with_capacity(capacity), p, s) + } + (BYTE_ARRAY | FIXED_LEN_BYTE_ARRAY, &DataType::Decimal128(p, s)) => { + Self::Decimal128(Vec::with_capacity(capacity), p, s) + } + (BYTE_ARRAY | FIXED_LEN_BYTE_ARRAY, &DataType::Decimal256(p, s)) => { + Self::Decimal256(Vec::with_capacity(capacity), p, s) + } + (BYTE_ARRAY | FIXED_LEN_BYTE_ARRAY, _) => { + let mut offsets = Vec::with_capacity(capacity + 1); + offsets.push(0); + Self::Bytes { + offsets, + values: Vec::new(), + fixed_len: physical_type == FIXED_LEN_BYTE_ARRAY, + } + } + (PhysicalType::BOOLEAN, _) => Self::Boolean(Vec::with_capacity(capacity)), + (PhysicalType::INT32, _) => Self::Int32(Vec::with_capacity(capacity)), + (PhysicalType::INT64, _) => Self::Int64(Vec::with_capacity(capacity)), + (PhysicalType::FLOAT, _) => Self::Float(Vec::with_capacity(capacity)), + (PhysicalType::DOUBLE, _) => Self::Double(Vec::with_capacity(capacity)), + (PhysicalType::INT96, _) => Self::Int96(Vec::new()), + } + } + + /// Adds `n` filler values, for pages that have no min or max. + fn append_nulls(&mut self, n: usize) { + match self { + Self::Boolean(v) => pad(v, n), + Self::Int32(v) => pad(v, n), + Self::Int64(v) => pad(v, n), + Self::Float(v) => pad(v, n), + Self::Double(v) => pad(v, n), + Self::Bytes { + offsets, values, .. + } => { + // an empty entry: it starts and ends where the data ends now + offsets.resize(offsets.len() + n, values.len() as i32) + } + Self::Int96(v) => pad(v, n), + Self::Decimal32(v, ..) => pad(v, n), + Self::Decimal64(v, ..) => pad(v, n), + Self::Decimal128(v, ..) => pad(v, n), + Self::Decimal256(v, ..) => pad(v, n), + } + } + + /// Reads one value per page from the list of binary values at the start + /// of `buf`, and returns how many bytes the list took. + /// + /// `has_min_max` holds one entry for each page in the list. Pages marked + /// `false` get a filler value, and their stored bytes are not looked at. + /// + /// The value kind is picked once for the whole list rather than once per + /// value, which is much faster. + fn read_list(&mut self, mut buf: &[u8], has_min_max: &[bool]) -> Result<usize> { + // `buf` is a local copy of the unread bytes, so the compiler can keep + // the read position in a register rather than in memory. This makes + // these loops much faster. + let start = buf.len(); + let buf = &mut buf; + match self { + Self::Boolean(v) => read_fixed(buf, v, has_min_max, |b: [u8; 1]| b[0] != 0)?, + Self::Int32(v) => read_fixed(buf, v, has_min_max, i32::from_le_bytes)?, + Self::Int64(v) => read_fixed(buf, v, has_min_max, i64::from_le_bytes)?, + Self::Float(v) => read_fixed(buf, v, has_min_max, f32::from_le_bytes)?, + Self::Double(v) => read_fixed(buf, v, has_min_max, f64::from_le_bytes)?, + Self::Bytes { + offsets, values, .. + } => { + offsets.reserve(has_min_max.len()); + for &has_value in has_min_max { + let (bytes, rest) = split_binary(buf)?; + *buf = rest; + if has_value { + values.extend_from_slice(bytes); + } + // checked once below: the data only grows, so if its + // final size fits, so does every offset before it + offsets.push(values.len() as i32); + } + bytes_end(values)?; + } + Self::Int96(v) => read_fixed(buf, v, has_min_max, |_: [u8; 12]| ())?, + Self::Decimal32(v, ..) => read_each(buf, v, has_min_max, |b| { + decimal_bytes::<4>(b).map(from_bytes_to_i32) + })?, + Self::Decimal64(v, ..) => read_each(buf, v, has_min_max, |b| { + decimal_bytes::<8>(b).map(from_bytes_to_i64) + })?, + Self::Decimal128(v, ..) => read_each(buf, v, has_min_max, |b| { + decimal_bytes::<16>(b).map(from_bytes_to_i128) + })?, + Self::Decimal256(v, ..) => read_each(buf, v, has_min_max, |b| { + decimal_bytes::<32>(b).map(from_bytes_to_i256) + })?, + } + Ok(start - buf.len()) + } + + /// Turns the `len` values into an Arrow array of `data_type`. + /// + /// This must give exactly the same results as `get_data_page_statistics!` + /// in the parent module. In particular, a value that does not fit the + /// wanted type becomes null rather than an error, and a type pair that the + /// old code does not know how to handle gives an array of nulls. + /// + /// Where the Parquet form and the Arrow type are the same, the data is + /// reused without copying. + fn finish( + self, + len: usize, + nulls: Option<NullBuffer>, + data_type: &DataType, + ) -> Result<ArrayRef> { + let converted = match self { + Self::Boolean(v) => same_type(BooleanArray::new(v.into(), nulls), data_type), + Self::Int32(v) => int32_to_logical(&Int32Array::new(v.into(), nulls), data_type)?, + Self::Int64(v) => int64_to_logical(&Int64Array::new(v.into(), nulls), data_type)?, + Self::Float(v) => same_type(Float32Array::new(v.into(), nulls), data_type), + Self::Double(v) => same_type(Float64Array::new(v.into(), nulls), data_type), + Self::Bytes { + offsets, + values, + fixed_len, + } => { + // the offsets never go down, because values are only ever added + let offsets = OffsetBuffer::new(offsets.into()); + let array = BinaryArray::new(offsets, values.into(), nulls); + bytes_to_logical(array, data_type, fixed_len)? + } + Self::Int96(_) => None, Review Comment: Now that #11348 has merged, could we reuse its INT96 conversion rules here? 🤔 This branch always returns None, even when the column declares `INT96_TIMESTAMP_ORDER` and bounds fit the requested timestamp unit. ########## parquet/src/arrow/arrow_reader/statistics/page_index.rs: ########## @@ -0,0 +1,1594 @@ +// 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. + +//! Reads the page statistics stored in a Parquet `ColumnIndex` and puts them +//! straight into Arrow arrays. +//! +//! The usual route first builds a [`ColumnIndexMetaData`] and then copies its +//! values into Arrow arrays one by one. This module skips the middle step: it +//! reads the stored bytes once and writes each value directly into the memory +//! that will become the final Arrow array. +//! +//! [`ColumnIndexMetaData`]: crate::file::page_index::column_index::ColumnIndexMetaData + +use super::{DataPageStatistics, from_bytes_to_i256}; +use super::{from_bytes_to_f16, from_bytes_to_i32, from_bytes_to_i64, from_bytes_to_i128}; +use crate::basic::{BoundaryOrder, Type as PhysicalType}; +use crate::errors::{ParquetError, Result}; +use crate::parquet_thrift::{ + ElementType, FieldType, ReadThrift, ThriftCompactInputProtocol, ThriftSliceInputProtocol, + validate_list_type, +}; +use arrow_array::types::{ + Date32Type, Date64Type, Decimal32Type, Decimal64Type, Decimal128Type, Decimal256Type, Int8Type, + Int16Type, Time32MillisecondType, Time32SecondType, Time64MicrosecondType, + Time64NanosecondType, TimestampMicrosecondType, TimestampMillisecondType, + TimestampNanosecondType, TimestampSecondType, UInt8Type, UInt16Type, UInt32Type, UInt64Type, +}; +use arrow_array::{ + Array, ArrayRef, BinaryArray, BinaryViewArray, BooleanArray, Decimal32Array, Decimal64Array, + Decimal128Array, Decimal256Array, FixedSizeBinaryArray, Float16Array, Float32Array, + Float64Array, Int32Array, Int64Array, LargeBinaryArray, LargeStringArray, StringArray, + StringViewArray, UInt64Array, new_null_array, +}; +use arrow_buffer::{ + BooleanBuffer, BooleanBufferBuilder, NullBuffer, OffsetBuffer, ScalarBuffer, i256, +}; +use arrow_schema::{DataType, TimeUnit}; +use std::sync::Arc; + +/// The min or max values of every page, kept in the form Parquet stores them in +/// (its "physical type"), before they are turned into the Arrow type the +/// caller asked for. +#[derive(Debug)] +enum PhysicalValues { + Boolean(Vec<bool>), + Int32(Vec<i32>), + Int64(Vec<i64>), + Float(Vec<f32>), + Double(Vec<f64>), + /// Used for both `BYTE_ARRAY` and `FIXED_LEN_BYTE_ARRAY`. Fixed length + /// values are kept here too, because a stored min or max may have been + /// shortened and so may not have the expected length. + Bytes { + offsets: Vec<i32>, + values: Vec<u8>, + /// `true` for `FIXED_LEN_BYTE_ARRAY` + fixed_len: bool, + }, + /// `INT96` values are only counted, not kept. No Arrow type is read + /// from them, so their mins and maxes always come out as nulls. They are + /// still checked for length, as the older decoder does. + Int96(Vec<()>), + /// Decimals stored as bytes (in either kind of byte column), turned + /// into numbers while reading, with their precision and scale. This skips + /// keeping a copy of the bytes and converting them afterwards, which is + /// much faster. + Decimal32(Vec<i32>, u8, i8), + Decimal64(Vec<i64>, u8, i8), + Decimal128(Vec<i128>, u8, i8), + Decimal256(Vec<i256>, u8, i8), +} + +impl PhysicalValues { + /// `data_type` is the Arrow type the caller wants. It only matters for + /// decimals stored as bytes, which are turned into numbers right away. + fn new(physical_type: PhysicalType, data_type: &DataType, capacity: usize) -> Self { + use PhysicalType::{BYTE_ARRAY, FIXED_LEN_BYTE_ARRAY}; + match (physical_type, data_type) { + (BYTE_ARRAY | FIXED_LEN_BYTE_ARRAY, &DataType::Decimal32(p, s)) => { + Self::Decimal32(Vec::with_capacity(capacity), p, s) + } + (BYTE_ARRAY | FIXED_LEN_BYTE_ARRAY, &DataType::Decimal64(p, s)) => { + Self::Decimal64(Vec::with_capacity(capacity), p, s) + } + (BYTE_ARRAY | FIXED_LEN_BYTE_ARRAY, &DataType::Decimal128(p, s)) => { + Self::Decimal128(Vec::with_capacity(capacity), p, s) + } + (BYTE_ARRAY | FIXED_LEN_BYTE_ARRAY, &DataType::Decimal256(p, s)) => { + Self::Decimal256(Vec::with_capacity(capacity), p, s) + } + (BYTE_ARRAY | FIXED_LEN_BYTE_ARRAY, _) => { + let mut offsets = Vec::with_capacity(capacity + 1); + offsets.push(0); + Self::Bytes { + offsets, + values: Vec::new(), + fixed_len: physical_type == FIXED_LEN_BYTE_ARRAY, + } + } + (PhysicalType::BOOLEAN, _) => Self::Boolean(Vec::with_capacity(capacity)), + (PhysicalType::INT32, _) => Self::Int32(Vec::with_capacity(capacity)), + (PhysicalType::INT64, _) => Self::Int64(Vec::with_capacity(capacity)), + (PhysicalType::FLOAT, _) => Self::Float(Vec::with_capacity(capacity)), + (PhysicalType::DOUBLE, _) => Self::Double(Vec::with_capacity(capacity)), + (PhysicalType::INT96, _) => Self::Int96(Vec::new()), + } + } + + /// Adds `n` filler values, for pages that have no min or max. + fn append_nulls(&mut self, n: usize) { + match self { + Self::Boolean(v) => pad(v, n), + Self::Int32(v) => pad(v, n), + Self::Int64(v) => pad(v, n), + Self::Float(v) => pad(v, n), + Self::Double(v) => pad(v, n), + Self::Bytes { + offsets, values, .. + } => { + // an empty entry: it starts and ends where the data ends now + offsets.resize(offsets.len() + n, values.len() as i32) + } + Self::Int96(v) => pad(v, n), + Self::Decimal32(v, ..) => pad(v, n), + Self::Decimal64(v, ..) => pad(v, n), + Self::Decimal128(v, ..) => pad(v, n), + Self::Decimal256(v, ..) => pad(v, n), + } + } + + /// Reads one value per page from the list of binary values at the start + /// of `buf`, and returns how many bytes the list took. + /// + /// `has_min_max` holds one entry for each page in the list. Pages marked + /// `false` get a filler value, and their stored bytes are not looked at. + /// + /// The value kind is picked once for the whole list rather than once per + /// value, which is much faster. + fn read_list(&mut self, mut buf: &[u8], has_min_max: &[bool]) -> Result<usize> { + // `buf` is a local copy of the unread bytes, so the compiler can keep + // the read position in a register rather than in memory. This makes + // these loops much faster. + let start = buf.len(); + let buf = &mut buf; + match self { + Self::Boolean(v) => read_fixed(buf, v, has_min_max, |b: [u8; 1]| b[0] != 0)?, + Self::Int32(v) => read_fixed(buf, v, has_min_max, i32::from_le_bytes)?, + Self::Int64(v) => read_fixed(buf, v, has_min_max, i64::from_le_bytes)?, + Self::Float(v) => read_fixed(buf, v, has_min_max, f32::from_le_bytes)?, + Self::Double(v) => read_fixed(buf, v, has_min_max, f64::from_le_bytes)?, + Self::Bytes { + offsets, values, .. + } => { + offsets.reserve(has_min_max.len()); + for &has_value in has_min_max { + let (bytes, rest) = split_binary(buf)?; + *buf = rest; + if has_value { + values.extend_from_slice(bytes); + } + // checked once below: the data only grows, so if its + // final size fits, so does every offset before it + offsets.push(values.len() as i32); + } + bytes_end(values)?; + } + Self::Int96(v) => read_fixed(buf, v, has_min_max, |_: [u8; 12]| ())?, + Self::Decimal32(v, ..) => read_each(buf, v, has_min_max, |b| { + decimal_bytes::<4>(b).map(from_bytes_to_i32) + })?, + Self::Decimal64(v, ..) => read_each(buf, v, has_min_max, |b| { + decimal_bytes::<8>(b).map(from_bytes_to_i64) + })?, + Self::Decimal128(v, ..) => read_each(buf, v, has_min_max, |b| { + decimal_bytes::<16>(b).map(from_bytes_to_i128) + })?, + Self::Decimal256(v, ..) => read_each(buf, v, has_min_max, |b| { + decimal_bytes::<32>(b).map(from_bytes_to_i256) + })?, + } + Ok(start - buf.len()) + } + + /// Turns the `len` values into an Arrow array of `data_type`. + /// + /// This must give exactly the same results as `get_data_page_statistics!` + /// in the parent module. In particular, a value that does not fit the + /// wanted type becomes null rather than an error, and a type pair that the + /// old code does not know how to handle gives an array of nulls. + /// + /// Where the Parquet form and the Arrow type are the same, the data is + /// reused without copying. + fn finish( + self, + len: usize, + nulls: Option<NullBuffer>, + data_type: &DataType, + ) -> Result<ArrayRef> { + let converted = match self { + Self::Boolean(v) => same_type(BooleanArray::new(v.into(), nulls), data_type), + Self::Int32(v) => int32_to_logical(&Int32Array::new(v.into(), nulls), data_type)?, + Self::Int64(v) => int64_to_logical(&Int64Array::new(v.into(), nulls), data_type)?, + Self::Float(v) => same_type(Float32Array::new(v.into(), nulls), data_type), + Self::Double(v) => same_type(Float64Array::new(v.into(), nulls), data_type), + Self::Bytes { + offsets, + values, + fixed_len, + } => { + // the offsets never go down, because values are only ever added + let offsets = OffsetBuffer::new(offsets.into()); + let array = BinaryArray::new(offsets, values.into(), nulls); + bytes_to_logical(array, data_type, fixed_len)? + } + Self::Int96(_) => None, + Self::Decimal32(v, p, s) => Some(Arc::new( + Decimal32Array::new(v.into(), nulls).with_precision_and_scale(p, s)?, + ) as ArrayRef), + Self::Decimal64(v, p, s) => Some(Arc::new( + Decimal64Array::new(v.into(), nulls).with_precision_and_scale(p, s)?, + ) as ArrayRef), + Self::Decimal128(v, p, s) => Some(Arc::new( + Decimal128Array::new(v.into(), nulls).with_precision_and_scale(p, s)?, + ) as ArrayRef), + Self::Decimal256(v, p, s) => Some(Arc::new( + Decimal256Array::new(v.into(), nulls).with_precision_and_scale(p, s)?, + ) as ArrayRef), + }; + // Every other pair gives nulls, as the old code does. + Ok(converted.unwrap_or_else(|| new_null_array(data_type, len))) + } +} + +/// Adds `n` default values to `v`. +fn pad<T: Default + Clone>(v: &mut Vec<T>, n: usize) { + v.resize(v.len() + n, T::default()); +} + +/// Reads byte values and turns each into a value with `convert`, one per +/// page. Pages without a min or max get a filler value, and `convert` is not +/// called for them. See [`PhysicalValues::read_list`]. +#[inline(never)] +fn read_each<T: Default>( + buf: &mut &[u8], + out: &mut Vec<T>, + has_min_max: &[bool], + convert: impl Fn(&[u8]) -> Result<T>, +) -> Result<()> { + out.reserve(has_min_max.len()); + for &has_value in has_min_max { + let (bytes, rest) = split_binary(buf)?; + *buf = rest; + out.push(if has_value { + convert(bytes)? + } else { + T::default() + }); + } + Ok(()) +} + +/// Like [`read_each`], for values that are the first `N` bytes of each +/// stored value. +#[inline(never)] +fn read_fixed<const N: usize, T: Default>( + buf: &mut &[u8], + out: &mut Vec<T>, + has_min_max: &[bool], + convert: impl Fn([u8; N]) -> T, +) -> Result<()> { + // Fill in filler values first and then overwrite them, which saves + // checking the capacity for every value. + let start = out.len(); + out.resize_with(start + has_min_max.len(), T::default); + for (slot, &has_value) in out[start..].iter_mut().zip(has_min_max) { + // Writers store each value as a one byte length of `N` followed by + // the `N` bytes, so handle that directly. Anything else, such as the + // empty value of a null page, takes the general route below. + if has_value + && let Some((&len, rest)) = buf.split_first() + && usize::from(len) == N + && let Some((value, rest)) = rest.split_first_chunk::<N>() + { + *slot = convert(*value); + *buf = rest; + continue; + } + let (bytes, rest) = split_binary(buf)?; + *buf = rest; + if has_value { + *slot = convert(first_bytes(bytes)?); + } + } + Ok(()) +} + +/// Splits one Thrift binary value off the front of `buf`, returning the +/// value and the bytes after it. A binary value is its length followed by +/// its bytes. +#[inline(always)] +fn split_binary(buf: &[u8]) -> Result<(&[u8], &[u8])> { + let (len, rest) = split_varint(buf)?; + let len = len as usize; + if rest.len() < len { + return Err(eof_err!("Unexpected EOF")); + } + Ok(rest.split_at(len)) +} + +/// Splits one stored whole number off the front of `buf`, returning the +/// number and the bytes after it. +/// +/// Numbers below 128 take a single byte, which covers nearly every length +/// and count in a page index, so that case is handled right here. Longer +/// numbers use the normal reader. +#[inline(always)] +fn split_varint(buf: &[u8]) -> Result<(u64, &[u8])> { + match buf.split_first() { + Some((&n, rest)) if n < 0x80 => Ok((n as u64, rest)), + Some(_) => { + let mut prot = ThriftSliceInputProtocol::new(buf); + Ok((prot.read_vlq()?, prot.as_slice())) + } + None => Err(eof_err!("Unexpected EOF")), + } +} + +/// The end position of the byte data, as stored in the offsets list. +fn bytes_end(values: &[u8]) -> Result<i32> { + i32::try_from(values.len()).map_err(|_| { + general_err!( + "ColumnIndex min/max values are larger than {} bytes", + i32::MAX + ) + }) +} + +/// Takes the first `N` bytes of `bytes`. +/// +/// This behaves like the older decoder: extra bytes are ignored and too few +/// bytes is an error, with the same message. +fn first_bytes<const N: usize>(bytes: &[u8]) -> Result<[u8; N]> { + match bytes.get(..N) { + Some(b) => Ok(b.try_into().unwrap()), + None => Err(general_err!( + "error converting value, expected {} bytes got {}", + N, + bytes.len() + )), + } +} + +/// Checks that a decimal stored as bytes is 1 to `N` bytes long, so it fits +/// an `N` byte number. The shared `from_bytes_to_*` helpers panic on any +/// other length, and these bytes come straight from the file. +#[inline(always)] +fn decimal_bytes<const N: usize>(bytes: &[u8]) -> Result<&[u8]> { + if bytes.is_empty() || bytes.len() > N { + return Err(general_err!( + "ColumnIndex decimal value has {} bytes, expected 1 to {N}", + bytes.len() + )); + } + Ok(bytes) +} + +/// The null or NaN counts of every page. +#[derive(Debug)] +struct Counts { + values: Vec<u64>, + /// One entry per page: `true` if its row group stored these counts. + known: BooleanBufferBuilder, +} + +impl Counts { + fn with_capacity(capacity: usize) -> Self { + Self { + values: Vec::with_capacity(capacity), + known: BooleanBufferBuilder::new(capacity), + } + } + + /// Adds `n` pages whose count is not known. + fn append_nulls(&mut self, n: usize) { + pad(&mut self.values, n); + self.known.append_n(n, false); + } + + /// Reads a list of counts, refusing negative numbers. `what` names the + /// counts in errors. + fn read(&mut self, prot: &mut ThriftSliceInputProtocol, what: &str) -> Result<()> { + let size = read_list_size(prot, ElementType::I64)?; + let mut buf = prot.as_slice(); + self.values.reserve(size); + let mut remaining = size; + while remaining > 0 { + // Counts from 0 to 63 take one byte each, with the top bit and + // the sign bit (the lowest) clear. When the next 8 counts are all + // like that, which is usual, convert them together. + if remaining >= 8 + && let Some((chunk, rest)) = buf.split_first_chunk::<8>() + && u64::from_le_bytes(*chunk) & 0x8181_8181_8181_8181 == 0 + { + self.values.extend(chunk.map(|b| u64::from(b >> 1))); + buf = rest; + remaining -= 8; + continue; + } + remaining -= 1; + // Numbers are stored so that small values of either sign are short: + // 0, -1, 1, -2, 2, ... are stored as 0, 1, 2, 3, 4, ... + let (stored, rest) = split_varint(buf)?; + buf = rest; + let count = (stored >> 1) as i64 ^ -((stored & 1) as i64); + let count = u64::try_from(count) + .map_err(|_| general_err!("ColumnIndex {what} count is negative {count}"))?; + self.values.push(count); + } + let used = prot.as_slice().len() - buf.len(); + Ok(prot.skip_bytes(used)?) + } + + /// Ends a row group of `len` pages whose counts start at `first`: checks + /// that it gave one count per page, or marks every page as unknown if it + /// gave none. + fn finish_row_group( + &mut self, + first: usize, + present: bool, + len: usize, + name: &str, + ) -> Result<()> { + if !present { + self.append_nulls(len); + return Ok(()); + } + let got = self.values.len() - first; + if got != len { + return Err(general_err!( + "ColumnIndex {name} length mismatch: expected {len}, got {got}" + )); + } + self.known.append_n(len, true); + Ok(()) + } + + fn finish(mut self) -> UInt64Array { + let nulls = NullBuffer::new(self.known.finish()); + let nulls = (nulls.null_count() > 0).then_some(nulls); + UInt64Array::new(ScalarBuffer::from(self.values), nulls) + } +} + +/// The names of the min and max fields, in the order of +/// [`ColumnIndexDecoder::min_max`]. +const MIN_MAX_NAMES: [&str; 2] = ["min_values", "max_values"]; + +/// Collects the page statistics of one column, across any number of row +/// groups, while reading the stored `ColumnIndex` bytes. +#[derive(Debug)] +pub(super) struct ColumnIndexDecoder { + /// The Arrow type the mins and maxes are turned into. A dictionary type + /// is replaced by its value type, as statistics come out as the values. + data_type: DataType, + /// One entry per page: `true` if the page has a min and max, `false` if + /// every value in the page is null (or the row group has no index). + has_min_max: Vec<bool>, + /// The mins, then the maxes. + min_max: [PhysicalValues; 2], + null_counts: Counts, + nan_counts: Counts, +} + +impl ColumnIndexDecoder { + /// `data_type` is the Arrow type the statistics will be turned into. + pub(super) fn new(physical_type: PhysicalType, data_type: &DataType, capacity: usize) -> Self { + let data_type = match data_type { + DataType::Dictionary(_, value_type) => value_type.as_ref(), + data_type => data_type, + }; Review Comment: If we have a `data_type` like `Dictionary<Int8, Dictionary<Int16, Int32>>`, then the `value_type` would be `Dictionary<Int16, Int32>` rather than `Int32` . ```suggestion let mut data_type = data_type; while let DataType::Dictionary(_, value_type) = data_type { data_type = value_type.as_ref(); } ``` -- 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]
