spark-test commented on code in PR #60314: URL: https://github.com/apache/spark/pull/60314#discussion_r4534877402
########## 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: **Non-blocking (P2):** Going by the source of serde 1.0.229, the version in Cargo.lock, an `i128` field can't be decoded from the content buffer that serde fills for `#[serde(flatten)]` fields, `untagged` enums and internally tagged enums. `Content` has no 128-bit variant, and `ContentDeserializer` and `ContentRefDeserializer` keep the default `deserialize_i128`, which returns "i128 is not supported". Encoding still works, because serialization doesn't buffer. The README (lines 106-111) tells connectors that their factory and partition types can use `untagged` and `flatten`, and this PR documents `Domain` as a value that a factory carries to the executors. Take a connector whose factory keeps the domains it was pushed in a flattened field or in an untagged enum, and a scan of `WHERE amount > 10.5` on a `decimal(10,2)` column. The driver plans the scan without trouble. Then every read task fails in `open_reader` when it decodes the factory, with "i128 is not supported", or with "data did not match any variant of untagged enum ..." for an untagged enum. Neither message points at the domains. Domains of other types, decimal domains in a plain field, and adjacently tagged enums, whose tag the derived serializer writes first, decode fine. `domains_round_trip_in_the_state_of_a_reader` decodes `Vec<Domain>` directly, so it can't catch this. A representation that the buffer holds fixes it and keeps the field an `i128` in the API, for example the decimal string through `#[serde(with = ...)]`, or two 64-bit halves. **Verification:** - **Regression:** A factory that holds decimal domains, with unscaled values beyond the 64-bit range such as i64::MAX + 1 and -(10^37), round-trips through the SDK's state encoding in a flattened field, inside an untagged enum and inside an internally tagged enum. - **Behavior:** Decimal domains in a plain field, and domains with every other kind of value and bound, still round-trip through the state encoding with equal values. ########## 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: **Nit (P3):** For an `Option<Vec<ValueRange>>`, "without ranges" reads as `None`, which the previous sentence has just defined as the opposite case: every other value is in the domain. The sentence means an empty list, which the header calls "an array without rows". A connector that takes it to mean `None` would treat the domain of `x IS NOT NULL` as admitting no value and skip data that matches. The type-level doc (line 37) and the README table get this right, so only the wording needs a fix: ```suggestion /// they are all in it. With an empty list, no value other than null or NaN is in the domain. ``` **Verification:** - **Inspection:** The doc of Domain::ranges describes None and the empty list as distinct cases, consistently with the type-level Domain doc and with the header's description of ranges without rows. ########## 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: **Non-blocking (P2):** Every domain that this suite pushes has `nan_allowed: false`, and its schema has no `float` or `double` column, so no test checks that the flag reaches the connector. Two other `push_domains` behaviors have no failing test either: - The default `ScanBuilder::push_domains`, which every connector that ignores domains runs. The suite's `Builder` overrides it, and no builder that keeps the default is ever pushed domains. - A skipped domain among used ones. Every column here has a `Value`, and the skip is only unit-tested on its own, so the position mapping, the count check and the early return in `Bridge::push_domains` (bridge.rs:185-199) never meet one. So each of these regressions would pass: - `nan_allowed` hard-coded to `false` in `abi::domains` or `Domain::from_abi`. - A default that returns the wrong number of flags, which would fail every filtered scan of a connector that ignores domains. - Used flags written by index into the passed subset instead of at each domain's position, or the builder called with an empty slice when every domain is skipped. The NaN case is the costly one. Spark sets `nan_allowed` for filters that NaN satisfies, such as `x > 10.0`, so a lost flag would let a connector skip row groups that hold matching NaN rows and return too few rows. **Verification:** - **Behavior:** Pushing domains to a scan whose builder keeps the default push_domains succeeds and reports every domain unused. - **Regression:** A domain of a double column that is pushed through the exported function table with nan_allowed set arrives at the connector with nan_allowed true, next to a domain without NaN that arrives with it false. - **Regression:** A domain of a column without a Value between used domains of supported columns yields false at its position and the connector's answers at the others, the connector sees only the supported domains, and a push of only skipped domains does not call the connector. ########## 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: **Nit (P3):** This skips a domain only when its bounds have a type without a `Value`. A domain whose ranges are NULL, like that of `tags IS NOT NULL`, has no bounds to check, so it gets through whatever the type of its column, while the domain of `tags IS NULL`, whose empty ranges array has the list type, is skipped. The README (lines 468-470), the docs of `from_abi` and `Bridge::push_domains`, and `ScanBuilder::push_domains` all say that domains of other types are skipped. Today's Spark derives domains only for types that have a `Value` (`ColumnDomains.isComparable`), so no current query hits this. But the header says that a later Spark may pass domains for other columns. On such a Spark, a connector written to the documented type set would get `Domain { path: ["tags"], ranges: None, .. }` for a list column, and if it rejects or panics on types it doesn't expect, `push_domains` and the query fail. Results can't go wrong, since a rangeless domain only excludes null and NaN. Checking the type of the resolved field here, against the types that `values()` converts, makes the skip independent of the shape of the ranges. **Verification:** - **Regression:** A domain without ranges whose path resolves to a field of a type without a Value is skipped, as the domain with an empty ranges array of the same field is. - **Behavior:** A domain without ranges of a column whose type has a Value still reaches the connector with no ranges and its null and NaN flags. -- 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]
