gengliangwang commented on code in PR #60314: URL: https://github.com/apache/spark/pull/60314#discussion_r4541392665
########## sql/native/rust/src/domain.rs: ########## @@ -0,0 +1,471 @@ +// 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. + +//! The domains of the columns that the filters of a query constrain, which a scan gets in +//! [`ScanBuilder::push_domains`](crate::ScanBuilder::push_domains). + +use std::ops::Bound; + +use arrow_array::cast::AsArray; +use arrow_array::types::{ + Date32Type, Decimal128Type, Float32Type, Float64Type, Int16Type, Int32Type, Int64Type, + Int8Type, TimestampMicrosecondType, +}; +use arrow_array::{Array, ArrayRef, BooleanArray, StructArray}; +use arrow_schema::{DataType, Fields, TimeUnit}; +use serde::{Deserialize, Serialize}; + +use crate::{abi, Result}; + +/// The domain of a column: the values that the column can have in the rows that match the +/// filters of a query. A value is in the domain when it is: +/// +/// - null, if [`null_allowed`](Self::null_allowed); +/// - NaN, if [`nan_allowed`](Self::nan_allowed), for a `float` or `double` column; +/// - another value, if [`ranges`](Self::ranges) is `None`, or if it is in one of the ranges. +/// +/// A scan can skip the data that has no value in the domain of a column, such as a file or a +/// row group whose statistics show that its values are all below the ranges, or a row whose +/// value is outside them. It must never skip a row whose values are all in their domains, since +/// Spark cannot detect it. Spark evaluates the filters again after reading, so the rows that a +/// scan returns need not match them. +/// +/// Values compare in the order of Spark SQL: +/// +/// - numbers, dates and timestamps by their values. The bounds of the ranges of a `float` or +/// `double` column are never NaN, and -0.0 is equal to 0.0: compare them with `<` and `==`, +/// not with a total order, such as [`f64::total_cmp`], that puts -0.0 before 0.0. Data that +/// has NaN values, or may have, can only be skipped if `nan_allowed` is false; +/// - strings by their UTF-8 bytes, as Rust compares `str`; +/// - binary values as unsigned bytes, in lexicographic order, as Rust compares `[u8]`; +/// - booleans with false before true. +/// +/// A domain is serializable, so that the factory of a scan can carry it to the executors. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct Domain { + /// The column, by its name in [`ScanInfo::schema`](crate::ScanInfo::schema), and then by the + /// name of its field in each struct: `["point", "x"]` is the field `x` of the column + /// `point`. + pub path: Vec<String>, + /// Whether null is in the domain. A field of a struct is null in the rows where the struct, + /// or a struct that contains it, is null, whatever the child array of the field holds there: + /// Spark never allows null for a field of a struct, since statistics computed from that + /// child array may not count these rows as nulls. + pub null_allowed: bool, + /// Whether NaN is in the domain. Always false for the columns of other types than `float` + /// and `double`. + pub nan_allowed: bool, + /// The ranges of the other values in the domain, sorted, and without overlaps, or `None` if + /// they are all in it. Without ranges, no other value than null or NaN is in the domain. + pub ranges: Option<Vec<ValueRange>>, +} + +impl Domain { + /// A domain without null or NaN, created outside Spark, for example in a test. Set + /// [`null_allowed`](Self::null_allowed) and [`nan_allowed`](Self::nan_allowed) for others. + pub fn new(path: Vec<String>, ranges: Option<Vec<ValueRange>>) -> Self { + Self { + path, + null_allowed: false, + nan_allowed: false, + ranges, + } + } + + /// The domain that Spark passes for the column at the path of `pushed`, by the indices of the + /// column in `fields`, the schema that `create_reader` got, and then of its field in each + /// struct, or `None` if the SDK has no [`Value`] for the type of the column, which a later + /// version of Spark may pass. + pub(crate) fn from_abi(fields: &Fields, pushed: &abi::PushedDomain) -> Result<Option<Self>> { + let path = &pushed.path; + let invalid = || format!("the path {path:?} of a domain is not a column of the scan"); + let (&last, parents) = path.split_last().ok_or_else(invalid)?; + let mut names = Vec::with_capacity(path.len()); + let mut fields = fields; + for &index in parents { + let field = fields.get(index).ok_or_else(invalid)?; + let DataType::Struct(children) = field.data_type() else { + return Err(invalid().into()); + }; + names.push(field.name().clone()); + fields = children; + } + names.push(fields.get(last).ok_or_else(invalid)?.name().clone()); + let ranges = match pushed.ranges.as_ref().map(value_ranges).transpose()? { + Some(None) => return Ok(None), + ranges => ranges.flatten(), + }; + Ok(Some(Self { + path: names, + null_allowed: pushed.null_allowed, + nan_allowed: pushed.nan_allowed, + ranges, + })) + } +} + +/// A range of the values of a [`Domain`]. A single value is a range whose bounds are equal and +/// included. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct ValueRange { + /// The lower bound, or [`Bound::Unbounded`] if the range has none. + pub low: Bound<Value>, + /// The upper bound, or [`Bound::Unbounded`] if the range has none. + pub high: Bound<Value>, +} + +impl ValueRange { + /// The range of a single value. + pub fn single(value: Value) -> Self { + Self { + low: Bound::Included(value.clone()), + high: Bound::Included(value), + } + } +} + +/// A value of a column, in the bounds of the ranges of a [`Domain`]. It has the type of its +/// column in [`ScanInfo::schema`](crate::ScanInfo::schema). New variants may be added for the +/// types that a later version of Spark passes domains for: a connector ignores the domains of +/// values that it does not handle. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub enum Value { + Boolean(bool), + /// A `tinyint`, `smallint`, `int`, or `bigint`. + Integer(i64), + /// A `float` or `double`, which is never NaN: a `float` is the exact value of the float. + Float(f64), + /// A `decimal(precision, scale)` of the precision and scale of its column, whose value is + /// `unscaled * 10^-scale`. + Decimal { + unscaled: i128, Review Comment: Done in c4f40143582a: `Value::Decimal::unscaled` is now encoded as its decimal string via `#[serde(with = "decimal_string")]`, so serde's buffer can hold it, and I added a round-trip test that puts decimal domains beyond the 64-bit range in a flattened field, an untagged enum and an internally tagged enum. ########## sql/native/rust/src/domain.rs: ########## @@ -0,0 +1,471 @@ +// 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. + +//! The domains of the columns that the filters of a query constrain, which a scan gets in +//! [`ScanBuilder::push_domains`](crate::ScanBuilder::push_domains). + +use std::ops::Bound; + +use arrow_array::cast::AsArray; +use arrow_array::types::{ + Date32Type, Decimal128Type, Float32Type, Float64Type, Int16Type, Int32Type, Int64Type, + Int8Type, TimestampMicrosecondType, +}; +use arrow_array::{Array, ArrayRef, BooleanArray, StructArray}; +use arrow_schema::{DataType, Fields, TimeUnit}; +use serde::{Deserialize, Serialize}; + +use crate::{abi, Result}; + +/// The domain of a column: the values that the column can have in the rows that match the +/// filters of a query. A value is in the domain when it is: +/// +/// - null, if [`null_allowed`](Self::null_allowed); +/// - NaN, if [`nan_allowed`](Self::nan_allowed), for a `float` or `double` column; +/// - another value, if [`ranges`](Self::ranges) is `None`, or if it is in one of the ranges. +/// +/// A scan can skip the data that has no value in the domain of a column, such as a file or a +/// row group whose statistics show that its values are all below the ranges, or a row whose +/// value is outside them. It must never skip a row whose values are all in their domains, since +/// Spark cannot detect it. Spark evaluates the filters again after reading, so the rows that a +/// scan returns need not match them. +/// +/// Values compare in the order of Spark SQL: +/// +/// - numbers, dates and timestamps by their values. The bounds of the ranges of a `float` or +/// `double` column are never NaN, and -0.0 is equal to 0.0: compare them with `<` and `==`, +/// not with a total order, such as [`f64::total_cmp`], that puts -0.0 before 0.0. Data that +/// has NaN values, or may have, can only be skipped if `nan_allowed` is false; +/// - strings by their UTF-8 bytes, as Rust compares `str`; +/// - binary values as unsigned bytes, in lexicographic order, as Rust compares `[u8]`; +/// - booleans with false before true. +/// +/// A domain is serializable, so that the factory of a scan can carry it to the executors. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct Domain { + /// The column, by its name in [`ScanInfo::schema`](crate::ScanInfo::schema), and then by the + /// name of its field in each struct: `["point", "x"]` is the field `x` of the column + /// `point`. + pub path: Vec<String>, + /// Whether null is in the domain. A field of a struct is null in the rows where the struct, + /// or a struct that contains it, is null, whatever the child array of the field holds there: + /// Spark never allows null for a field of a struct, since statistics computed from that + /// child array may not count these rows as nulls. + pub null_allowed: bool, + /// Whether NaN is in the domain. Always false for the columns of other types than `float` + /// and `double`. + pub nan_allowed: bool, + /// The ranges of the other values in the domain, sorted, and without overlaps, or `None` if + /// they are all in it. Without ranges, no other value than null or NaN is in the domain. Review Comment: Done in c4f40143582a: Reworded the doc of `Domain::ranges` so it says an empty list, not "without ranges". ########## sql/native/rust/tests/domains.rs: ########## @@ -0,0 +1,338 @@ +// 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. + +//! The domains that Spark pushes down to a scan through `push_domains`. + +use std::ffi::{c_int, c_void, CStr, CString}; +use std::mem::size_of; +use std::ops::Bound; +use std::ptr; +use std::sync::{Arc, Mutex, PoisonError}; + +use arrow_array::ffi::FFI_ArrowArray; +use arrow_array::{Array, ArrayRef, BooleanArray, Int64Array, StringArray, StructArray}; +use arrow_schema::{DataType, Field, Fields, Schema}; +use serde::{Deserialize, Serialize}; +use spark_datasource::__private::abi::{ + ArrowSchema, SparkDsCreateInfo, SparkDsDomain, SparkDsHost, SparkDsLibrary, SparkDsReaderInfo, + ABI_VERSION, +}; +use spark_datasource::{ + CreateInfo, DataSource, Domain, PartitionReader, PartitionReaderFactory, ReaderContext, Result, + ScanBuilder, ScanInfo, ScanPlan, Unsupported, Value, ValueRange, +}; + +// The tests share the domains that the last scan got. +static TEST_LOCK: Mutex<()> = Mutex::new(()); +static PUSHED: Mutex<Vec<Domain>> = Mutex::new(Vec::new()); + +struct Source { + mode: String, +} + +impl DataSource for Source { + type ScanBuilder = Builder; + type MicroBatchStream = Unsupported; + type BatchWrite = Unsupported; + type StreamingWrite = Unsupported; + + const INFERS_SCHEMA: bool = false; + + fn new(info: CreateInfo) -> Result<Self> { + let mode = info.options.get("mode").cloned().unwrap_or_default(); + Ok(Self { mode }) + } + + fn new_scan(&self, _: ScanInfo) -> Result<Builder> { + Ok(Builder { + mode: self.mode.clone(), + }) + } +} + +struct Builder { + mode: String, +} + +impl ScanBuilder for Builder { + type Factory = Factory; + + fn push_domains(&mut self, domains: &[Domain]) -> Result<Vec<bool>> { + *PUSHED.lock().unwrap() = domains.to_vec(); + match self.mode.as_str() { + "one_result" => Ok(vec![true]), + // Uses the domains that constrain the values, not only their nulls. + _ => Ok(domains + .iter() + .map(|domain| domain.ranges.is_some()) + .collect()), + } + } + + fn plan(self) -> Result<ScanPlan<Factory>> { + Ok(ScanPlan::new(Factory, vec![])) + } +} + +#[derive(Serialize, Deserialize)] +struct Factory; + +impl PartitionReaderFactory for Factory { + type Partition = (); + + fn open<'task>(&self, _: (), _: ReaderContext<'task>) -> Result<PartitionReader<'task>> { + Err("domain tests do not read partitions".into()) + } +} + +spark_datasource::export_data_source!(Source); + +extern "C" { + fn spark_ds_init(host: *const SparkDsHost, library: *mut *const SparkDsLibrary) -> c_int; +} + +fn library() -> &'static SparkDsLibrary { + // Spark's host structure stays valid until the JVM exits. + let host = Box::leak(Box::new(SparkDsHost { + size: size_of::<SparkDsHost>() as i64, + abi_version: ABI_VERSION, + spark_version: c"test".as_ptr(), + log: None, + is_log_enabled: None, + })); + let mut table = ptr::null(); + assert_eq!(unsafe { spark_ds_init(host, &mut table) }, 0); + unsafe { &*table } +} + +fn error(library: &SparkDsLibrary) -> String { + let message = unsafe { library.last_error.unwrap()() }; + assert!(!message.is_null()); + unsafe { CStr::from_ptr(message) }.to_str().unwrap().into() +} + +/// The columns `id BIGINT, label STRING, point STRUCT<x: INT, y: STRING>`. +fn schema() -> Schema { + let point = Fields::from(vec![ + Field::new("x", DataType::Int32, true), + Field::new("y", DataType::Utf8, true), + ]); + Schema::new(vec![ + Field::new("id", DataType::Int64, true), + Field::new("label", DataType::Utf8, true), + Field::new("point", DataType::Struct(point), true), + ]) +} + +/// The ranges of a domain, as Spark exports them: a struct array with the bounds and whether +/// each is included. +fn ranges(low: ArrayRef, high: ArrayRef, inclusive: &[(bool, bool)]) -> StructArray { + let flags = |index: fn(&(bool, bool)) -> bool| { + let flags: Vec<bool> = inclusive.iter().map(index).collect(); + Arc::new(BooleanArray::from(flags)) as ArrayRef + }; + StructArray::from(vec![ + ( + Arc::new(Field::new("low", low.data_type().clone(), true)), + low, + ), + ( + Arc::new(Field::new("high", high.data_type().clone(), true)), + high, + ), + ( + Arc::new(Field::new("low_inclusive", DataType::Boolean, false)), + flags(|flags| flags.0), + ), + ( + Arc::new(Field::new("high_inclusive", DataType::Boolean, false)), + flags(|flags| flags.1), + ), + ]) +} + +/// A domain that Spark passes, with the Arrow structs of its ranges, which Spark releases after +/// the call unless the library moved them. +struct Exported { + path: Vec<i32>, + null_allowed: bool, + ranges: Option<(Box<FFI_ArrowArray>, Box<ArrowSchema>)>, +} + +impl Exported { + fn new(path: &[i32], null_allowed: bool, ranges: Option<StructArray>) -> Self { + let ranges = ranges.map(|ranges| { + let data = ranges.into_data(); + let schema = ArrowSchema::try_from(data.data_type()).unwrap(); + (Box::new(FFI_ArrowArray::new(&data)), Box::new(schema)) + }); + Self { + path: path.to_vec(), + null_allowed, + ranges, + } + } + + fn domain(&mut self) -> SparkDsDomain { + let (ranges, ranges_schema) = match &mut self.ranges { + Some((array, schema)) => (&mut **array as *mut _, &mut **schema as *mut _), + None => (ptr::null_mut(), ptr::null_mut()), + }; + SparkDsDomain { + size: size_of::<SparkDsDomain>() as i64, + path: self.path.as_ptr(), + path_length: self.path.len() as i64, + null_allowed: self.null_allowed, + nan_allowed: false, Review Comment: Done in c4f40143582a: Added `score DOUBLE` and a time column to the test schema. A new test pushes a NaN domain and a skipped domain between used ones through the function table, and checks that a push of only skipped domains never calls the builder. Another test covers the default `push_domains`. ########## sql/native/rust/src/domain.rs: ########## @@ -0,0 +1,471 @@ +// 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. + +//! The domains of the columns that the filters of a query constrain, which a scan gets in +//! [`ScanBuilder::push_domains`](crate::ScanBuilder::push_domains). + +use std::ops::Bound; + +use arrow_array::cast::AsArray; +use arrow_array::types::{ + Date32Type, Decimal128Type, Float32Type, Float64Type, Int16Type, Int32Type, Int64Type, + Int8Type, TimestampMicrosecondType, +}; +use arrow_array::{Array, ArrayRef, BooleanArray, StructArray}; +use arrow_schema::{DataType, Fields, TimeUnit}; +use serde::{Deserialize, Serialize}; + +use crate::{abi, Result}; + +/// The domain of a column: the values that the column can have in the rows that match the +/// filters of a query. A value is in the domain when it is: +/// +/// - null, if [`null_allowed`](Self::null_allowed); +/// - NaN, if [`nan_allowed`](Self::nan_allowed), for a `float` or `double` column; +/// - another value, if [`ranges`](Self::ranges) is `None`, or if it is in one of the ranges. +/// +/// A scan can skip the data that has no value in the domain of a column, such as a file or a +/// row group whose statistics show that its values are all below the ranges, or a row whose +/// value is outside them. It must never skip a row whose values are all in their domains, since +/// Spark cannot detect it. Spark evaluates the filters again after reading, so the rows that a +/// scan returns need not match them. +/// +/// Values compare in the order of Spark SQL: +/// +/// - numbers, dates and timestamps by their values. The bounds of the ranges of a `float` or +/// `double` column are never NaN, and -0.0 is equal to 0.0: compare them with `<` and `==`, +/// not with a total order, such as [`f64::total_cmp`], that puts -0.0 before 0.0. Data that +/// has NaN values, or may have, can only be skipped if `nan_allowed` is false; +/// - strings by their UTF-8 bytes, as Rust compares `str`; +/// - binary values as unsigned bytes, in lexicographic order, as Rust compares `[u8]`; +/// - booleans with false before true. +/// +/// A domain is serializable, so that the factory of a scan can carry it to the executors. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct Domain { + /// The column, by its name in [`ScanInfo::schema`](crate::ScanInfo::schema), and then by the + /// name of its field in each struct: `["point", "x"]` is the field `x` of the column + /// `point`. + pub path: Vec<String>, + /// Whether null is in the domain. A field of a struct is null in the rows where the struct, + /// or a struct that contains it, is null, whatever the child array of the field holds there: + /// Spark never allows null for a field of a struct, since statistics computed from that + /// child array may not count these rows as nulls. + pub null_allowed: bool, + /// Whether NaN is in the domain. Always false for the columns of other types than `float` + /// and `double`. + pub nan_allowed: bool, + /// The ranges of the other values in the domain, sorted, and without overlaps, or `None` if + /// they are all in it. Without ranges, no other value than null or NaN is in the domain. + pub ranges: Option<Vec<ValueRange>>, +} + +impl Domain { + /// A domain without null or NaN, created outside Spark, for example in a test. Set + /// [`null_allowed`](Self::null_allowed) and [`nan_allowed`](Self::nan_allowed) for others. + pub fn new(path: Vec<String>, ranges: Option<Vec<ValueRange>>) -> Self { + Self { + path, + null_allowed: false, + nan_allowed: false, + ranges, + } + } + + /// The domain that Spark passes for the column at the path of `pushed`, by the indices of the + /// column in `fields`, the schema that `create_reader` got, and then of its field in each + /// struct, or `None` if the SDK has no [`Value`] for the type of the column, which a later + /// version of Spark may pass. + pub(crate) fn from_abi(fields: &Fields, pushed: &abi::PushedDomain) -> Result<Option<Self>> { + let path = &pushed.path; + let invalid = || format!("the path {path:?} of a domain is not a column of the scan"); + let (&last, parents) = path.split_last().ok_or_else(invalid)?; + let mut names = Vec::with_capacity(path.len()); + let mut fields = fields; + for &index in parents { + let field = fields.get(index).ok_or_else(invalid)?; + let DataType::Struct(children) = field.data_type() else { + return Err(invalid().into()); + }; + names.push(field.name().clone()); + fields = children; + } + names.push(fields.get(last).ok_or_else(invalid)?.name().clone()); + let ranges = match pushed.ranges.as_ref().map(value_ranges).transpose()? { Review Comment: Done in c4f40143582a: `Domain::from_abi` now checks the type of the resolved field against the types that have a `Value`, so a domain is skipped whatever the shape of its ranges. Rangeless domains of such columns are now tested in both the unit and the FFI tests. -- 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] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
