← Back to Pull requests

[SPARK-XXXXX][SQL] Push the domains of filtered columns down to native data sources #59929

Open
HyukjinKwon opened this pull request with 1873 lines diff across 14 files
View on GitHub
HyukjinKwon HyukjinKwon commented on Oct 29, 2026 17:48 UTC
Author

What changes were proposed in this pull request?

This PR adds filter pushdown to native data sources (SPARK-60101), as a follow-up of #59424, which left predicate pushdown out. Instead of passing filters to a library as expression trees, Spark passes the domains of the columns that the filters constrain: for each column, the values that it can have in the rows that match. A library compares them with the statistics of its data to skip what cannot match, such as files, row groups or blocks.

C interface. spark_datasource.h gets a new struct, SparkDsDomain, and a new optional function, push_domains. The function is appended at the end of SparkDsLibrary, after close_data_writer. A library built against the 4.4 header has a smaller table, so Spark never calls it there, and SPARK_DS_ABI_VERSION stays 1. A domain has:

  • path: the index of the column in the schema to read, then the index of the field in each struct, for a field of a struct;

  • null_allowed and nan_allowed;

  • ranges: a struct array of low, high, low_inclusive and high_inclusive, with NULL for any other value. The bounds have the Arrow type of the column in the schema to read, and a null bound means no bound. The ranges are sorted and do not overlap, and a single value is a range whose bounds are equal and inclusive.
  • The library sets used for the domains that it uses, and the plan shows the filters of those domains as PushedFilters, and the domains as PushedDomains.

    Deriving domains. ColumnDomains derives the domains from the V2 predicates that Data Source V2 pushes:

  • comparisons of a column with a literal (=, <>, <=>, <, <=, >, >=), IN, IS NULL, IS NOT NULL and STARTS_WITH;

  • combined with AND, OR and NOT. NOT is pushed to the leaves, and an OR keeps only the columns that both sides constrain.
  • The semantics are Spark's:

  • comparisons with null are null, so NOT (x IN (1, NULL)) matches no row;

  • x IN (), which the DataFrame API can build, is never true, and NOT (x IN ()) constrains no column, with or without spark.sql.legacy.nullInEmptyListBehavior;

  • NaN is equal to NaN and greater than any other value, so it is a flag (nan_allowed) rather than a bound;

  • -0.0 is normalized to 0.0;

  • strings compare by UTF-8 bytes, and only the binary collation is pushed;

  • binary values compare as unsigned bytes;

  • a field of a struct is null where the struct, or a struct that contains it, is null. Statistics computed from the Arrow child array of the field may not count these rows as nulls, so a field of a struct only gets a domain without null, which these rows never match.
  • A domain is a superset of the values of the matching rows. Spark keeps evaluating all the filters after the scan, which is the second kind of SupportsPushDownV2Filters.pushedPredicates(), as for Parquet row-group filters. So a library can only read less, never return wrong results by over-filtering. The existing push_limit and prune_columns semantics don't change: Spark still doesn't push a limit with a filter, and still reads the filtered columns.

    Other changes:

  • ColumnarScanBuilder implements SupportsPushDownV2Filters.

  • spark.sql.dataSource.native.filterPushdown.enabled (default true) turns the pushdown off, for example to check whether a library skips data that matches.
  • Example: a downstream implementation. A Rust reader with arrow-rs that keeps the domain of a bigint column id and plans only the files whose min/max statistics may match. The same check works for row groups or pages. It was compiled and tested against arrow-rs 58.3.0, with the ranges exported as Spark exports them.

    use std::ffi::{c_int, c_void};
    
    use arrow_array::cast::AsArray;
    use arrow_array::ffi::{from_ffi, FFI_ArrowArray, FFI_ArrowSchema};
    use arrow_array::types::Int64Type;
    use arrow_array::{Array, StructArray};
    
    /// SparkDsDomain, as spark_datasource.h declares it.
    #[repr(C)]
    pub struct SparkDsDomain {
        size: i64,
        path: *const i32,
        path_length: i64,
        null_allowed: bool,
        nan_allowed: bool,
        ranges: *mut FFI_ArrowArray,
        ranges_schema: *mut FFI_ArrowSchema,
    }
    
    /// A range of a bigint column: each bound with whether it is inclusive, or None if unbounded.
    struct Range {
        low: Option<(i64, bool)>,
        high: Option<(i64, bool)>,
    }
    
    /// The domain of a bigint column. `ranges` is None when all the values other than null are in it.
    struct Domain {
        null_allowed: bool,
        ranges: Option<Vec<Range>>,
    }
    
    /// The statistics of a file of the data source for the column.
    pub struct Stats {
        pub min: i64,
        pub max: i64,
        pub null_count: u64,
        pub row_count: u64,
    }
    
    impl Domain {
        /// Whether the file may have a row whose value is in the domain. This must never be false for
        /// a file that has one: Spark cannot get that row back.
        fn may_match(&self, stats: &Stats) -> bool {
            if self.null_allowed && stats.null_count > 0 {
                return true;
            }
            if stats.null_count == stats.row_count {
                return false; // Only nulls.
            }
            match &self.ranges {
                None => true,
                // [min, max] overlaps one of the ranges.
                Some(ranges) => ranges.iter().any(|range| {
                    let above_low = range.low.is_none_or(|(low, inclusive)| {
                        if inclusive { stats.max >= low } else { stats.max > low }
                    });
                    let below_high = range.high.is_none_or(|(high, inclusive)| {
                        if inclusive { stats.min <= high } else { stats.min < high }
                    });
                    above_low && below_high
                }),
            }
        }
    }
    
    pub struct Reader {
        /// The index of the column `id` in the schema that create_reader got.
        id_index: i32,
        id_domain: Option<Domain>,
        files: Vec<(String, Stats)>,
    }
    
    /// push_domains of the table: keeps the domain of `id`, and leaves the others unused.
    pub unsafe extern "C" fn push_domains(
        reader: *mut c_void,
        domains: *const *const SparkDsDomain,
        count: i64,
        used: *mut bool,
    ) -> c_int {
        let reader = unsafe { &mut *(reader as *mut Reader) };
        for i in 0..count as usize {
            let domain = unsafe { &**domains.add(i) };
            let path = unsafe { std::slice::from_raw_parts(domain.path, domain.path_length as usize) };
            if path != [reader.id_index] {
                continue;
            }
            let ranges = if domain.ranges.is_null() {
                None
            } else {
                // Moves the ranges out of the struct of Spark, which then does not release them.
                let array = unsafe { FFI_ArrowArray::from_raw(domain.ranges) };
                let Ok(data) = (unsafe { from_ffi(array, &*domain.ranges_schema) }) else {
                    return 1; // A real library also sets the message that last_error returns.
                };
                let ranges = StructArray::from(data);
                let low = ranges.column(0).as_primitive::<Int64Type>();
                let high = ranges.column(1).as_primitive::<Int64Type>();
                let low_inclusive = ranges.column(2).as_boolean();
                let high_inclusive = ranges.column(3).as_boolean();
                Some((0..ranges.len()).map(|r| Range {
                    low: low.is_valid(r).then(|| (low.value(r), low_inclusive.value(r))),
                    high: high.is_valid(r).then(|| (high.value(r), high_inclusive.value(r))),
                }).collect())
            };
            reader.id_domain = Some(Domain { null_allowed: domain.null_allowed, ranges });
            unsafe { *used.add(i) = true };
        }
        0
    }
    
    /// In partitions: plan only the files that may have a matching row.
    pub fn files_to_read(reader: &Reader) -> impl Iterator<Item = &str> {
        reader.files.iter()
            .filter(|(_, stats)| reader.id_domain.as_ref().is_none_or(|domain| domain.may_match(stats)))
            .map(|(path, _)| path.as_str())
    }
    

    The library sets push_domains: Some(push_domains) in its SparkDsLibrary. Because push_domains is the last function of the table, the struct must declare all the functions of the header, as bindgen generates them. Some points for real libraries:

  • A double or float column also needs a NaN count: a file that has NaN, or may have, can only be skipped when nan_allowed is false.

  • Compare with the IEEE operators (<, >=), not total_cmp, so that -0.0 equals 0.0.

  • A reader that skips row groups on the executors puts the domain in the state of serialize_reader.
  • <details>
    <summary>The same in C++, with Arrow C++ (compiled and tested against Arrow C++ 24)</summary>

    #include <algorithm>
    #include <cstdint>
    #include <optional>
    #include <utility>
    #include <vector>
    
    #include <arrow/api.h>
    #include <arrow/c/bridge.h>
    
    #include "spark_datasource.h"  // After Arrow C++, which defines the C data interface structs.
    
    // The statistics of a file of the data source for a bigint column.
    struct Stats {
      int64_t min, max, null_count, row_count;
    };
    
    // A range of a bigint column: each bound with whether it is inclusive, or none if unbounded.
    struct Range {
      std::optional<std::pair<int64_t, bool>> low, high;
    };
    
    // The domain of a bigint column. `ranges` is empty when all the values other than null are in it.
    struct Domain {
      bool null_allowed = true;
      std::optional<std::vector<Range>> ranges;
    
      // Whether the file may have a row whose value is in the domain. This must never be false for a
      // file that has one: Spark cannot get that row back.
      bool MayMatch(const Stats& stats) const {
        if (null_allowed && stats.null_count > 0) return true;
        if (stats.null_count == stats.row_count) return false;  // Only nulls.
        if (!ranges) return true;
        // [min, max] overlaps one of the ranges.
        return std::any_of(ranges->begin(), ranges->end(), [&](const Range& range) {
          bool above_low = !range.low || (range.low->second ? stats.max >= range.low->first
                                                             : stats.max > range.low->first);
          bool below_high = !range.high || (range.high->second ? stats.min <= range.high->first
                                                                : stats.min < range.high->first);
          return above_low && below_high;
        });
      }
    };
    
    struct Reader {
      int32_t id_index;  // The index of the column `id` in the schema that create_reader got.
      std::optional<Domain> id_domain;
    };
    
    // push_domains of the table: keeps the domain of `id`, and leaves the others unused.
    int PushDomains(void* handle, const SparkDsDomain* const* domains, int64_t count, bool* used) {
      auto* reader = static_cast<Reader*>(handle);
      for (int64_t i = 0; i < count; i++) {
        const SparkDsDomain* domain = domains[i];
        if (domain->path_length != 1 || domain->path[0] != reader->id_index) continue;
        Domain id{domain->null_allowed, std::nullopt};
        if (domain->ranges != nullptr) {
          // Moves the ranges and their schema, which Spark then does not release.
          auto imported = arrow::ImportArray(domain->ranges, domain->ranges_schema);
          if (!imported.ok()) return 1;  // A real library also sets the message of last_error.
          auto ranges = std::static_pointer_cast<arrow::StructArray>(*imported);
          auto low = std::static_pointer_cast<arrow::Int64Array>(ranges->field(0));
          auto high = std::static_pointer_cast<arrow::Int64Array>(ranges->field(1));
          auto low_inclusive = std::static_pointer_cast<arrow::BooleanArray>(ranges->field(2));
          auto high_inclusive = std::static_pointer_cast<arrow::BooleanArray>(ranges->field(3));
          id.ranges.emplace();
          for (int64_t r = 0; r < ranges->length(); r++) {
            Range range;
            if (low->IsValid(r)) range.low = std::make_pair(low->Value(r), low_inclusive->Value(r));
            if (high->IsValid(r)) range.high = std::make_pair(high->Value(r), high_inclusive->Value(r));
            id.ranges->push_back(range);
          }
        }
        reader->id_domain = id;
        used[i] = true;
      }
      return 0;
    }
    

    </details>

    Why are the changes needed?

    Without filter pushdown, a native scan reads all of its data even for selective queries. The predicate design dropped from #59424 passed JSON expression trees. That made every library implement Spark's expression semantics: three-valued logic, partial use only under AND/OR, NaN order, literal encodings. Each of these was easy to get wrong silently, as the review threads on #59424 showed.

    Domains move all of that into Spark, where it is implemented once and tested. A library only checks ranges against its statistics, as Presto/Trino (TupleDomain), DuckDB (TableFilterSet) and Velox (per-column filters) do for their scans. Expression-tree pushdown, for example with Substrait, can be added later as another function, for sources that evaluate whole expressions.

    Does this PR introduce _any_ user-facing change?

    Yes, for native data sources, which are unreleased (4.4.0):

  • a new optional function push_domains and struct SparkDsDomain in spark_datasource.h;

  • PushedFilters and PushedDomains in the plan of a native scan;

  • a new configuration, spark.sql.dataSource.native.filterPushdown.enabled.
  • How was this patch tested?

  • ColumnDomainsSuite (new):

  • - The domains of comparisons, IN (also with an empty list, from the DataFrame API), null checks, AND/OR/NOT, NaN and -0.0, strings, prefixes (including U+10FFFF and the surrogate gap), collations, binary values, nested fields (only without null) and other types.
    - A check against Spark's own evaluation. For about 450 filters, a fixed list of edge cases plus random combinations of comparisons over rows with NULL, NaN, infinities, -0.0, extreme integers, non-BMP strings, U+FFFD, high-byte binary values, and null structs and fields, every row for which Spark finds the filter true must be in the domains. The filters with empty IN lists are also checked with spark.sql.legacy.nullInEmptyListBehavior.
    - The domains of an IN list of 100,000 values, and of its NOT IN, combined with a range of the same column: they take a fraction of a second, within a limit of 20 seconds.
  • NativeDataSourceSuite, end to end with the C++ test library:

  • - The test library uses the domain of id to skip blocks of rows, and records the domains that it gets.
    - Checks the domains of ranges, of other columns, unused domains, NaN, LIKE 'n1%', a nested field, timestamps and an empty domain, domains with null (NOT (id <=> 5), name IS NULL), and domains of several ranges (id NOT IN (5, 20), and an OR whose two ranges make the library skip blocks).
    - Checks that filters on functions are not pushed, that a collated column gets no domain, also for a library that uses all the domains, a read-only library, and the configuration turned off.
    - A library built against a header without push_domains: Spark must not call it, although it is set in the table past its end.
    - The existing layout test covers the offsets of SparkDsDomain.
  • ColumnarDataSourceSuite: the same plumbing with a JVM data source, including a filter whose domain makes the data source read a row that only Spark's evaluation of a pushed predicate drops.
  • Was this patch authored or co-authored using generative AI tooling?

    Yes.

    This pull request and its description were written by Isaac.

    Diff: 1873 lines (+1831 / -42) across 14 files Reviewer: spark-test Review duration: 13458m
    All Vouch review confidence checks passed
    Residual risk 0.05 = Change Risk (0.62) × (1 − Review Confidence (0.93)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.62 · 1873 lines diff across 14 files
    0.62
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.94 · 5 substantive comment(s)
    0.94
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    92%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Real PR Conversation Timeline
    35 items
    spark-test spark-test commented on code on Oct 29, 2026 22:59 UTC
    Code Review
    sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnDomains.scala:1
    @@ -0,0 +1,534 @@
    +/*
    + * 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.
    + */
    +package org.apache.spark.sql.execution.datasources.v2.columnar
    +
    +import scala.collection.mutable.ArrayBuffer
    +
    +import org.apache.spark.SparkException
    +import org.apache.spark.sql.catalyst.expressions.Literal
    +import org.apache.spark.sql.catalyst.types.PhysicalDataType
    +import org.apache.spark.sql.catalyst.util.quoteIfNeeded
    +import org.apache.spark.sql.connector.expressions.{Expression, LiteralValue, NamedReference}
    +import org.apache.spark.sql.connector.expressions.filter.Predicate
    +import org.apache.spark.sql.types._
    +import org.apache.spark.unsafe.types.UTF8String
    +
    +/**
    + * The values that a column can have in the rows that match the filters of a query: null if
    + * `nullAllowed`, NaN if `nanAllowed`, for a float or double column, and the other values in one
    + * of the `ranges`, or any of them without ranges. A data source can skip the data whose statistics
    + * show that it has no value in the domain of a column, but never a row whose values are in their
    + * domains: Spark evaluates the filters after reading anyway.
    + *
    + * @param path the index of the column in the read schema, and then the index of the field in each
    + *             struct, for a field of a struct
    + * @param name the names of the column and of its fields
    + * @param ranges sorted ranges, which neither overlap nor touch, of the values other than null and
    + *               NaN, in the internal representation of Spark. None if the column can have any of
    + *               them, and empty if it can have none.
    + */
    +case class ColumnDomain(
    +    path: Seq[Int],
    +    name: Seq[String],
    +    dataType: DataType,
    +    nullAllowed: Boolean,
    +    nanAllowed: Boolean,
    +    ranges: Option[Seq[ValueRange]]) {
    +
    +  private def ordering: Ordering[Any] = PhysicalDataType.ordering(dataType)
    +
    +  /** Whether the domain has the value, in the internal representation of Spark. */
    +  def contains(value: Any): Boolean = value match {
    +    case null => nullAllowed
    +    case f: Float if f.isNaN => nanAllowed
    +    case d: Double if d.isNaN => nanAllowed
    +    case _ => ranges.forall(_.exists(_.contains(value, ordering)))
    +  }
    +
    +  override def toString: String = {
    +    def literal(value: Any): String = Literal(value, dataType).sql
    +    val values = ranges match {
    +      case None => Seq("ANY")
    +      case Some(ranges) => ranges.map {
    +        case ValueRange(Some(low), true, Some(high), true) if ordering.equiv(low, high) =>
    +          literal(low)
    +        case range =>
    +          (if (range.lowInclusive) "[" else "(") + range.low.map(literal).getOrElse("-inf") +
    +            ", " + range.high.map(literal).getOrElse("+inf") +
    +            (if (range.highInclusive) "]" else ")")
    +      }
    +    }
    +    val special = (if (nullAllowed) Seq("NULL") else Nil) ++ (if (nanAllowed) Seq("NaN") else Nil)
    +    val all = special ++ values
    +    s"${name.map(quoteIfNeeded).mkString(".")}: ${if (all.isEmpty) "NONE" else all.mkString(", ")}"
    +  }
    +}
    +
    +/**
    + * A range of values in the internal representation of Spark: the values above `low`, or equal to
    + * it if `lowInclusive`, and below `high`, or equal to it if `highInclusive`. A bound that is None
    + * is unbounded, and is not inclusive.
    + */
    +case class ValueRange(low: Option[Any], lowInclusive: Boolean, high: Option[Any],
    +    highInclusive: Boolean) {
    +
    +  def contains(value: Any, ordering: Ordering[Any]): Boolean = {
    +    low.forall { l =>
    +      val c = ordering.compare(value, l)
    +      c > 0 || (c == 0 && lowInclusive)
    +    } && high.forall { h =>
    +      val c = ordering.compare(value, h)
    +      c < 0 || (c == 0 && highInclusive)
    +    }
    +  }
    +}
    +
    +/**
    + * The domains that a query passes to a data source, and the predicates that each of them comes
    + * from.
    + *
    + * @param domains the domains, at most one for each column, sorted by path
    + * @param columns the paths of the columns that each predicate constrains
    + */
    +case class ColumnDomains(domains: Seq[ColumnDomain], columns: Seq[Set[Seq[Int]]]) {
    +
    +  /**
    +   * Returns the predicates that constrain only the columns whose domains are used, given whether
    +   * the data source uses each domain.
    +   */
    +  def pushedPredicates(predicates: Array[Predicate], used: Seq[Boolean]): Array[Predicate] = {
    +    val usedPaths = domains.zip(used).collect { case (domain, true) => domain.path }.toSet
    +    predicates.zip(columns).collect {
    +      case (predicate, paths) if paths.nonEmpty && paths.subsetOf(usedPaths) => predicate
    +    }
    +  }
    +}
    +
    +/**
    + * Derives the domains of the columns that the predicates of a query constrain, the ones that Data
    + * Source V2 pushes to a scan, combined with AND. A domain is a superset of the values that a column
    + * has in the rows for which all the predicates are true: Spark derives it from the comparisons of
    + * a column with literals, IN, IS NULL, IS NOT NULL and STARTS_WITH, under AND, OR and NOT, with the
    + * semantics of Spark SQL. Comparisons with null are null, NaN is equal to NaN and greater than any
    + * other value, -0.0 is equal to 0.0, and strings and binary values are compared by their bytes, as
    + * unsigned bytes. A predicate that cannot be expressed this way does not constrain any column. Only
    + * the columns and the fields of structs of the types that a data source can compare get a domain:
    + * not the strings of a non-binary collation, nor arrays, maps and structs.
    + */
    +object ColumnDomains {
    +
    +  // A column that a predicate constrains, with its type.
    +  private case class Column(path: Seq[Int], name: Seq[String], dataType: DataType) {
    +    val ordering: Ordering[Any] = PhysicalDataType.ordering(dataType)
    +    val isFloating: Boolean = dataType == FloatType || dataType == DoubleType
    +  }
    +
    +  // The values that a column can have: see ColumnDomain.
    +  private case class Values(nullAllowed: Boolean, nanAllowed: Boolean,
    +      ranges: Option[Seq[ValueRange]])
    +
    +  private val NoValue = Values(nullAllowed = false, nanAllowed = false, Some(Nil))
    +  private val OnlyNull = Values(nullAllowed = true, nanAllowed = false, Some(Nil))
    +
    +  // The columns that the predicates constrain, with their values: a row can only make the
    +  // predicates true if each of these columns has one of the values. None when no row can.
    +  private type Constraint = Option[Map[Column, Values]]
    +  private val All: Constraint = Some(Map.empty)
    +  private val NoRow: Constraint = None
    +
    +  /** Derives the domains of the predicates for a scan of the schema. */
    +  def derive(predicates: Seq[Predicate], schema: StructType): ColumnDomains = {
    +    val constraints = predicates.map(constraint(_, negated = false, schema))
    +    val columns = constraints.map(_.map(_.keySet.map(_.path)).getOrElse(Set.empty[Seq[Int]]))
    +    val domains = constraints.foldLeft(All)(and) match {
    +      case Some(values) =>
    +        values.toSeq.map { case (column, v) =>
    +          ColumnDomain(column.path, column.name, column.dataType, v.nullAllowed, v.nanAllowed,
    +            v.ranges)
    +        }.sortBy(_.path)(Ordering.Implicits.seqOrdering[Seq, Int])
    +      // A predicate that is always false, which Spark usually removes before it scans the data.
    +      case None => Nil
    +    }
    +    ColumnDomains(domains, columns)
    +  }
    +
    +  // The rows for which the predicate is true, or false if negated: NOT moves to the leaves.
    +  private def constraint(predicate: Predicate, negated: Boolean, schema: StructType): Constraint = {
    +    def child(i: Int): Option[Predicate] = predicate.children().lift(i).collect {
    +      case p: Predicate => p
    +    }
    +    def both(combine: (Constraint, Constraint) => Constraint, negated: Boolean): Constraint = {
    +      (child(0), child(1)) match {
    +        case (Some(left), Some(right)) =>
    +          combine(constraint(left, negated, schema), constraint(right, negated, schema))
    +        case _ => All
    +      }
    +    }
    +    predicate.name() match {
    +      case "AND" => if (negated) both(or, negated = true) else both(and, negated = false)
    +      case "OR" => if (negated) both(and, negated = true) else both(or, negated = false)
    +      case "NOT" => child(0).map(constraint(_, !negated, schema)).getOrElse(All)
    +      case "ALWAYS_TRUE" => if (negated) NoRow else All
    +      case "ALWAYS_FALSE" => if (negated) All else NoRow
    +      case _ => leaf(predicate, negated, schema).getOrElse(All)
    +    }
    +  }
    +
    +  private def leaf(
    +      predicate: Predicate,
    +      negated: Boolean,
    +      schema: StructType): Option[Constraint] = {
    +    val children = predicate.children()
    +    predicate.name() match {
    +      case "IS_NULL" | "IS_NOT_NULL" if children.length == 1 =>
    +        column(children(0), schema).map { col =>
    +          val isNull = (predicate.name() == "IS_NULL") != negated
    +          single(col, if (isNull) OnlyNull else anyValue(col))
    +        }
    +      case op @ ("=" | "<>" | "<=>" | "<" | "<=" | ">" | ">=") if children.length == 2 =>
    +        val operands = (column(children(0), schema), column(children(1), schema)) match {
    +          case (Some(col), _) => literal(children(1), col).map((col, _, op))
    +          case (_, Some(col)) => literal(children(0), col).map((col, _, flip(op)))
    +          case _ => None
    +        }
    +        operands.map { case (col, value, op) => compare(col, value, op, negated) }
    +      case "IN" if children.nonEmpty =>
    +        column(children(0), schema).flatMap { col =>
    +          val values = children.tail.map(literal(_, col))
    +          if (values.forall(_.isDefined)) Some(in(col, values.map(_.get).toSeq, negated)) else None
    +        }
    +      case "STARTS_WITH" if children.length == 2 =>
    +        column(children(0), schema).filter(_.dataType.isInstanceOf[StringType]).flatMap { col =>
    +          literal(children(1), col).map(prefix => startsWith(col, prefix, negated))
    +        }
    +      case _ => None
    +    }
    +  }
    +
    +  private def flip(op: String): String = op match {
    +    case "<" => ">"
    +    case "<=" => ">="
    +    case ">" => "<"
    +    case ">=" => "<="
    +    case other => other
    +  }
    +
    +  private def compare(column: Column, value: Any, op: String, negated: Boolean): Constraint = {
    +    // NOT (x <=> v) is true for null, unless v is null.
    +    val nullAllowed = op == "<=>" && negated && value != null
    +    if (value == null) {
    +      // A comparison with null is null, and so is its negation, but x <=> NULL is x IS NULL.
    +      if (op == "<=>") single(column, if (negated) anyValue(column) else OnlyNull)
    +      else single(column, NoValue)
    +    } else if (isNaN(value)) {
    +      // NaN is equal to NaN and greater than any other value: (NaN, other values).
    +      val (nan, others) = (op, negated) match {
    +        case ("=" | "<=>" | ">=", false) | ("<>" | "<", true) => (true, Some(Nil))
    +        case ("=" | "<=>" | ">=", true) | ("<>" | "<", false) => (false, None)
    +        case ("<=", false) | (">", true) => (true, None)
    +        case ("<=", true) | (">", false) => (false, Some(Nil))
    +        case _ => throw SparkException.internalError(s"Unexpected comparison $op.")
    +      }
    +      single(column, Values(nullAllowed, nan, others))
    +    } else {
    +      val v = normalize(value)
    +      // NaN is greater than v, and not equal to it.
    +      val (nan, ranges) = (op, negated) match {
    +        case ("=" | "<=>", false) | ("<>", true) => (false, Seq(point(v)))
    +        case ("=" | "<=>", true) | ("<>", false) =>
    +          (true, Seq(below(v, inclusive = false), above(v, inclusive = false)))
    +        case ("<", false) | (">=", true) => (false, Seq(below(v, inclusive = false)))
    +        case ("<=", false) | (">", true) => (false, Seq(below(v, inclusive = true)))
    +        case (">", false) | ("<=", true) => (true, Seq(above(v, inclusive = false)))
    +        case (">=", false) | ("<", true) => (true, Seq(above(v, inclusive = true)))
    +        case _ => throw SparkException.internalError(s"Unexpected comparison $op.")
    +      }
    +      single(column, Values(nullAllowed, nan, Some(ranges)))
    +    }
    +  }
    +
    +  private def in(column: Column, values: Seq[Any], negated: Boolean): Constraint = {
    +    val nonNull = values.filter(_ != null)
    +    val hasNaN = nonNull.exists(isNaN)
    +    val points = nonNull.filterNot(isNaN).map(normalize).sorted(column.ordering)
    +      .foldLeft(List.empty[Any]) {
    +        case (last :: rest, v) if column.ordering.equiv(last, v) => last :: rest
    +        case (acc, v) => v :: acc
    +      }.reverse
    +    if (!negated) {
    +      single(column, Values(nullAllowed = false, hasNaN, Some(points.map(point))))
    +    } else if (nonNull.length < values.length) {
    +      // NOT (x IN (..., NULL)) is never true: it is false or null.
    +      single(column, NoValue)
    +    } else if (points.isEmpty) {
    +      single(column, Values(nullAllowed = false, !hasNaN, None))

    Blocking (P1): When values is empty, the NULL-in-list check is 0 < 0 and points is empty, so this branch also handles NOT (x IN ()). It returns every non-null value with nullAllowed = false. Under the default semantics, though, In.eval with an empty list is false for every row, null included (predicates.scala:513-517; legacyNullInEmptyBehavior defaults to !ansiEnabled). So NOT (x IN ()) is true for rows where x is null.

    The DataFrame API builds that predicate from col("x").isin() or isInCollection(Seq.empty); SQL rejects an empty IN list. The default optimizer folds it away first. With spark.sql.optimizer.excludedRules set to OptimizeIn and NullPropagation, neither of which is non-excludable, it reaches pushPredicates. The library then gets null_allowed = false with ranges = NULL. A library that skips null-only files or row groups, as the description's may_match does, drops rows that match, and Spark's post-scan filter never sees them.

    Handling an empty list before the other branches fixes it: no value when not negated, and no constraint when negated. That is correct under both the current and the legacy semantics, without reading the legacy flag. ParquetFilters likewise builds an IN filter only when values.nonEmpty.

    Verification:

  • Regression: Deriving domains for NOT (x IN ()) built with the DataFrame API gives x no domain, and every row with a null x for which Spark evaluates the filter to true is in the derived domains.

  • Behavior: x IN () derives an empty domain, and the existing IN, NOT IN, NULL and NaN cases derive the same domains as before.
  • spark-test spark-test commented on code on Oct 29, 2026 22:59 UTC
    Code Review
    sql/core/src/main/resources/org/apache/spark/sql/datasource/spark_datasource.h:1
    @@ -350,6 +350,63 @@ typedef struct SparkDsWriteInfo {
       const char* query_id;
     } SparkDsWriteInfo;
     
    +/*
    + * The domain of a column, which push_domains gets: 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 is true;
    + * - NaN, if nan_allowed is true, for a float or double column;
    + * - another value, if ranges is NULL, or if it is in one of the ranges.
    + * A reader can skip the data whose statistics show that it has no value in the domain of a column,
    + * such as a file or a row group whose values are all below the ranges. But it must never skip a
    + * row whose values are all in their domains, which Spark cannot detect. Spark evaluates the
    + * filters again after reading, so the rows that a reader returns do not need to match them.
    + *
    + * Values are compared with 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 the comparisons of IEEE 754,
    + *   as the operators of C, C++ and Rust do, not with a total order, such as f64::total_cmp in Rust,
    + *   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, which order the characters outside the Basic Multilingual Plane
    + *   after all the others, unlike comparisons of UTF-16 strings;
    + * - binary values as unsigned bytes, in lexicographic order: X'80' is greater than X'7F', and a
    + *   value is greater than its prefixes;
    + * - booleans with false before true.
    + */
    +typedef struct SparkDsDomain {
    +  /* The size of this struct in the header that Spark was built with, as in SparkDsHost. */
    +  int64_t size;
    +  /*
    +   * The column, by the path_length indices of its fields: the index of the column in the schema to
    +   * read, the one that create_reader got, and then the index of the field in each struct, for a
    +   * field of a struct. {2, 0} is the first field of the third column.
    +   */
    +  const int32_t* path;
    +  int64_t path_length;
    +  /* Whether null is in the domain. */

    Non-blocking (P2): This defines null_allowed only as whether null is in the domain. For a struct-field path, neither the header nor the Filter Pushdown docs say what the field's value is in a row whose struct, or an enclosing struct, is null. Spark derives the domain as Spark SQL evaluates it, so the value is null there: st.y IS NULL gives st.y: NULL.

    Arrow allows a child array to hold valid values in slots where the struct is null (the header already notes a related validity trap for batches). A library that computes statistics from the child array of y can then find null_count = 0 in a block whose rows all have a null st. For st.y IS NULL it sees no null and no range, skips the block, and loses every row in it. Only null-allowing domains are affected. Readers whose statistics already count those rows as null are fine, as with Parquet's definition levels.

    One sentence here and in the docs closes it: a field is null in every row where it or an enclosing struct is null, and statistics compared with null_allowed must count those rows as null. The alternative is for Spark to withhold null-allowing domains for struct fields.

    Verification:

  • Inspection: The SparkDsDomain documentation and the Filter Pushdown documentation define a struct field's value as null in rows whose enclosing struct is null, and tell readers to count those rows as null when they compare statistics with null_allowed.
  • spark-test spark-test commented on code on Oct 29, 2026 22:59 UTC
    Code Review
    sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnDomains.scala:1
    @@ -0,0 +1,534 @@
    +/*
    + * 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.
    + */
    +package org.apache.spark.sql.execution.datasources.v2.columnar
    +
    +import scala.collection.mutable.ArrayBuffer
    +
    +import org.apache.spark.SparkException
    +import org.apache.spark.sql.catalyst.expressions.Literal
    +import org.apache.spark.sql.catalyst.types.PhysicalDataType
    +import org.apache.spark.sql.catalyst.util.quoteIfNeeded
    +import org.apache.spark.sql.connector.expressions.{Expression, LiteralValue, NamedReference}
    +import org.apache.spark.sql.connector.expressions.filter.Predicate
    +import org.apache.spark.sql.types._
    +import org.apache.spark.unsafe.types.UTF8String
    +
    +/**
    + * The values that a column can have in the rows that match the filters of a query: null if
    + * `nullAllowed`, NaN if `nanAllowed`, for a float or double column, and the other values in one
    + * of the `ranges`, or any of them without ranges. A data source can skip the data whose statistics
    + * show that it has no value in the domain of a column, but never a row whose values are in their
    + * domains: Spark evaluates the filters after reading anyway.
    + *
    + * @param path the index of the column in the read schema, and then the index of the field in each
    + *             struct, for a field of a struct
    + * @param name the names of the column and of its fields
    + * @param ranges sorted ranges, which neither overlap nor touch, of the values other than null and
    + *               NaN, in the internal representation of Spark. None if the column can have any of
    + *               them, and empty if it can have none.
    + */
    +case class ColumnDomain(
    +    path: Seq[Int],
    +    name: Seq[String],
    +    dataType: DataType,
    +    nullAllowed: Boolean,
    +    nanAllowed: Boolean,
    +    ranges: Option[Seq[ValueRange]]) {
    +
    +  private def ordering: Ordering[Any] = PhysicalDataType.ordering(dataType)
    +
    +  /** Whether the domain has the value, in the internal representation of Spark. */
    +  def contains(value: Any): Boolean = value match {
    +    case null => nullAllowed
    +    case f: Float if f.isNaN => nanAllowed
    +    case d: Double if d.isNaN => nanAllowed
    +    case _ => ranges.forall(_.exists(_.contains(value, ordering)))
    +  }
    +
    +  override def toString: String = {
    +    def literal(value: Any): String = Literal(value, dataType).sql
    +    val values = ranges match {
    +      case None => Seq("ANY")
    +      case Some(ranges) => ranges.map {
    +        case ValueRange(Some(low), true, Some(high), true) if ordering.equiv(low, high) =>
    +          literal(low)
    +        case range =>
    +          (if (range.lowInclusive) "[" else "(") + range.low.map(literal).getOrElse("-inf") +
    +            ", " + range.high.map(literal).getOrElse("+inf") +
    +            (if (range.highInclusive) "]" else ")")
    +      }
    +    }
    +    val special = (if (nullAllowed) Seq("NULL") else Nil) ++ (if (nanAllowed) Seq("NaN") else Nil)
    +    val all = special ++ values
    +    s"${name.map(quoteIfNeeded).mkString(".")}: ${if (all.isEmpty) "NONE" else all.mkString(", ")}"
    +  }
    +}
    +
    +/**
    + * A range of values in the internal representation of Spark: the values above `low`, or equal to
    + * it if `lowInclusive`, and below `high`, or equal to it if `highInclusive`. A bound that is None
    + * is unbounded, and is not inclusive.
    + */
    +case class ValueRange(low: Option[Any], lowInclusive: Boolean, high: Option[Any],
    +    highInclusive: Boolean) {
    +
    +  def contains(value: Any, ordering: Ordering[Any]): Boolean = {
    +    low.forall { l =>
    +      val c = ordering.compare(value, l)
    +      c > 0 || (c == 0 && lowInclusive)
    +    } && high.forall { h =>
    +      val c = ordering.compare(value, h)
    +      c < 0 || (c == 0 && highInclusive)
    +    }
    +  }
    +}
    +
    +/**
    + * The domains that a query passes to a data source, and the predicates that each of them comes
    + * from.
    + *
    + * @param domains the domains, at most one for each column, sorted by path
    + * @param columns the paths of the columns that each predicate constrains
    + */
    +case class ColumnDomains(domains: Seq[ColumnDomain], columns: Seq[Set[Seq[Int]]]) {
    +
    +  /**
    +   * Returns the predicates that constrain only the columns whose domains are used, given whether
    +   * the data source uses each domain.
    +   */
    +  def pushedPredicates(predicates: Array[Predicate], used: Seq[Boolean]): Array[Predicate] = {
    +    val usedPaths = domains.zip(used).collect { case (domain, true) => domain.path }.toSet
    +    predicates.zip(columns).collect {
    +      case (predicate, paths) if paths.nonEmpty && paths.subsetOf(usedPaths) => predicate
    +    }
    +  }
    +}
    +
    +/**
    + * Derives the domains of the columns that the predicates of a query constrain, the ones that Data
    + * Source V2 pushes to a scan, combined with AND. A domain is a superset of the values that a column
    + * has in the rows for which all the predicates are true: Spark derives it from the comparisons of
    + * a column with literals, IN, IS NULL, IS NOT NULL and STARTS_WITH, under AND, OR and NOT, with the
    + * semantics of Spark SQL. Comparisons with null are null, NaN is equal to NaN and greater than any
    + * other value, -0.0 is equal to 0.0, and strings and binary values are compared by their bytes, as
    + * unsigned bytes. A predicate that cannot be expressed this way does not constrain any column. Only
    + * the columns and the fields of structs of the types that a data source can compare get a domain:
    + * not the strings of a non-binary collation, nor arrays, maps and structs.
    + */
    +object ColumnDomains {
    +
    +  // A column that a predicate constrains, with its type.
    +  private case class Column(path: Seq[Int], name: Seq[String], dataType: DataType) {
    +    val ordering: Ordering[Any] = PhysicalDataType.ordering(dataType)
    +    val isFloating: Boolean = dataType == FloatType || dataType == DoubleType
    +  }
    +
    +  // The values that a column can have: see ColumnDomain.
    +  private case class Values(nullAllowed: Boolean, nanAllowed: Boolean,
    +      ranges: Option[Seq[ValueRange]])
    +
    +  private val NoValue = Values(nullAllowed = false, nanAllowed = false, Some(Nil))
    +  private val OnlyNull = Values(nullAllowed = true, nanAllowed = false, Some(Nil))
    +
    +  // The columns that the predicates constrain, with their values: a row can only make the
    +  // predicates true if each of these columns has one of the values. None when no row can.
    +  private type Constraint = Option[Map[Column, Values]]
    +  private val All: Constraint = Some(Map.empty)
    +  private val NoRow: Constraint = None
    +
    +  /** Derives the domains of the predicates for a scan of the schema. */
    +  def derive(predicates: Seq[Predicate], schema: StructType): ColumnDomains = {
    +    val constraints = predicates.map(constraint(_, negated = false, schema))
    +    val columns = constraints.map(_.map(_.keySet.map(_.path)).getOrElse(Set.empty[Seq[Int]]))
    +    val domains = constraints.foldLeft(All)(and) match {
    +      case Some(values) =>
    +        values.toSeq.map { case (column, v) =>
    +          ColumnDomain(column.path, column.name, column.dataType, v.nullAllowed, v.nanAllowed,
    +            v.ranges)
    +        }.sortBy(_.path)(Ordering.Implicits.seqOrdering[Seq, Int])
    +      // A predicate that is always false, which Spark usually removes before it scans the data.
    +      case None => Nil
    +    }
    +    ColumnDomains(domains, columns)
    +  }
    +
    +  // The rows for which the predicate is true, or false if negated: NOT moves to the leaves.
    +  private def constraint(predicate: Predicate, negated: Boolean, schema: StructType): Constraint = {
    +    def child(i: Int): Option[Predicate] = predicate.children().lift(i).collect {
    +      case p: Predicate => p
    +    }
    +    def both(combine: (Constraint, Constraint) => Constraint, negated: Boolean): Constraint = {
    +      (child(0), child(1)) match {
    +        case (Some(left), Some(right)) =>
    +          combine(constraint(left, negated, schema), constraint(right, negated, schema))
    +        case _ => All
    +      }
    +    }
    +    predicate.name() match {
    +      case "AND" => if (negated) both(or, negated = true) else both(and, negated = false)
    +      case "OR" => if (negated) both(and, negated = true) else both(or, negated = false)
    +      case "NOT" => child(0).map(constraint(_, !negated, schema)).getOrElse(All)
    +      case "ALWAYS_TRUE" => if (negated) NoRow else All
    +      case "ALWAYS_FALSE" => if (negated) All else NoRow
    +      case _ => leaf(predicate, negated, schema).getOrElse(All)
    +    }
    +  }
    +
    +  private def leaf(
    +      predicate: Predicate,
    +      negated: Boolean,
    +      schema: StructType): Option[Constraint] = {
    +    val children = predicate.children()
    +    predicate.name() match {
    +      case "IS_NULL" | "IS_NOT_NULL" if children.length == 1 =>
    +        column(children(0), schema).map { col =>
    +          val isNull = (predicate.name() == "IS_NULL") != negated
    +          single(col, if (isNull) OnlyNull else anyValue(col))
    +        }
    +      case op @ ("=" | "<>" | "<=>" | "<" | "<=" | ">" | ">=") if children.length == 2 =>
    +        val operands = (column(children(0), schema), column(children(1), schema)) match {
    +          case (Some(col), _) => literal(children(1), col).map((col, _, op))
    +          case (_, Some(col)) => literal(children(0), col).map((col, _, flip(op)))
    +          case _ => None
    +        }
    +        operands.map { case (col, value, op) => compare(col, value, op, negated) }
    +      case "IN" if children.nonEmpty =>
    +        column(children(0), schema).flatMap { col =>
    +          val values = children.tail.map(literal(_, col))
    +          if (values.forall(_.isDefined)) Some(in(col, values.map(_.get).toSeq, negated)) else None
    +        }
    +      case "STARTS_WITH" if children.length == 2 =>
    +        column(children(0), schema).filter(_.dataType.isInstanceOf[StringType]).flatMap { col =>
    +          literal(children(1), col).map(prefix => startsWith(col, prefix, negated))
    +        }
    +      case _ => None
    +    }
    +  }
    +
    +  private def flip(op: String): String = op match {
    +    case "<" => ">"
    +    case "<=" => ">="
    +    case ">" => "<"
    +    case ">=" => "<="
    +    case other => other
    +  }
    +
    +  private def compare(column: Column, value: Any, op: String, negated: Boolean): Constraint = {
    +    // NOT (x <=> v) is true for null, unless v is null.
    +    val nullAllowed = op == "<=>" && negated && value != null
    +    if (value == null) {
    +      // A comparison with null is null, and so is its negation, but x <=> NULL is x IS NULL.
    +      if (op == "<=>") single(column, if (negated) anyValue(column) else OnlyNull)
    +      else single(column, NoValue)
    +    } else if (isNaN(value)) {
    +      // NaN is equal to NaN and greater than any other value: (NaN, other values).
    +      val (nan, others) = (op, negated) match {
    +        case ("=" | "<=>" | ">=", false) | ("<>" | "<", true) => (true, Some(Nil))
    +        case ("=" | "<=>" | ">=", true) | ("<>" | "<", false) => (false, None)
    +        case ("<=", false) | (">", true) => (true, None)
    +        case ("<=", true) | (">", false) => (false, Some(Nil))
    +        case _ => throw SparkException.internalError(s"Unexpected comparison $op.")
    +      }
    +      single(column, Values(nullAllowed, nan, others))
    +    } else {
    +      val v = normalize(value)
    +      // NaN is greater than v, and not equal to it.
    +      val (nan, ranges) = (op, negated) match {
    +        case ("=" | "<=>", false) | ("<>", true) => (false, Seq(point(v)))
    +        case ("=" | "<=>", true) | ("<>", false) =>
    +          (true, Seq(below(v, inclusive = false), above(v, inclusive = false)))
    +        case ("<", false) | (">=", true) => (false, Seq(below(v, inclusive = false)))
    +        case ("<=", false) | (">", true) => (false, Seq(below(v, inclusive = true)))
    +        case (">", false) | ("<=", true) => (true, Seq(above(v, inclusive = false)))
    +        case (">=", false) | ("<", true) => (true, Seq(above(v, inclusive = true)))
    +        case _ => throw SparkException.internalError(s"Unexpected comparison $op.")
    +      }
    +      single(column, Values(nullAllowed, nan, Some(ranges)))
    +    }
    +  }
    +
    +  private def in(column: Column, values: Seq[Any], negated: Boolean): Constraint = {
    +    val nonNull = values.filter(_ != null)
    +    val hasNaN = nonNull.exists(isNaN)
    +    val points = nonNull.filterNot(isNaN).map(normalize).sorted(column.ordering)
    +      .foldLeft(List.empty[Any]) {
    +        case (last :: rest, v) if column.ordering.equiv(last, v) => last :: rest
    +        case (acc, v) => v :: acc
    +      }.reverse
    +    if (!negated) {
    +      single(column, Values(nullAllowed = false, hasNaN, Some(points.map(point))))
    +    } else if (nonNull.length < values.length) {
    +      // NOT (x IN (..., NULL)) is never true: it is false or null.
    +      single(column, NoValue)
    +    } else if (points.isEmpty) {
    +      single(column, Values(nullAllowed = false, !hasNaN, None))
    +    } else {
    +      // The values between the points.
    +      val bounds = None +: points.map(Some(_)) :+ None
    +      val gaps = bounds.zip(bounds.tail).map { case (low, high) =>
    +        ValueRange(low, lowInclusive = false, high = high, highInclusive = false)
    +      }
    +      single(column, Values(nullAllowed = false, !hasNaN, Some(gaps)))
    +    }
    +  }
    +
    +  private def startsWith(column: Column, prefix: Any, negated: Boolean): Constraint = {
    +    (prefix, negated) match {
    +      case (null, _) => single(column, NoValue)
    +      // The strings that do not start with the prefix are not a range. A value whose bytes are not
    +      // valid UTF-8 could even be in the range of the strings that do.
    +      case (_, true) => single(column, anyValue(column))
    +      case (prefix: UTF8String, false) if prefix.numBytes() == 0 => single(column, anyValue(column))
    +      case (prefix: UTF8String, false) =>
    +        val range = ValueRange(Some(prefix), lowInclusive = true, high = nextPrefix(prefix),
    +          highInclusive = false)
    +        single(column, Values(nullAllowed = false, nanAllowed = false, Some(Seq(range))))
    +      case _ => All
    +    }
    +  }
    +
    +  /**
    +   * Returns the smallest string that is greater than all the strings that start with the prefix,
    +   * in the order of their UTF-8 bytes, which is the order of their code points, or None if there
    +   * is none: the prefix with its last code point incremented, after dropping the trailing
    +   * U+10FFFF, the largest code point.
    +   */
    +  private[columnar] def nextPrefix(prefix: UTF8String): Option[UTF8String] = {
    +    val codePoints = prefix.toString.codePoints().toArray.toBuffer
    +    while (codePoints.nonEmpty && codePoints.last == Character.MAX_CODE_POINT) {
    +      codePoints.remove(codePoints.length - 1)
    +    }
    +    if (codePoints.isEmpty) {
    +      None
    +    } else {
    +      val last = codePoints.last + 1
    +      // Skips the surrogates, which are not code points of characters.
    +      codePoints(codePoints.length - 1) =
    +        if (last >= Character.MIN_SURROGATE && last <= Character.MAX_SURROGATE) {
    +          Character.MAX_SURROGATE + 1
    +        } else {
    +          last
    +        }
    +      Some(UTF8String.fromString(new String(codePoints.toArray, 0, codePoints.length)))
    +    }
    +  }
    +
    +  private def single(column: Column, values: Values): Constraint = {
    +    // Only floating-point columns have NaN.
    +    val normalized = values.copy(nanAllowed = values.nanAllowed && column.isFloating)
    +    if (isAll(column, normalized)) All else Some(Map(column -> normalized))
    +  }
    +
    +  private def point(v: Any): ValueRange =
    +    ValueRange(Some(v), lowInclusive = true, high = Some(v), highInclusive = true)
    +
    +  private def below(v: Any, inclusive: Boolean): ValueRange =
    +    ValueRange(None, lowInclusive = false, high = Some(v), highInclusive = inclusive)
    +
    +  private def above(v: Any, inclusive: Boolean): ValueRange =
    +    ValueRange(Some(v), lowInclusive = inclusive, high = None, highInclusive = false)
    +
    +  private def anyValue(column: Column): Values = {
    +    Values(nullAllowed = false, nanAllowed = column.isFloating, None)
    +  }
    +
    +  private def isAll(column: Column, values: Values): Boolean = {
    +    values.nullAllowed && values.ranges.isEmpty && (values.nanAllowed || !column.isFloating)
    +  }
    +
    +  private def isEmpty(values: Values): Boolean = {
    +    !values.nullAllowed && !values.nanAllowed && values.ranges.exists(_.isEmpty)
    +  }
    +
    +  // Whether no row can make the predicates true.
    +  private def matchesNoRow(constraint: Constraint): Boolean = {
    +    constraint.forall(_.values.exists(isEmpty))
    +  }
    +
    +  private def and(left: Constraint, right: Constraint): Constraint = (left, right) match {
    +    case (Some(l), Some(r)) =>
    +      Some((l.keySet ++ r.keySet).map { column =>
    +        column -> ((l.get(column), r.get(column)) match {
    +          case (Some(a), Some(b)) => intersect(column, a, b)
    +          case (a, b) => a.orElse(b).get
    +        })
    +      }.toMap)
    +    case _ => NoRow
    +  }
    +
    +  // A column that only one side constrains can have any value in the rows of the other side, so
    +  // only the columns that both sides constrain are constrained.
    +  private def or(left: Constraint, right: Constraint): Constraint = {
    +    if (matchesNoRow(left)) {
    +      right
    +    } else if (matchesNoRow(right)) {
    +      left
    +    } else {
    +      val (l, r) = (left.get, right.get)
    +      Some(l.keySet.intersect(r.keySet).map(column => column -> union(column, l(column), r(column)))
    +        .filterNot { case (column, values) => isAll(column, values) }.toMap)
    +    }
    +  }
    +
    +  private def intersect(column: Column, a: Values, b: Values): Values = Values(
    +    a.nullAllowed && b.nullAllowed,
    +    a.nanAllowed && b.nanAllowed,
    +    (a.ranges, b.ranges) match {
    +      case (Some(x), Some(y)) => Some(intersectRanges(x, y, column.ordering))
    +      case (x, y) => x.orElse(y)
    +    })
    +
    +  private def union(column: Column, a: Values, b: Values): Values = Values(
    +    a.nullAllowed || b.nullAllowed,
    +    a.nanAllowed || b.nanAllowed,
    +    (a.ranges, b.ranges) match {
    +      case (Some(x), Some(y)) =>
    +        unionRanges(x, y, column.ordering) match {
    +          // All the values.
    +          case Seq(ValueRange(None, _, None, _)) => None
    +          case ranges => Some(ranges)
    +        }
    +      case _ => None
    +    })
    +
    +  // A negative value when `a` starts before `b`.
    +  private def compareLows(a: ValueRange, b: ValueRange, ordering: Ordering[Any]): Int = {
    +    (a.low, b.low) match {
    +      case (None, None) => 0
    +      case (None, _) => -1
    +      case (_, None) => 1
    +      case (Some(x), Some(y)) =>
    +        val c = ordering.compare(x, y)
    +        if (c != 0 || a.lowInclusive == b.lowInclusive) c else if (a.lowInclusive) -1 else 1
    +    }
    +  }
    +
    +  // A negative value when `a` ends before `b`.
    +  private def compareHighs(a: ValueRange, b: ValueRange, ordering: Ordering[Any]): Int = {
    +    (a.high, b.high) match {
    +      case (None, None) => 0
    +      case (None, _) => 1
    +      case (_, None) => -1
    +      case (Some(x), Some(y)) =>
    +        val c = ordering.compare(x, y)
    +        if (c != 0 || a.highInclusive == b.highInclusive) c else if (a.highInclusive) 1 else -1
    +    }
    +  }
    +
    +  private def isEmptyRange(range: ValueRange, ordering: Ordering[Any]): Boolean = {
    +    (range.low, range.high) match {
    +      case (Some(low), Some(high)) =>
    +        val c = ordering.compare(low, high)
    +        c > 0 || (c == 0 && !(range.lowInclusive && range.highInclusive))
    +      case _ => false
    +    }
    +  }
    +
    +  // Intersects two lists of sorted ranges that neither overlap nor touch, by sweeping them.
    +  private def intersectRanges(
    +      a: Seq[ValueRange],
    +      b: Seq[ValueRange],
    +      ordering: Ordering[Any]): Seq[ValueRange] = {
    +    val result = ArrayBuffer.empty[ValueRange]
    +    var i = 0
    +    var j = 0
    +    while (i < a.length && j < b.length) {

    Non-blocking (P2): Every range sequence that reaches this loop is a List: Seq(...) in compare and startsWith, the point and gap lists of in, the result of unionRanges, and result.toSeq on the ArrayBuffer below. List.length and List.apply are linear, so each iteration re-walks both inputs, and the sweep is quadratic in the number of ranges.

    This runs on the driver during optimization, by default for every native batch scan, whenever two pushed predicates constrain the same column with ranges. Take col("id").isin(ids: _*) && col("id") > 0 with 10^5 ids: OptimizeIn turns the list into an InSet, which is pushed as one IN carrying every literal. That makes about 10^10 list-node visits, tens of seconds of planning, and around 3 x 10^4 literals it already takes seconds. A NOT IN list, or two IN lists on one column, behaves the same.

    Converting both inputs once with toIndexedSeq, or walking them with buffered iterators, restores the linear sweep without changing any domain.

    Verification:

  • Inspection: The intersection sweep reads its inputs through constant-time indexing or iteration, so apart from the value comparisons each step does constant work.

  • Behavior: The domains derived for comparisons, IN, NOT IN and STARTS_WITH, and for their AND, OR and NOT combinations, are the same as before, including in the matching-rows property check.

  • Regression: Deriving the domains of an IN list with about 100,000 values combined with a range on the same column takes time proportional to the number of values, not its square.
  • spark-test spark-test commented on code on Oct 29, 2026 22:59 UTC
    Code Review
    sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnarDataSourceSuite.scala:1
    @@ -83,6 +83,34 @@ class ColumnarDataSourceSuite extends QueryTest with SharedSparkSession {
         assert(scan(limited).getMetaData()("PushedLimit") == "LIMIT 2")
       }
     
    +  test("push down the domains of filtered columns") {
    +    val df = spark.read.format(format).option("end", "100").load()
    +      .filter("id >= 40 AND id < 50 AND name <> 'x'")
    +    checkAnswer(df, (40L until 50L).map(id => Row(id, s"name$id")))
    +    // The data source only uses the domain of id, to read the ids in it.
    +    val metadata = scan(df).getMetaData()
    +    assert(metadata("PushedDomains") == "[id: [40L, 50L)]")
    +    val pushed = metadata("PushedFilters")
    +    assert(pushed.contains("id >= 40") && pushed.contains("id < 50"), pushed)
    +    assert(!pushed.contains("name"), pushed)
    +    assert(scan(df).toBatch.planInputPartitions().toSeq ==
    +      Seq(TestRangePartition(40, 45), TestRangePartition(45, 50)))
    +
    +    // A filter that is not a domain is not pushed, and Spark evaluates all the filters after
    +    // reading: here, the data source reads all the ids that are not 3.

    Nit (P3): TestRangePlanner.pushDomains keeps only the hull of the ranges. For (-inf, 3L), (3L, +inf) it plans [0, 5) and [5, 10), so it reads id 3 too, and the unpushed id % 2 = 0 also rejects that row. In the first case the planner reads exactly [40, 50). No row that the planner reads is rejected only by a pushed predicate, so if pushPredicates stopped returning the pushed predicates for post-scan evaluation, both checkAnswer calls would still pass. Only the native tests would catch it, and they are skipped without a C++ compiler and Java 22 or later.

    A filter like id <> 3 AND id < 8 would make this regression-sensitive. Its hull plans [0, 4) and [4, 8), so id 3 is read and only the pushed id <> 3 rejects it. Assert the partitions and the answer, and fix this comment.

    Verification:

  • Regression: With a filter whose domain hull includes a row that only a pushed predicate rejects, the test checks that the row is read and that the result does not contain it, so dropping pushed predicates from post-scan evaluation fails the test.
  • spark-test spark-test commented on code on Oct 29, 2026 22:59 UTC
    Code Review
    sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/ffi/NativeDataSourceSuite.scala:1
    @@ -394,6 +399,88 @@ class NativeDataSourceSuite extends QueryTest with SharedSparkSession {
         assert(!scan(filtered).getMetaData().contains("PushedLimit"))
       }
     
    +  nativeTest("push down the domains of filtered columns") {
    +    val file = new File(Utils.createTempDir(), "domains")
    +    def readIn(session: SparkSession, options: (String, String)*): DataFrame = {
    +      file.delete()
    +      range(session, Seq("end" -> "45", "domains_path" -> file.getPath) ++ options: _*)
    +    }
    +    def read(options: (String, String)*): DataFrame = {
    +      readIn(newSession(defaultPackage), options: _*)
    +    }
    +    // The domains that the library got: for each, the path of the column, whether null and NaN are
    +    // in the domain, and the ranges.
    +    def received(): Seq[String] = Files.readAllLines(file.toPath, UTF_8).asScala.toSeq
    +
    +    // The library reads the blocks of 10 rows whose ids may match, [10, 20) and [20, 30), with all
    +    // their rows, and Spark filters the rows after reading.
    +    val df = read().filter("id > 13 AND id < 27")
    +    checkRows(df, (14L until 27L).map(expectedRow))
    +    assert(received() == Seq("0 - - (13,27)"))

    Nit (P3): Every received() line in this test has - for null and at most one range. No native filter here uses IS NULL, <=>, <>, NOT IN or a same-column OR. So if NativeLibrary.pushDomains lost the null_allowed byte, or NativeArrow.exportDomains exported only the first range, everything here would still pass. Those are the encodings that tell a library which null or between-value rows it must keep, and the test library already prints null and every range.

    Separately, the collated-column assertion added at line 355 checks PushedFilters == "[]". That holds even if Spark pushed a byte-wise domain for the UTF8_LCASE column, because the library marks only the id domain used unless use_domains is all.

    Separate cases such as NOT (id <=> 5) (null plus two ranges), name IS NULL and id NOT IN (5, 20) would cover the encodings. A collated case with domains_path or use_domains = all would cover the exclusion. Combining a null check with NOT IN on the same column in one filter would not work: NOT IN excludes null, so that domain is empty.

    Verification:

  • Regression: Native tests with filters such as NOT (id <=> 5) and id NOT IN (5, 20), each handing the library a domain that allows null or has several ranges, assert the null flag and every range that the library receives, so losing the null flag or any range after the first makes them fail.

  • Regression: The collated-column test records the domains the library receives and fails if one is passed for the collated column.
  • spark-test spark-test commented on code on Oct 29, 2026 22:59 UTC
    Code Review
    sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnDomainsSuite.scala:1
    @@ -0,0 +1,305 @@
    +/*
    + * 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.
    + */
    +package org.apache.spark.sql.execution.datasources.v2.columnar
    +
    +import java.sql.Date
    +
    +import scala.jdk.CollectionConverters._
    +import scala.util.Random
    +
    +import org.apache.spark.sql.{QueryTest, Row}
    +import org.apache.spark.sql.catalyst.CatalystTypeConverters
    +import org.apache.spark.sql.catalyst.expressions.{Literal, PredicateHelper}
    +import org.apache.spark.sql.catalyst.plans.logical.Filter
    +import org.apache.spark.sql.connector.expressions.filter.Predicate
    +import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Strategy
    +import org.apache.spark.sql.functions.expr
    +import org.apache.spark.sql.test.SharedSparkSession
    +import org.apache.spark.sql.types._
    +import org.apache.spark.unsafe.types.UTF8String
    +
    +/** Tests how [[ColumnDomains]] derives the domains of columns from the predicates of a query. */
    +class ColumnDomainsSuite extends QueryTest with SharedSparkSession with PredicateHelper {
    +
    +  private val schema = StructType.fromDDL("id BIGINT, i INT, d DOUBLE, f FLOAT, s STRING, " +
    +    "b BINARY, flag BOOLEAN, dt DATE, ts TIMESTAMP, dec DECIMAL(10, 2), " +
    +    "st STRUCT<x: INT, y: STRING>, arr ARRAY<INT>, c STRING COLLATE UTF8_LCASE")
    +
    +  private def char(codePoint: Int): String = new String(Character.toChars(codePoint))
    +
    +  /**
    +   * The predicates that Data Source V2 pushes for the filter, as in the analyzed plan with the
    +   * constants folded: the optimizer would rewrite some of them, such as NOT (x > 1).
    +   */
    +  private def predicates(filter: String, schema: StructType): Seq[Predicate] = {
    +    val df = spark.createDataFrame(Seq.empty[Row].asJava, schema)
    +    val condition = df.where(filter).queryExecution.analyzed.collectFirst {
    +      case Filter(condition, _) => condition
    +    }.get
    +    splitConjunctivePredicates(condition.transformUp {
    +      case e if e.foldable && !e.isInstanceOf[Literal] => Literal.create(e.eval(), e.dataType)
    +    }).flatMap(DataSourceV2Strategy.translateFilterV2)
    +  }
    +
    +  private def domains(filter: String): Seq[String] = {
    +    ColumnDomains.derive(predicates(filter, schema), schema).domains.map(_.toString)
    +  }
    +
    +  test("comparisons, IN and null checks") {
    +    assert(domains("id > 5") == Seq("id: (5L, +inf)"))
    +    assert(domains("5 < id") == Seq("id: (5L, +inf)"))
    +    assert(domains("id >= 5 AND id < 10") == Seq("id: [5L, 10L)"))
    +    assert(domains("id <= 5") == Seq("id: (-inf, 5L]"))
    +    assert(domains("id = 5") == Seq("id: 5L"))
    +    assert(domains("id <> 5") == Seq("id: (-inf, 5L), (5L, +inf)"))
    +    assert(domains("id <=> 5") == Seq("id: 5L"))
    +    // x <=> v is true for null when false, and so is NOT (x <=> v).

    Nit (P3): For a null x and a non-null v, x <=> v is false, not null, so NOT (x <=> v) is true. That is why NULL is in the expected domain, and it is what ColumnDomains.compare says. Read literally, this line says x <=> v is true for null.

        // x <=> v is false, not null, when x is null, so NOT (x <=> v) is true for null.
    

    Verification:

  • Inspection: The comment above the null-safe equality assertion says that x <=> v is false, not null, for a null x, consistent with the asserted domain and with the corresponding comment in the derivation code.
  • spark-test spark-test commented on Oct 29, 2026 22:59 UTC
    Reviewer

    Review summary

    The derivation rules handle NaN, -0.0, UTF-8 order, collations and three-valued logic carefully, and the property check against Spark's own evaluation backs them up. Six findings follow, plus one question for the author.

  • NOT (x IN ()) gets a domain without null, although it is true for null rows under the default IN semantics. The DataFrame API can build it, and once OptimizeIn and NullPropagation are excluded nothing folds it, so a library that skips all-null data can silently drop matching rows.

  • The header and docs never say that a field of a null struct is null. A library that computes statistics from Arrow child arrays can then skip rows that match a null-allowing struct-field domain.

  • intersectRanges indexes Lists by position. When another range constrains the same column, planning time grows quadratically with the literals of an IN or NOT IN list.

  • Three test issues:

  • - The JVM columnar test cannot detect a lost post-scan filter, and its comment misdescribes what the planner reads.
    - The native tests never observe null_allowed, multiple ranges or the collation exclusion at the library boundary.
    - A ColumnDomainsSuite comment misstates null-safe equality.

    Cross-cutting observations

  • The correctness risks in this review all involve null membership. The domain of NOT (x IN ()) excludes null although null rows match it, the contract never says that a struct field is null under a null struct, and no native test hands a library a domain that allows null. Null is where a library that follows the contract can drop rows without Spark noticing, so null-allowing domains deserve explicit end-to-end coverage.

  • Separation: The three issues have different owners and fixes: a derivation rule in Spark, a sentence in the implementor contract, and native test cases. Each repair closes its own issue, so the shared theme does not change their grouping, scope or severity.

    Findings

    6 total: 0 P0, 1 P1, 2 P2, 3 P3.

    Blocking (P1)

  • NOT (x IN ()) gets a domain without null, although null rows match it — sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnDomains.scala:278 — see inline.
  • Non-blocking (P2)

  • The domain contract never says that a field of a null struct is null — sql/core/src/main/resources/org/apache/spark/sql/datasource/spark_datasource.h:386 — see inline.

  • intersectRanges indexes Lists, so planning time grows quadratically with IN lists — sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnDomains.scala:449 — see inline.
  • Nit (P3)

  • The JVM pushdown test cannot detect a lost post-scan filter, and misdescribes what it reads — sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnarDataSourceSuite.scala:100 — see inline.

  • Native tests never observe null_allowed, multiple ranges or the collation exclusion — sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/ffi/NativeDataSourceSuite.scala:419 — see inline.

  • A test comment misstates null-safe equality — sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnDomainsSuite.scala:70 — see inline.
  • PR description suggestions

  • The title still has the SPARK-XXXXX placeholder. Replace it with this PR's JIRA ID; the body cites SPARK-60101.
  • Decision challenges

    Release target of push_domains and its config: 4.4.0, or master-only 5.0.0?

    Verified in the checkout:

  • The new config declares .version("5.0.0"), which is master's version (5.0.0-SNAPSHOT).

  • branch-4.x is 4.4.0-SNAPSHOT, and its spark_datasource.h has no push_domains.

  • The sibling spark.sql.dataSource.native.paths declares 4.4.0. The header says the interface exists since 4.4.0, with ABI version 1 in every Spark 4 release from 4.4.0.
  • The repository's versioning guidance uses the branch-4.x version for changes that are also merged there. It keeps master's version for breaking changes and for dependency upgrades. This change is additive within ABI version 1, so by that rule it would normally go to branch-4.x as well and document 4.4.0. The description's note that a library built against the 4.4 header has a smaller table suggests instead that 4.4.0 is meant to ship without push_domains.

    Could you confirm the release target? If this lands in 4.4.0, the config should declare 4.4.0, and the 4.4-header note in the description no longer holds. If it is master-only, 5.0.0 is consistent, and it would help to say why in the description, since the guidance does not list this case.

    Generated by Omnigent on Databricks
    <!-- SPARK_OSS_REVIEW_REQUEST 34618627224 -->

    <!-- SPARK_DEV_REVIEW_CODE {"findings":[{"delivery":"inline","fingerprint":"ffe366c95628a3eb2d1c","id":"pass-a:negated-empty-in-excludes-null"},{"delivery":"inline","fingerprint":"13e64bb5eb914bb42645","id":"pass-a:struct-field-null-semantics-unspecified"},{"delivery":"inline","fingerprint":"ab092e3e2325c068594c","id":"pass-b:intersect-ranges-quadratic-list-indexing"},{"delivery":"inline","fingerprint":"b79ee396420c6511ef20","id":"pass-b:columnar-domain-test-cannot-observe-post-scan-filter"},{"delivery":"inline","fingerprint":"9693ec0c91577524ba5c","id":"pass-b:native-domain-tests-miss-null-and-multi-range"},{"delivery":"inline","fingerprint":"26998e39aef3609a2672","id":"pass-b:null-safe-negation-test-comment"}],"head_sha":"fc0ef28e8ee1456880283b715ec835aa7b5e17a5","verdict_sha256":"7255ea9c6472ab0b5de93e19a6002a5bfd818c5eaf80eb6c9f7190c2dbe04c66"} -->

    gengliangwang gengliangwang commented on code on Oct 30, 2026 05:18 UTC
    Code Review
    sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnDomains.scala:1
    @@ -0,0 +1,534 @@
    +/*
    + * 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.
    + */
    +package org.apache.spark.sql.execution.datasources.v2.columnar
    +
    +import scala.collection.mutable.ArrayBuffer
    +
    +import org.apache.spark.SparkException
    +import org.apache.spark.sql.catalyst.expressions.Literal
    +import org.apache.spark.sql.catalyst.types.PhysicalDataType
    +import org.apache.spark.sql.catalyst.util.quoteIfNeeded
    +import org.apache.spark.sql.connector.expressions.{Expression, LiteralValue, NamedReference}
    +import org.apache.spark.sql.connector.expressions.filter.Predicate
    +import org.apache.spark.sql.types._
    +import org.apache.spark.unsafe.types.UTF8String
    +
    +/**
    + * The values that a column can have in the rows that match the filters of a query: null if
    + * `nullAllowed`, NaN if `nanAllowed`, for a float or double column, and the other values in one
    + * of the `ranges`, or any of them without ranges. A data source can skip the data whose statistics
    + * show that it has no value in the domain of a column, but never a row whose values are in their
    + * domains: Spark evaluates the filters after reading anyway.
    + *
    + * @param path the index of the column in the read schema, and then the index of the field in each
    + *             struct, for a field of a struct
    + * @param name the names of the column and of its fields
    + * @param ranges sorted ranges, which neither overlap nor touch, of the values other than null and
    + *               NaN, in the internal representation of Spark. None if the column can have any of
    + *               them, and empty if it can have none.
    + */
    +case class ColumnDomain(
    +    path: Seq[Int],
    +    name: Seq[String],
    +    dataType: DataType,
    +    nullAllowed: Boolean,
    +    nanAllowed: Boolean,
    +    ranges: Option[Seq[ValueRange]]) {
    +
    +  private def ordering: Ordering[Any] = PhysicalDataType.ordering(dataType)
    +
    +  /** Whether the domain has the value, in the internal representation of Spark. */
    +  def contains(value: Any): Boolean = value match {
    +    case null => nullAllowed
    +    case f: Float if f.isNaN => nanAllowed
    +    case d: Double if d.isNaN => nanAllowed
    +    case _ => ranges.forall(_.exists(_.contains(value, ordering)))
    +  }
    +
    +  override def toString: String = {
    +    def literal(value: Any): String = Literal(value, dataType).sql
    +    val values = ranges match {
    +      case None => Seq("ANY")
    +      case Some(ranges) => ranges.map {
    +        case ValueRange(Some(low), true, Some(high), true) if ordering.equiv(low, high) =>
    +          literal(low)
    +        case range =>
    +          (if (range.lowInclusive) "[" else "(") + range.low.map(literal).getOrElse("-inf") +
    +            ", " + range.high.map(literal).getOrElse("+inf") +
    +            (if (range.highInclusive) "]" else ")")
    +      }
    +    }
    +    val special = (if (nullAllowed) Seq("NULL") else Nil) ++ (if (nanAllowed) Seq("NaN") else Nil)
    +    val all = special ++ values
    +    s"${name.map(quoteIfNeeded).mkString(".")}: ${if (all.isEmpty) "NONE" else all.mkString(", ")}"
    +  }
    +}
    +
    +/**
    + * A range of values in the internal representation of Spark: the values above `low`, or equal to
    + * it if `lowInclusive`, and below `high`, or equal to it if `highInclusive`. A bound that is None
    + * is unbounded, and is not inclusive.
    + */
    +case class ValueRange(low: Option[Any], lowInclusive: Boolean, high: Option[Any],
    +    highInclusive: Boolean) {
    +
    +  def contains(value: Any, ordering: Ordering[Any]): Boolean = {
    +    low.forall { l =>
    +      val c = ordering.compare(value, l)
    +      c > 0 || (c == 0 && lowInclusive)
    +    } && high.forall { h =>
    +      val c = ordering.compare(value, h)
    +      c < 0 || (c == 0 && highInclusive)
    +    }
    +  }
    +}
    +
    +/**
    + * The domains that a query passes to a data source, and the predicates that each of them comes
    + * from.
    + *
    + * @param domains the domains, at most one for each column, sorted by path
    + * @param columns the paths of the columns that each predicate constrains
    + */
    +case class ColumnDomains(domains: Seq[ColumnDomain], columns: Seq[Set[Seq[Int]]]) {
    +
    +  /**
    +   * Returns the predicates that constrain only the columns whose domains are used, given whether
    +   * the data source uses each domain.
    +   */
    +  def pushedPredicates(predicates: Array[Predicate], used: Seq[Boolean]): Array[Predicate] = {
    +    val usedPaths = domains.zip(used).collect { case (domain, true) => domain.path }.toSet
    +    predicates.zip(columns).collect {
    +      case (predicate, paths) if paths.nonEmpty && paths.subsetOf(usedPaths) => predicate
    +    }
    +  }
    +}
    +
    +/**
    + * Derives the domains of the columns that the predicates of a query constrain, the ones that Data
    + * Source V2 pushes to a scan, combined with AND. A domain is a superset of the values that a column
    + * has in the rows for which all the predicates are true: Spark derives it from the comparisons of
    + * a column with literals, IN, IS NULL, IS NOT NULL and STARTS_WITH, under AND, OR and NOT, with the
    + * semantics of Spark SQL. Comparisons with null are null, NaN is equal to NaN and greater than any
    + * other value, -0.0 is equal to 0.0, and strings and binary values are compared by their bytes, as
    + * unsigned bytes. A predicate that cannot be expressed this way does not constrain any column. Only
    + * the columns and the fields of structs of the types that a data source can compare get a domain:
    + * not the strings of a non-binary collation, nor arrays, maps and structs.
    + */
    +object ColumnDomains {
    +
    +  // A column that a predicate constrains, with its type.
    +  private case class Column(path: Seq[Int], name: Seq[String], dataType: DataType) {
    +    val ordering: Ordering[Any] = PhysicalDataType.ordering(dataType)
    +    val isFloating: Boolean = dataType == FloatType || dataType == DoubleType
    +  }
    +
    +  // The values that a column can have: see ColumnDomain.
    +  private case class Values(nullAllowed: Boolean, nanAllowed: Boolean,
    +      ranges: Option[Seq[ValueRange]])
    +
    +  private val NoValue = Values(nullAllowed = false, nanAllowed = false, Some(Nil))
    +  private val OnlyNull = Values(nullAllowed = true, nanAllowed = false, Some(Nil))
    +
    +  // The columns that the predicates constrain, with their values: a row can only make the
    +  // predicates true if each of these columns has one of the values. None when no row can.
    +  private type Constraint = Option[Map[Column, Values]]
    +  private val All: Constraint = Some(Map.empty)
    +  private val NoRow: Constraint = None
    +
    +  /** Derives the domains of the predicates for a scan of the schema. */
    +  def derive(predicates: Seq[Predicate], schema: StructType): ColumnDomains = {
    +    val constraints = predicates.map(constraint(_, negated = false, schema))
    +    val columns = constraints.map(_.map(_.keySet.map(_.path)).getOrElse(Set.empty[Seq[Int]]))
    +    val domains = constraints.foldLeft(All)(and) match {
    +      case Some(values) =>
    +        values.toSeq.map { case (column, v) =>
    +          ColumnDomain(column.path, column.name, column.dataType, v.nullAllowed, v.nanAllowed,
    +            v.ranges)
    +        }.sortBy(_.path)(Ordering.Implicits.seqOrdering[Seq, Int])
    +      // A predicate that is always false, which Spark usually removes before it scans the data.
    +      case None => Nil
    +    }
    +    ColumnDomains(domains, columns)
    +  }
    +
    +  // The rows for which the predicate is true, or false if negated: NOT moves to the leaves.
    +  private def constraint(predicate: Predicate, negated: Boolean, schema: StructType): Constraint = {
    +    def child(i: Int): Option[Predicate] = predicate.children().lift(i).collect {
    +      case p: Predicate => p
    +    }
    +    def both(combine: (Constraint, Constraint) => Constraint, negated: Boolean): Constraint = {
    +      (child(0), child(1)) match {
    +        case (Some(left), Some(right)) =>
    +          combine(constraint(left, negated, schema), constraint(right, negated, schema))
    +        case _ => All
    +      }
    +    }
    +    predicate.name() match {
    +      case "AND" => if (negated) both(or, negated = true) else both(and, negated = false)
    +      case "OR" => if (negated) both(and, negated = true) else both(or, negated = false)
    +      case "NOT" => child(0).map(constraint(_, !negated, schema)).getOrElse(All)
    +      case "ALWAYS_TRUE" => if (negated) NoRow else All
    +      case "ALWAYS_FALSE" => if (negated) All else NoRow
    +      case _ => leaf(predicate, negated, schema).getOrElse(All)
    +    }
    +  }
    +
    +  private def leaf(
    +      predicate: Predicate,
    +      negated: Boolean,
    +      schema: StructType): Option[Constraint] = {
    +    val children = predicate.children()
    +    predicate.name() match {
    +      case "IS_NULL" | "IS_NOT_NULL" if children.length == 1 =>
    +        column(children(0), schema).map { col =>
    +          val isNull = (predicate.name() == "IS_NULL") != negated
    +          single(col, if (isNull) OnlyNull else anyValue(col))
    +        }
    +      case op @ ("=" | "<>" | "<=>" | "<" | "<=" | ">" | ">=") if children.length == 2 =>
    +        val operands = (column(children(0), schema), column(children(1), schema)) match {
    +          case (Some(col), _) => literal(children(1), col).map((col, _, op))
    +          case (_, Some(col)) => literal(children(0), col).map((col, _, flip(op)))
    +          case _ => None
    +        }
    +        operands.map { case (col, value, op) => compare(col, value, op, negated) }
    +      case "IN" if children.nonEmpty =>
    +        column(children(0), schema).flatMap { col =>
    +          val values = children.tail.map(literal(_, col))
    +          if (values.forall(_.isDefined)) Some(in(col, values.map(_.get).toSeq, negated)) else None
    +        }
    +      case "STARTS_WITH" if children.length == 2 =>
    +        column(children(0), schema).filter(_.dataType.isInstanceOf[StringType]).flatMap { col =>
    +          literal(children(1), col).map(prefix => startsWith(col, prefix, negated))
    +        }
    +      case _ => None
    +    }
    +  }
    +
    +  private def flip(op: String): String = op match {
    +    case "<" => ">"
    +    case "<=" => ">="
    +    case ">" => "<"
    +    case ">=" => "<="
    +    case other => other
    +  }
    +
    +  private def compare(column: Column, value: Any, op: String, negated: Boolean): Constraint = {
    +    // NOT (x <=> v) is true for null, unless v is null.
    +    val nullAllowed = op == "<=>" && negated && value != null
    +    if (value == null) {
    +      // A comparison with null is null, and so is its negation, but x <=> NULL is x IS NULL.
    +      if (op == "<=>") single(column, if (negated) anyValue(column) else OnlyNull)
    +      else single(column, NoValue)
    +    } else if (isNaN(value)) {
    +      // NaN is equal to NaN and greater than any other value: (NaN, other values).
    +      val (nan, others) = (op, negated) match {
    +        case ("=" | "<=>" | ">=", false) | ("<>" | "<", true) => (true, Some(Nil))
    +        case ("=" | "<=>" | ">=", true) | ("<>" | "<", false) => (false, None)
    +        case ("<=", false) | (">", true) => (true, None)
    +        case ("<=", true) | (">", false) => (false, Some(Nil))
    +        case _ => throw SparkException.internalError(s"Unexpected comparison $op.")
    +      }
    +      single(column, Values(nullAllowed, nan, others))
    +    } else {
    +      val v = normalize(value)
    +      // NaN is greater than v, and not equal to it.
    +      val (nan, ranges) = (op, negated) match {
    +        case ("=" | "<=>", false) | ("<>", true) => (false, Seq(point(v)))
    +        case ("=" | "<=>", true) | ("<>", false) =>
    +          (true, Seq(below(v, inclusive = false), above(v, inclusive = false)))
    +        case ("<", false) | (">=", true) => (false, Seq(below(v, inclusive = false)))
    +        case ("<=", false) | (">", true) => (false, Seq(below(v, inclusive = true)))
    +        case (">", false) | ("<=", true) => (true, Seq(above(v, inclusive = false)))
    +        case (">=", false) | ("<", true) => (true, Seq(above(v, inclusive = true)))
    +        case _ => throw SparkException.internalError(s"Unexpected comparison $op.")
    +      }
    +      single(column, Values(nullAllowed, nan, Some(ranges)))
    +    }
    +  }
    +
    +  private def in(column: Column, values: Seq[Any], negated: Boolean): Constraint = {
    +    val nonNull = values.filter(_ != null)
    +    val hasNaN = nonNull.exists(isNaN)
    +    val points = nonNull.filterNot(isNaN).map(normalize).sorted(column.ordering)
    +      .foldLeft(List.empty[Any]) {
    +        case (last :: rest, v) if column.ordering.equiv(last, v) => last :: rest
    +        case (acc, v) => v :: acc
    +      }.reverse
    +    if (!negated) {
    +      single(column, Values(nullAllowed = false, hasNaN, Some(points.map(point))))
    +    } else if (nonNull.length < values.length) {
    +      // NOT (x IN (..., NULL)) is never true: it is false or null.
    +      single(column, NoValue)
    +    } else if (points.isEmpty) {
    +      single(column, Values(nullAllowed = false, !hasNaN, None))
    +    } else {
    +      // The values between the points.
    +      val bounds = None +: points.map(Some(_)) :+ None
    +      val gaps = bounds.zip(bounds.tail).map { case (low, high) =>
    +        ValueRange(low, lowInclusive = false, high = high, highInclusive = false)
    +      }
    +      single(column, Values(nullAllowed = false, !hasNaN, Some(gaps)))
    +    }
    +  }
    +
    +  private def startsWith(column: Column, prefix: Any, negated: Boolean): Constraint = {
    +    (prefix, negated) match {
    +      case (null, _) => single(column, NoValue)
    +      // The strings that do not start with the prefix are not a range. A value whose bytes are not
    +      // valid UTF-8 could even be in the range of the strings that do.
    +      case (_, true) => single(column, anyValue(column))
    +      case (prefix: UTF8String, false) if prefix.numBytes() == 0 => single(column, anyValue(column))
    +      case (prefix: UTF8String, false) =>
    +        val range = ValueRange(Some(prefix), lowInclusive = true, high = nextPrefix(prefix),
    +          highInclusive = false)
    +        single(column, Values(nullAllowed = false, nanAllowed = false, Some(Seq(range))))
    +      case _ => All
    +    }
    +  }
    +
    +  /**
    +   * Returns the smallest string that is greater than all the strings that start with the prefix,
    +   * in the order of their UTF-8 bytes, which is the order of their code points, or None if there
    +   * is none: the prefix with its last code point incremented, after dropping the trailing
    +   * U+10FFFF, the largest code point.
    +   */
    +  private[columnar] def nextPrefix(prefix: UTF8String): Option[UTF8String] = {
    +    val codePoints = prefix.toString.codePoints().toArray.toBuffer
    +    while (codePoints.nonEmpty && codePoints.last == Character.MAX_CODE_POINT) {
    +      codePoints.remove(codePoints.length - 1)
    +    }
    +    if (codePoints.isEmpty) {
    +      None
    +    } else {
    +      val last = codePoints.last + 1
    +      // Skips the surrogates, which are not code points of characters.
    +      codePoints(codePoints.length - 1) =
    +        if (last >= Character.MIN_SURROGATE && last <= Character.MAX_SURROGATE) {
    +          Character.MAX_SURROGATE + 1
    +        } else {
    +          last
    +        }
    +      Some(UTF8String.fromString(new String(codePoints.toArray, 0, codePoints.length)))
    +    }
    +  }
    +
    +  private def single(column: Column, values: Values): Constraint = {
    +    // Only floating-point columns have NaN.
    +    val normalized = values.copy(nanAllowed = values.nanAllowed && column.isFloating)
    +    if (isAll(column, normalized)) All else Some(Map(column -> normalized))
    +  }
    +
    +  private def point(v: Any): ValueRange =
    +    ValueRange(Some(v), lowInclusive = true, high = Some(v), highInclusive = true)
    +
    +  private def below(v: Any, inclusive: Boolean): ValueRange =
    +    ValueRange(None, lowInclusive = false, high = Some(v), highInclusive = inclusive)
    +
    +  private def above(v: Any, inclusive: Boolean): ValueRange =
    +    ValueRange(Some(v), lowInclusive = inclusive, high = None, highInclusive = false)
    +
    +  private def anyValue(column: Column): Values = {
    +    Values(nullAllowed = false, nanAllowed = column.isFloating, None)
    +  }
    +
    +  private def isAll(column: Column, values: Values): Boolean = {
    +    values.nullAllowed && values.ranges.isEmpty && (values.nanAllowed || !column.isFloating)
    +  }
    +
    +  private def isEmpty(values: Values): Boolean = {
    +    !values.nullAllowed && !values.nanAllowed && values.ranges.exists(_.isEmpty)
    +  }
    +
    +  // Whether no row can make the predicates true.
    +  private def matchesNoRow(constraint: Constraint): Boolean = {
    +    constraint.forall(_.values.exists(isEmpty))
    +  }
    +
    +  private def and(left: Constraint, right: Constraint): Constraint = (left, right) match {
    +    case (Some(l), Some(r)) =>
    +      Some((l.keySet ++ r.keySet).map { column =>
    +        column -> ((l.get(column), r.get(column)) match {
    +          case (Some(a), Some(b)) => intersect(column, a, b)
    +          case (a, b) => a.orElse(b).get
    +        })
    +      }.toMap)
    +    case _ => NoRow
    +  }
    +
    +  // A column that only one side constrains can have any value in the rows of the other side, so
    +  // only the columns that both sides constrain are constrained.
    +  private def or(left: Constraint, right: Constraint): Constraint = {
    +    if (matchesNoRow(left)) {
    +      right
    +    } else if (matchesNoRow(right)) {
    +      left
    +    } else {
    +      val (l, r) = (left.get, right.get)
    +      Some(l.keySet.intersect(r.keySet).map(column => column -> union(column, l(column), r(column)))
    +        .filterNot { case (column, values) => isAll(column, values) }.toMap)
    +    }
    +  }
    +
    +  private def intersect(column: Column, a: Values, b: Values): Values = Values(
    +    a.nullAllowed && b.nullAllowed,
    +    a.nanAllowed && b.nanAllowed,
    +    (a.ranges, b.ranges) match {
    +      case (Some(x), Some(y)) => Some(intersectRanges(x, y, column.ordering))
    +      case (x, y) => x.orElse(y)
    +    })
    +
    +  private def union(column: Column, a: Values, b: Values): Values = Values(
    +    a.nullAllowed || b.nullAllowed,
    +    a.nanAllowed || b.nanAllowed,
    +    (a.ranges, b.ranges) match {
    +      case (Some(x), Some(y)) =>
    +        unionRanges(x, y, column.ordering) match {
    +          // All the values.
    +          case Seq(ValueRange(None, _, None, _)) => None
    +          case ranges => Some(ranges)
    +        }
    +      case _ => None
    +    })
    +
    +  // A negative value when `a` starts before `b`.
    +  private def compareLows(a: ValueRange, b: ValueRange, ordering: Ordering[Any]): Int = {
    +    (a.low, b.low) match {
    +      case (None, None) => 0
    +      case (None, _) => -1
    +      case (_, None) => 1
    +      case (Some(x), Some(y)) =>
    +        val c = ordering.compare(x, y)
    +        if (c != 0 || a.lowInclusive == b.lowInclusive) c else if (a.lowInclusive) -1 else 1
    +    }
    +  }
    +
    +  // A negative value when `a` ends before `b`.
    +  private def compareHighs(a: ValueRange, b: ValueRange, ordering: Ordering[Any]): Int = {
    +    (a.high, b.high) match {
    +      case (None, None) => 0
    +      case (None, _) => 1
    +      case (_, None) => -1
    +      case (Some(x), Some(y)) =>
    +        val c = ordering.compare(x, y)
    +        if (c != 0 || a.highInclusive == b.highInclusive) c else if (a.highInclusive) 1 else -1
    +    }
    +  }
    +
    +  private def isEmptyRange(range: ValueRange, ordering: Ordering[Any]): Boolean = {
    +    (range.low, range.high) match {
    +      case (Some(low), Some(high)) =>
    +        val c = ordering.compare(low, high)
    +        c > 0 || (c == 0 && !(range.lowInclusive && range.highInclusive))
    +      case _ => false
    +    }
    +  }
    +
    +  // Intersects two lists of sorted ranges that neither overlap nor touch, by sweeping them.
    +  private def intersectRanges(
    +      a: Seq[ValueRange],
    +      b: Seq[ValueRange],
    +      ordering: Ordering[Any]): Seq[ValueRange] = {
    +    val result = ArrayBuffer.empty[ValueRange]
    +    var i = 0
    +    var j = 0
    +    while (i < a.length && j < b.length) {
    +      val (x, y) = (a(i), b(j))

    [P2] Keep range intersection linear for IN-derived lists

    For filters combining a large IN or NOT IN list with a range predicate on the same column, in() produces ranges as a List. Both length and indexed access traverse that list on every iteration here, making the intended linear sweep quadratic and potentially stalling driver-side query planning. Use iterators or convert the inputs to indexed collections before the loop.

    HyukjinKwon HyukjinKwon commented on code on Oct 30, 2026 12:03 UTC
    Code Review
    sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnDomains.scala:1
    @@ -0,0 +1,534 @@
    +/*
    + * 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.
    + */
    +package org.apache.spark.sql.execution.datasources.v2.columnar
    +
    +import scala.collection.mutable.ArrayBuffer
    +
    +import org.apache.spark.SparkException
    +import org.apache.spark.sql.catalyst.expressions.Literal
    +import org.apache.spark.sql.catalyst.types.PhysicalDataType
    +import org.apache.spark.sql.catalyst.util.quoteIfNeeded
    +import org.apache.spark.sql.connector.expressions.{Expression, LiteralValue, NamedReference}
    +import org.apache.spark.sql.connector.expressions.filter.Predicate
    +import org.apache.spark.sql.types._
    +import org.apache.spark.unsafe.types.UTF8String
    +
    +/**
    + * The values that a column can have in the rows that match the filters of a query: null if
    + * `nullAllowed`, NaN if `nanAllowed`, for a float or double column, and the other values in one
    + * of the `ranges`, or any of them without ranges. A data source can skip the data whose statistics
    + * show that it has no value in the domain of a column, but never a row whose values are in their
    + * domains: Spark evaluates the filters after reading anyway.
    + *
    + * @param path the index of the column in the read schema, and then the index of the field in each
    + *             struct, for a field of a struct
    + * @param name the names of the column and of its fields
    + * @param ranges sorted ranges, which neither overlap nor touch, of the values other than null and
    + *               NaN, in the internal representation of Spark. None if the column can have any of
    + *               them, and empty if it can have none.
    + */
    +case class ColumnDomain(
    +    path: Seq[Int],
    +    name: Seq[String],
    +    dataType: DataType,
    +    nullAllowed: Boolean,
    +    nanAllowed: Boolean,
    +    ranges: Option[Seq[ValueRange]]) {
    +
    +  private def ordering: Ordering[Any] = PhysicalDataType.ordering(dataType)
    +
    +  /** Whether the domain has the value, in the internal representation of Spark. */
    +  def contains(value: Any): Boolean = value match {
    +    case null => nullAllowed
    +    case f: Float if f.isNaN => nanAllowed
    +    case d: Double if d.isNaN => nanAllowed
    +    case _ => ranges.forall(_.exists(_.contains(value, ordering)))
    +  }
    +
    +  override def toString: String = {
    +    def literal(value: Any): String = Literal(value, dataType).sql
    +    val values = ranges match {
    +      case None => Seq("ANY")
    +      case Some(ranges) => ranges.map {
    +        case ValueRange(Some(low), true, Some(high), true) if ordering.equiv(low, high) =>
    +          literal(low)
    +        case range =>
    +          (if (range.lowInclusive) "[" else "(") + range.low.map(literal).getOrElse("-inf") +
    +            ", " + range.high.map(literal).getOrElse("+inf") +
    +            (if (range.highInclusive) "]" else ")")
    +      }
    +    }
    +    val special = (if (nullAllowed) Seq("NULL") else Nil) ++ (if (nanAllowed) Seq("NaN") else Nil)
    +    val all = special ++ values
    +    s"${name.map(quoteIfNeeded).mkString(".")}: ${if (all.isEmpty) "NONE" else all.mkString(", ")}"
    +  }
    +}
    +
    +/**
    + * A range of values in the internal representation of Spark: the values above `low`, or equal to
    + * it if `lowInclusive`, and below `high`, or equal to it if `highInclusive`. A bound that is None
    + * is unbounded, and is not inclusive.
    + */
    +case class ValueRange(low: Option[Any], lowInclusive: Boolean, high: Option[Any],
    +    highInclusive: Boolean) {
    +
    +  def contains(value: Any, ordering: Ordering[Any]): Boolean = {
    +    low.forall { l =>
    +      val c = ordering.compare(value, l)
    +      c > 0 || (c == 0 && lowInclusive)
    +    } && high.forall { h =>
    +      val c = ordering.compare(value, h)
    +      c < 0 || (c == 0 && highInclusive)
    +    }
    +  }
    +}
    +
    +/**
    + * The domains that a query passes to a data source, and the predicates that each of them comes
    + * from.
    + *
    + * @param domains the domains, at most one for each column, sorted by path
    + * @param columns the paths of the columns that each predicate constrains
    + */
    +case class ColumnDomains(domains: Seq[ColumnDomain], columns: Seq[Set[Seq[Int]]]) {
    +
    +  /**
    +   * Returns the predicates that constrain only the columns whose domains are used, given whether
    +   * the data source uses each domain.
    +   */
    +  def pushedPredicates(predicates: Array[Predicate], used: Seq[Boolean]): Array[Predicate] = {
    +    val usedPaths = domains.zip(used).collect { case (domain, true) => domain.path }.toSet
    +    predicates.zip(columns).collect {
    +      case (predicate, paths) if paths.nonEmpty && paths.subsetOf(usedPaths) => predicate
    +    }
    +  }
    +}
    +
    +/**
    + * Derives the domains of the columns that the predicates of a query constrain, the ones that Data
    + * Source V2 pushes to a scan, combined with AND. A domain is a superset of the values that a column
    + * has in the rows for which all the predicates are true: Spark derives it from the comparisons of
    + * a column with literals, IN, IS NULL, IS NOT NULL and STARTS_WITH, under AND, OR and NOT, with the
    + * semantics of Spark SQL. Comparisons with null are null, NaN is equal to NaN and greater than any
    + * other value, -0.0 is equal to 0.0, and strings and binary values are compared by their bytes, as
    + * unsigned bytes. A predicate that cannot be expressed this way does not constrain any column. Only
    + * the columns and the fields of structs of the types that a data source can compare get a domain:
    + * not the strings of a non-binary collation, nor arrays, maps and structs.
    + */
    +object ColumnDomains {
    +
    +  // A column that a predicate constrains, with its type.
    +  private case class Column(path: Seq[Int], name: Seq[String], dataType: DataType) {
    +    val ordering: Ordering[Any] = PhysicalDataType.ordering(dataType)
    +    val isFloating: Boolean = dataType == FloatType || dataType == DoubleType
    +  }
    +
    +  // The values that a column can have: see ColumnDomain.
    +  private case class Values(nullAllowed: Boolean, nanAllowed: Boolean,
    +      ranges: Option[Seq[ValueRange]])
    +
    +  private val NoValue = Values(nullAllowed = false, nanAllowed = false, Some(Nil))
    +  private val OnlyNull = Values(nullAllowed = true, nanAllowed = false, Some(Nil))
    +
    +  // The columns that the predicates constrain, with their values: a row can only make the
    +  // predicates true if each of these columns has one of the values. None when no row can.
    +  private type Constraint = Option[Map[Column, Values]]
    +  private val All: Constraint = Some(Map.empty)
    +  private val NoRow: Constraint = None
    +
    +  /** Derives the domains of the predicates for a scan of the schema. */
    +  def derive(predicates: Seq[Predicate], schema: StructType): ColumnDomains = {
    +    val constraints = predicates.map(constraint(_, negated = false, schema))
    +    val columns = constraints.map(_.map(_.keySet.map(_.path)).getOrElse(Set.empty[Seq[Int]]))
    +    val domains = constraints.foldLeft(All)(and) match {
    +      case Some(values) =>
    +        values.toSeq.map { case (column, v) =>
    +          ColumnDomain(column.path, column.name, column.dataType, v.nullAllowed, v.nanAllowed,
    +            v.ranges)
    +        }.sortBy(_.path)(Ordering.Implicits.seqOrdering[Seq, Int])
    +      // A predicate that is always false, which Spark usually removes before it scans the data.
    +      case None => Nil
    +    }
    +    ColumnDomains(domains, columns)
    +  }
    +
    +  // The rows for which the predicate is true, or false if negated: NOT moves to the leaves.
    +  private def constraint(predicate: Predicate, negated: Boolean, schema: StructType): Constraint = {
    +    def child(i: Int): Option[Predicate] = predicate.children().lift(i).collect {
    +      case p: Predicate => p
    +    }
    +    def both(combine: (Constraint, Constraint) => Constraint, negated: Boolean): Constraint = {
    +      (child(0), child(1)) match {
    +        case (Some(left), Some(right)) =>
    +          combine(constraint(left, negated, schema), constraint(right, negated, schema))
    +        case _ => All
    +      }
    +    }
    +    predicate.name() match {
    +      case "AND" => if (negated) both(or, negated = true) else both(and, negated = false)
    +      case "OR" => if (negated) both(and, negated = true) else both(or, negated = false)
    +      case "NOT" => child(0).map(constraint(_, !negated, schema)).getOrElse(All)
    +      case "ALWAYS_TRUE" => if (negated) NoRow else All
    +      case "ALWAYS_FALSE" => if (negated) All else NoRow
    +      case _ => leaf(predicate, negated, schema).getOrElse(All)
    +    }
    +  }
    +
    +  private def leaf(
    +      predicate: Predicate,
    +      negated: Boolean,
    +      schema: StructType): Option[Constraint] = {
    +    val children = predicate.children()
    +    predicate.name() match {
    +      case "IS_NULL" | "IS_NOT_NULL" if children.length == 1 =>
    +        column(children(0), schema).map { col =>
    +          val isNull = (predicate.name() == "IS_NULL") != negated
    +          single(col, if (isNull) OnlyNull else anyValue(col))
    +        }
    +      case op @ ("=" | "<>" | "<=>" | "<" | "<=" | ">" | ">=") if children.length == 2 =>
    +        val operands = (column(children(0), schema), column(children(1), schema)) match {
    +          case (Some(col), _) => literal(children(1), col).map((col, _, op))
    +          case (_, Some(col)) => literal(children(0), col).map((col, _, flip(op)))
    +          case _ => None
    +        }
    +        operands.map { case (col, value, op) => compare(col, value, op, negated) }
    +      case "IN" if children.nonEmpty =>
    +        column(children(0), schema).flatMap { col =>
    +          val values = children.tail.map(literal(_, col))
    +          if (values.forall(_.isDefined)) Some(in(col, values.map(_.get).toSeq, negated)) else None
    +        }
    +      case "STARTS_WITH" if children.length == 2 =>
    +        column(children(0), schema).filter(_.dataType.isInstanceOf[StringType]).flatMap { col =>
    +          literal(children(1), col).map(prefix => startsWith(col, prefix, negated))
    +        }
    +      case _ => None
    +    }
    +  }
    +
    +  private def flip(op: String): String = op match {
    +    case "<" => ">"
    +    case "<=" => ">="
    +    case ">" => "<"
    +    case ">=" => "<="
    +    case other => other
    +  }
    +
    +  private def compare(column: Column, value: Any, op: String, negated: Boolean): Constraint = {
    +    // NOT (x <=> v) is true for null, unless v is null.
    +    val nullAllowed = op == "<=>" && negated && value != null
    +    if (value == null) {
    +      // A comparison with null is null, and so is its negation, but x <=> NULL is x IS NULL.
    +      if (op == "<=>") single(column, if (negated) anyValue(column) else OnlyNull)
    +      else single(column, NoValue)
    +    } else if (isNaN(value)) {
    +      // NaN is equal to NaN and greater than any other value: (NaN, other values).
    +      val (nan, others) = (op, negated) match {
    +        case ("=" | "<=>" | ">=", false) | ("<>" | "<", true) => (true, Some(Nil))
    +        case ("=" | "<=>" | ">=", true) | ("<>" | "<", false) => (false, None)
    +        case ("<=", false) | (">", true) => (true, None)
    +        case ("<=", true) | (">", false) => (false, Some(Nil))
    +        case _ => throw SparkException.internalError(s"Unexpected comparison $op.")
    +      }
    +      single(column, Values(nullAllowed, nan, others))
    +    } else {
    +      val v = normalize(value)
    +      // NaN is greater than v, and not equal to it.
    +      val (nan, ranges) = (op, negated) match {
    +        case ("=" | "<=>", false) | ("<>", true) => (false, Seq(point(v)))
    +        case ("=" | "<=>", true) | ("<>", false) =>
    +          (true, Seq(below(v, inclusive = false), above(v, inclusive = false)))
    +        case ("<", false) | (">=", true) => (false, Seq(below(v, inclusive = false)))
    +        case ("<=", false) | (">", true) => (false, Seq(below(v, inclusive = true)))
    +        case (">", false) | ("<=", true) => (true, Seq(above(v, inclusive = false)))
    +        case (">=", false) | ("<", true) => (true, Seq(above(v, inclusive = true)))
    +        case _ => throw SparkException.internalError(s"Unexpected comparison $op.")
    +      }
    +      single(column, Values(nullAllowed, nan, Some(ranges)))
    +    }
    +  }
    +
    +  private def in(column: Column, values: Seq[Any], negated: Boolean): Constraint = {
    +    val nonNull = values.filter(_ != null)
    +    val hasNaN = nonNull.exists(isNaN)
    +    val points = nonNull.filterNot(isNaN).map(normalize).sorted(column.ordering)
    +      .foldLeft(List.empty[Any]) {
    +        case (last :: rest, v) if column.ordering.equiv(last, v) => last :: rest
    +        case (acc, v) => v :: acc
    +      }.reverse
    +    if (!negated) {
    +      single(column, Values(nullAllowed = false, hasNaN, Some(points.map(point))))
    +    } else if (nonNull.length < values.length) {
    +      // NOT (x IN (..., NULL)) is never true: it is false or null.
    +      single(column, NoValue)
    +    } else if (points.isEmpty) {
    +      single(column, Values(nullAllowed = false, !hasNaN, None))

    Done in daba613: in now handles an empty list first. x IN () gets an empty domain, since it is never true, and NOT (x IN ()) constrains no column, which holds with and without spark.sql.legacy.nullInEmptyListBehavior. ColumnDomainsSuite checks both with the DataFrame API (isin() and isInCollection(Nil)), and the property check now also evaluates filters with empty IN lists, under the default and the legacy behavior.

    HyukjinKwon HyukjinKwon commented on code on Oct 30, 2026 12:03 UTC
    Code Review
    sql/core/src/main/resources/org/apache/spark/sql/datasource/spark_datasource.h:1
    @@ -350,6 +350,63 @@ typedef struct SparkDsWriteInfo {
       const char* query_id;
     } SparkDsWriteInfo;
     
    +/*
    + * The domain of a column, which push_domains gets: 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 is true;
    + * - NaN, if nan_allowed is true, for a float or double column;
    + * - another value, if ranges is NULL, or if it is in one of the ranges.
    + * A reader can skip the data whose statistics show that it has no value in the domain of a column,
    + * such as a file or a row group whose values are all below the ranges. But it must never skip a
    + * row whose values are all in their domains, which Spark cannot detect. Spark evaluates the
    + * filters again after reading, so the rows that a reader returns do not need to match them.
    + *
    + * Values are compared with 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 the comparisons of IEEE 754,
    + *   as the operators of C, C++ and Rust do, not with a total order, such as f64::total_cmp in Rust,
    + *   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, which order the characters outside the Basic Multilingual Plane
    + *   after all the others, unlike comparisons of UTF-16 strings;
    + * - binary values as unsigned bytes, in lexicographic order: X'80' is greater than X'7F', and a
    + *   value is greater than its prefixes;
    + * - booleans with false before true.
    + */
    +typedef struct SparkDsDomain {
    +  /* The size of this struct in the header that Spark was built with, as in SparkDsHost. */
    +  int64_t size;
    +  /*
    +   * The column, by the path_length indices of its fields: the index of the column in the schema to
    +   * read, the one that create_reader got, and then the index of the field in each struct, for a
    +   * field of a struct. {2, 0} is the first field of the third column.
    +   */
    +  const int32_t* path;
    +  int64_t path_length;
    +  /* Whether null is in the domain. */

    Done in daba613, with the alternative: Spark no longer passes a domain that has null for a field of a struct. It is the safer option, since a library that computes its statistics from the Arrow child arrays, which is the natural way with Arrow, would otherwise skip the rows of a null struct, and Spark cannot detect that. A domain without null is safe either way: the rows of a null struct never match it, and the values that a child array holds under a null struct only make a library read more. Only filters such as st.y IS NULL or NOT (st.y <=> v) lose their domain.

    The header (null_allowed and push_domains) and the Filter Pushdown section of the guide now say that a field is null where the struct, or a struct that contains it, is null, and that Spark only passes domains without null for the fields of structs. The property check now has a struct column with null structs and null fields.

    HyukjinKwon HyukjinKwon commented on code on Oct 30, 2026 12:03 UTC
    Code Review
    sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnDomains.scala:1
    @@ -0,0 +1,534 @@
    +/*
    + * 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.
    + */
    +package org.apache.spark.sql.execution.datasources.v2.columnar
    +
    +import scala.collection.mutable.ArrayBuffer
    +
    +import org.apache.spark.SparkException
    +import org.apache.spark.sql.catalyst.expressions.Literal
    +import org.apache.spark.sql.catalyst.types.PhysicalDataType
    +import org.apache.spark.sql.catalyst.util.quoteIfNeeded
    +import org.apache.spark.sql.connector.expressions.{Expression, LiteralValue, NamedReference}
    +import org.apache.spark.sql.connector.expressions.filter.Predicate
    +import org.apache.spark.sql.types._
    +import org.apache.spark.unsafe.types.UTF8String
    +
    +/**
    + * The values that a column can have in the rows that match the filters of a query: null if
    + * `nullAllowed`, NaN if `nanAllowed`, for a float or double column, and the other values in one
    + * of the `ranges`, or any of them without ranges. A data source can skip the data whose statistics
    + * show that it has no value in the domain of a column, but never a row whose values are in their
    + * domains: Spark evaluates the filters after reading anyway.
    + *
    + * @param path the index of the column in the read schema, and then the index of the field in each
    + *             struct, for a field of a struct
    + * @param name the names of the column and of its fields
    + * @param ranges sorted ranges, which neither overlap nor touch, of the values other than null and
    + *               NaN, in the internal representation of Spark. None if the column can have any of
    + *               them, and empty if it can have none.
    + */
    +case class ColumnDomain(
    +    path: Seq[Int],
    +    name: Seq[String],
    +    dataType: DataType,
    +    nullAllowed: Boolean,
    +    nanAllowed: Boolean,
    +    ranges: Option[Seq[ValueRange]]) {
    +
    +  private def ordering: Ordering[Any] = PhysicalDataType.ordering(dataType)
    +
    +  /** Whether the domain has the value, in the internal representation of Spark. */
    +  def contains(value: Any): Boolean = value match {
    +    case null => nullAllowed
    +    case f: Float if f.isNaN => nanAllowed
    +    case d: Double if d.isNaN => nanAllowed
    +    case _ => ranges.forall(_.exists(_.contains(value, ordering)))
    +  }
    +
    +  override def toString: String = {
    +    def literal(value: Any): String = Literal(value, dataType).sql
    +    val values = ranges match {
    +      case None => Seq("ANY")
    +      case Some(ranges) => ranges.map {
    +        case ValueRange(Some(low), true, Some(high), true) if ordering.equiv(low, high) =>
    +          literal(low)
    +        case range =>
    +          (if (range.lowInclusive) "[" else "(") + range.low.map(literal).getOrElse("-inf") +
    +            ", " + range.high.map(literal).getOrElse("+inf") +
    +            (if (range.highInclusive) "]" else ")")
    +      }
    +    }
    +    val special = (if (nullAllowed) Seq("NULL") else Nil) ++ (if (nanAllowed) Seq("NaN") else Nil)
    +    val all = special ++ values
    +    s"${name.map(quoteIfNeeded).mkString(".")}: ${if (all.isEmpty) "NONE" else all.mkString(", ")}"
    +  }
    +}
    +
    +/**
    + * A range of values in the internal representation of Spark: the values above `low`, or equal to
    + * it if `lowInclusive`, and below `high`, or equal to it if `highInclusive`. A bound that is None
    + * is unbounded, and is not inclusive.
    + */
    +case class ValueRange(low: Option[Any], lowInclusive: Boolean, high: Option[Any],
    +    highInclusive: Boolean) {
    +
    +  def contains(value: Any, ordering: Ordering[Any]): Boolean = {
    +    low.forall { l =>
    +      val c = ordering.compare(value, l)
    +      c > 0 || (c == 0 && lowInclusive)
    +    } && high.forall { h =>
    +      val c = ordering.compare(value, h)
    +      c < 0 || (c == 0 && highInclusive)
    +    }
    +  }
    +}
    +
    +/**
    + * The domains that a query passes to a data source, and the predicates that each of them comes
    + * from.
    + *
    + * @param domains the domains, at most one for each column, sorted by path
    + * @param columns the paths of the columns that each predicate constrains
    + */
    +case class ColumnDomains(domains: Seq[ColumnDomain], columns: Seq[Set[Seq[Int]]]) {
    +
    +  /**
    +   * Returns the predicates that constrain only the columns whose domains are used, given whether
    +   * the data source uses each domain.
    +   */
    +  def pushedPredicates(predicates: Array[Predicate], used: Seq[Boolean]): Array[Predicate] = {
    +    val usedPaths = domains.zip(used).collect { case (domain, true) => domain.path }.toSet
    +    predicates.zip(columns).collect {
    +      case (predicate, paths) if paths.nonEmpty && paths.subsetOf(usedPaths) => predicate
    +    }
    +  }
    +}
    +
    +/**
    + * Derives the domains of the columns that the predicates of a query constrain, the ones that Data
    + * Source V2 pushes to a scan, combined with AND. A domain is a superset of the values that a column
    + * has in the rows for which all the predicates are true: Spark derives it from the comparisons of
    + * a column with literals, IN, IS NULL, IS NOT NULL and STARTS_WITH, under AND, OR and NOT, with the
    + * semantics of Spark SQL. Comparisons with null are null, NaN is equal to NaN and greater than any
    + * other value, -0.0 is equal to 0.0, and strings and binary values are compared by their bytes, as
    + * unsigned bytes. A predicate that cannot be expressed this way does not constrain any column. Only
    + * the columns and the fields of structs of the types that a data source can compare get a domain:
    + * not the strings of a non-binary collation, nor arrays, maps and structs.
    + */
    +object ColumnDomains {
    +
    +  // A column that a predicate constrains, with its type.
    +  private case class Column(path: Seq[Int], name: Seq[String], dataType: DataType) {
    +    val ordering: Ordering[Any] = PhysicalDataType.ordering(dataType)
    +    val isFloating: Boolean = dataType == FloatType || dataType == DoubleType
    +  }
    +
    +  // The values that a column can have: see ColumnDomain.
    +  private case class Values(nullAllowed: Boolean, nanAllowed: Boolean,
    +      ranges: Option[Seq[ValueRange]])
    +
    +  private val NoValue = Values(nullAllowed = false, nanAllowed = false, Some(Nil))
    +  private val OnlyNull = Values(nullAllowed = true, nanAllowed = false, Some(Nil))
    +
    +  // The columns that the predicates constrain, with their values: a row can only make the
    +  // predicates true if each of these columns has one of the values. None when no row can.
    +  private type Constraint = Option[Map[Column, Values]]
    +  private val All: Constraint = Some(Map.empty)
    +  private val NoRow: Constraint = None
    +
    +  /** Derives the domains of the predicates for a scan of the schema. */
    +  def derive(predicates: Seq[Predicate], schema: StructType): ColumnDomains = {
    +    val constraints = predicates.map(constraint(_, negated = false, schema))
    +    val columns = constraints.map(_.map(_.keySet.map(_.path)).getOrElse(Set.empty[Seq[Int]]))
    +    val domains = constraints.foldLeft(All)(and) match {
    +      case Some(values) =>
    +        values.toSeq.map { case (column, v) =>
    +          ColumnDomain(column.path, column.name, column.dataType, v.nullAllowed, v.nanAllowed,
    +            v.ranges)
    +        }.sortBy(_.path)(Ordering.Implicits.seqOrdering[Seq, Int])
    +      // A predicate that is always false, which Spark usually removes before it scans the data.
    +      case None => Nil
    +    }
    +    ColumnDomains(domains, columns)
    +  }
    +
    +  // The rows for which the predicate is true, or false if negated: NOT moves to the leaves.
    +  private def constraint(predicate: Predicate, negated: Boolean, schema: StructType): Constraint = {
    +    def child(i: Int): Option[Predicate] = predicate.children().lift(i).collect {
    +      case p: Predicate => p
    +    }
    +    def both(combine: (Constraint, Constraint) => Constraint, negated: Boolean): Constraint = {
    +      (child(0), child(1)) match {
    +        case (Some(left), Some(right)) =>
    +          combine(constraint(left, negated, schema), constraint(right, negated, schema))
    +        case _ => All
    +      }
    +    }
    +    predicate.name() match {
    +      case "AND" => if (negated) both(or, negated = true) else both(and, negated = false)
    +      case "OR" => if (negated) both(and, negated = true) else both(or, negated = false)
    +      case "NOT" => child(0).map(constraint(_, !negated, schema)).getOrElse(All)
    +      case "ALWAYS_TRUE" => if (negated) NoRow else All
    +      case "ALWAYS_FALSE" => if (negated) All else NoRow
    +      case _ => leaf(predicate, negated, schema).getOrElse(All)
    +    }
    +  }
    +
    +  private def leaf(
    +      predicate: Predicate,
    +      negated: Boolean,
    +      schema: StructType): Option[Constraint] = {
    +    val children = predicate.children()
    +    predicate.name() match {
    +      case "IS_NULL" | "IS_NOT_NULL" if children.length == 1 =>
    +        column(children(0), schema).map { col =>
    +          val isNull = (predicate.name() == "IS_NULL") != negated
    +          single(col, if (isNull) OnlyNull else anyValue(col))
    +        }
    +      case op @ ("=" | "<>" | "<=>" | "<" | "<=" | ">" | ">=") if children.length == 2 =>
    +        val operands = (column(children(0), schema), column(children(1), schema)) match {
    +          case (Some(col), _) => literal(children(1), col).map((col, _, op))
    +          case (_, Some(col)) => literal(children(0), col).map((col, _, flip(op)))
    +          case _ => None
    +        }
    +        operands.map { case (col, value, op) => compare(col, value, op, negated) }
    +      case "IN" if children.nonEmpty =>
    +        column(children(0), schema).flatMap { col =>
    +          val values = children.tail.map(literal(_, col))
    +          if (values.forall(_.isDefined)) Some(in(col, values.map(_.get).toSeq, negated)) else None
    +        }
    +      case "STARTS_WITH" if children.length == 2 =>
    +        column(children(0), schema).filter(_.dataType.isInstanceOf[StringType]).flatMap { col =>
    +          literal(children(1), col).map(prefix => startsWith(col, prefix, negated))
    +        }
    +      case _ => None
    +    }
    +  }
    +
    +  private def flip(op: String): String = op match {
    +    case "<" => ">"
    +    case "<=" => ">="
    +    case ">" => "<"
    +    case ">=" => "<="
    +    case other => other
    +  }
    +
    +  private def compare(column: Column, value: Any, op: String, negated: Boolean): Constraint = {
    +    // NOT (x <=> v) is true for null, unless v is null.
    +    val nullAllowed = op == "<=>" && negated && value != null
    +    if (value == null) {
    +      // A comparison with null is null, and so is its negation, but x <=> NULL is x IS NULL.
    +      if (op == "<=>") single(column, if (negated) anyValue(column) else OnlyNull)
    +      else single(column, NoValue)
    +    } else if (isNaN(value)) {
    +      // NaN is equal to NaN and greater than any other value: (NaN, other values).
    +      val (nan, others) = (op, negated) match {
    +        case ("=" | "<=>" | ">=", false) | ("<>" | "<", true) => (true, Some(Nil))
    +        case ("=" | "<=>" | ">=", true) | ("<>" | "<", false) => (false, None)
    +        case ("<=", false) | (">", true) => (true, None)
    +        case ("<=", true) | (">", false) => (false, Some(Nil))
    +        case _ => throw SparkException.internalError(s"Unexpected comparison $op.")
    +      }
    +      single(column, Values(nullAllowed, nan, others))
    +    } else {
    +      val v = normalize(value)
    +      // NaN is greater than v, and not equal to it.
    +      val (nan, ranges) = (op, negated) match {
    +        case ("=" | "<=>", false) | ("<>", true) => (false, Seq(point(v)))
    +        case ("=" | "<=>", true) | ("<>", false) =>
    +          (true, Seq(below(v, inclusive = false), above(v, inclusive = false)))
    +        case ("<", false) | (">=", true) => (false, Seq(below(v, inclusive = false)))
    +        case ("<=", false) | (">", true) => (false, Seq(below(v, inclusive = true)))
    +        case (">", false) | ("<=", true) => (true, Seq(above(v, inclusive = false)))
    +        case (">=", false) | ("<", true) => (true, Seq(above(v, inclusive = true)))
    +        case _ => throw SparkException.internalError(s"Unexpected comparison $op.")
    +      }
    +      single(column, Values(nullAllowed, nan, Some(ranges)))
    +    }
    +  }
    +
    +  private def in(column: Column, values: Seq[Any], negated: Boolean): Constraint = {
    +    val nonNull = values.filter(_ != null)
    +    val hasNaN = nonNull.exists(isNaN)
    +    val points = nonNull.filterNot(isNaN).map(normalize).sorted(column.ordering)
    +      .foldLeft(List.empty[Any]) {
    +        case (last :: rest, v) if column.ordering.equiv(last, v) => last :: rest
    +        case (acc, v) => v :: acc
    +      }.reverse
    +    if (!negated) {
    +      single(column, Values(nullAllowed = false, hasNaN, Some(points.map(point))))
    +    } else if (nonNull.length < values.length) {
    +      // NOT (x IN (..., NULL)) is never true: it is false or null.
    +      single(column, NoValue)
    +    } else if (points.isEmpty) {
    +      single(column, Values(nullAllowed = false, !hasNaN, None))
    +    } else {
    +      // The values between the points.
    +      val bounds = None +: points.map(Some(_)) :+ None
    +      val gaps = bounds.zip(bounds.tail).map { case (low, high) =>
    +        ValueRange(low, lowInclusive = false, high = high, highInclusive = false)
    +      }
    +      single(column, Values(nullAllowed = false, !hasNaN, Some(gaps)))
    +    }
    +  }
    +
    +  private def startsWith(column: Column, prefix: Any, negated: Boolean): Constraint = {
    +    (prefix, negated) match {
    +      case (null, _) => single(column, NoValue)
    +      // The strings that do not start with the prefix are not a range. A value whose bytes are not
    +      // valid UTF-8 could even be in the range of the strings that do.
    +      case (_, true) => single(column, anyValue(column))
    +      case (prefix: UTF8String, false) if prefix.numBytes() == 0 => single(column, anyValue(column))
    +      case (prefix: UTF8String, false) =>
    +        val range = ValueRange(Some(prefix), lowInclusive = true, high = nextPrefix(prefix),
    +          highInclusive = false)
    +        single(column, Values(nullAllowed = false, nanAllowed = false, Some(Seq(range))))
    +      case _ => All
    +    }
    +  }
    +
    +  /**
    +   * Returns the smallest string that is greater than all the strings that start with the prefix,
    +   * in the order of their UTF-8 bytes, which is the order of their code points, or None if there
    +   * is none: the prefix with its last code point incremented, after dropping the trailing
    +   * U+10FFFF, the largest code point.
    +   */
    +  private[columnar] def nextPrefix(prefix: UTF8String): Option[UTF8String] = {
    +    val codePoints = prefix.toString.codePoints().toArray.toBuffer
    +    while (codePoints.nonEmpty && codePoints.last == Character.MAX_CODE_POINT) {
    +      codePoints.remove(codePoints.length - 1)
    +    }
    +    if (codePoints.isEmpty) {
    +      None
    +    } else {
    +      val last = codePoints.last + 1
    +      // Skips the surrogates, which are not code points of characters.
    +      codePoints(codePoints.length - 1) =
    +        if (last >= Character.MIN_SURROGATE && last <= Character.MAX_SURROGATE) {
    +          Character.MAX_SURROGATE + 1
    +        } else {
    +          last
    +        }
    +      Some(UTF8String.fromString(new String(codePoints.toArray, 0, codePoints.length)))
    +    }
    +  }
    +
    +  private def single(column: Column, values: Values): Constraint = {
    +    // Only floating-point columns have NaN.
    +    val normalized = values.copy(nanAllowed = values.nanAllowed && column.isFloating)
    +    if (isAll(column, normalized)) All else Some(Map(column -> normalized))
    +  }
    +
    +  private def point(v: Any): ValueRange =
    +    ValueRange(Some(v), lowInclusive = true, high = Some(v), highInclusive = true)
    +
    +  private def below(v: Any, inclusive: Boolean): ValueRange =
    +    ValueRange(None, lowInclusive = false, high = Some(v), highInclusive = inclusive)
    +
    +  private def above(v: Any, inclusive: Boolean): ValueRange =
    +    ValueRange(Some(v), lowInclusive = inclusive, high = None, highInclusive = false)
    +
    +  private def anyValue(column: Column): Values = {
    +    Values(nullAllowed = false, nanAllowed = column.isFloating, None)
    +  }
    +
    +  private def isAll(column: Column, values: Values): Boolean = {
    +    values.nullAllowed && values.ranges.isEmpty && (values.nanAllowed || !column.isFloating)
    +  }
    +
    +  private def isEmpty(values: Values): Boolean = {
    +    !values.nullAllowed && !values.nanAllowed && values.ranges.exists(_.isEmpty)
    +  }
    +
    +  // Whether no row can make the predicates true.
    +  private def matchesNoRow(constraint: Constraint): Boolean = {
    +    constraint.forall(_.values.exists(isEmpty))
    +  }
    +
    +  private def and(left: Constraint, right: Constraint): Constraint = (left, right) match {
    +    case (Some(l), Some(r)) =>
    +      Some((l.keySet ++ r.keySet).map { column =>
    +        column -> ((l.get(column), r.get(column)) match {
    +          case (Some(a), Some(b)) => intersect(column, a, b)
    +          case (a, b) => a.orElse(b).get
    +        })
    +      }.toMap)
    +    case _ => NoRow
    +  }
    +
    +  // A column that only one side constrains can have any value in the rows of the other side, so
    +  // only the columns that both sides constrain are constrained.
    +  private def or(left: Constraint, right: Constraint): Constraint = {
    +    if (matchesNoRow(left)) {
    +      right
    +    } else if (matchesNoRow(right)) {
    +      left
    +    } else {
    +      val (l, r) = (left.get, right.get)
    +      Some(l.keySet.intersect(r.keySet).map(column => column -> union(column, l(column), r(column)))
    +        .filterNot { case (column, values) => isAll(column, values) }.toMap)
    +    }
    +  }
    +
    +  private def intersect(column: Column, a: Values, b: Values): Values = Values(
    +    a.nullAllowed && b.nullAllowed,
    +    a.nanAllowed && b.nanAllowed,
    +    (a.ranges, b.ranges) match {
    +      case (Some(x), Some(y)) => Some(intersectRanges(x, y, column.ordering))
    +      case (x, y) => x.orElse(y)
    +    })
    +
    +  private def union(column: Column, a: Values, b: Values): Values = Values(
    +    a.nullAllowed || b.nullAllowed,
    +    a.nanAllowed || b.nanAllowed,
    +    (a.ranges, b.ranges) match {
    +      case (Some(x), Some(y)) =>
    +        unionRanges(x, y, column.ordering) match {
    +          // All the values.
    +          case Seq(ValueRange(None, _, None, _)) => None
    +          case ranges => Some(ranges)
    +        }
    +      case _ => None
    +    })
    +
    +  // A negative value when `a` starts before `b`.
    +  private def compareLows(a: ValueRange, b: ValueRange, ordering: Ordering[Any]): Int = {
    +    (a.low, b.low) match {
    +      case (None, None) => 0
    +      case (None, _) => -1
    +      case (_, None) => 1
    +      case (Some(x), Some(y)) =>
    +        val c = ordering.compare(x, y)
    +        if (c != 0 || a.lowInclusive == b.lowInclusive) c else if (a.lowInclusive) -1 else 1
    +    }
    +  }
    +
    +  // A negative value when `a` ends before `b`.
    +  private def compareHighs(a: ValueRange, b: ValueRange, ordering: Ordering[Any]): Int = {
    +    (a.high, b.high) match {
    +      case (None, None) => 0
    +      case (None, _) => 1
    +      case (_, None) => -1
    +      case (Some(x), Some(y)) =>
    +        val c = ordering.compare(x, y)
    +        if (c != 0 || a.highInclusive == b.highInclusive) c else if (a.highInclusive) 1 else -1
    +    }
    +  }
    +
    +  private def isEmptyRange(range: ValueRange, ordering: Ordering[Any]): Boolean = {
    +    (range.low, range.high) match {
    +      case (Some(low), Some(high)) =>
    +        val c = ordering.compare(low, high)
    +        c > 0 || (c == 0 && !(range.lowInclusive && range.highInclusive))
    +      case _ => false
    +    }
    +  }
    +
    +  // Intersects two lists of sorted ranges that neither overlap nor touch, by sweeping them.
    +  private def intersectRanges(
    +      a: Seq[ValueRange],
    +      b: Seq[ValueRange],
    +      ordering: Ordering[Any]): Seq[ValueRange] = {
    +    val result = ArrayBuffer.empty[ValueRange]
    +    var i = 0
    +    var j = 0
    +    while (i < a.length && j < b.length) {

    Done in daba613: intersectRanges sweeps indexed copies of both inputs (toIndexedSeq), so each step is constant work. A new test derives the domains of an IN list of 100,000 values and of its NOT IN, each combined with a range of the same column, and checks the 99,949 points and the 99,950 gaps under a limit of 20 seconds. Here it takes about 0.2 seconds, while with the previous sweep it did not finish within a minute (91 seconds).

    HyukjinKwon HyukjinKwon commented on code on Oct 30, 2026 12:03 UTC
    Code Review
    sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnDomains.scala:1
    @@ -0,0 +1,534 @@
    +/*
    + * 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.
    + */
    +package org.apache.spark.sql.execution.datasources.v2.columnar
    +
    +import scala.collection.mutable.ArrayBuffer
    +
    +import org.apache.spark.SparkException
    +import org.apache.spark.sql.catalyst.expressions.Literal
    +import org.apache.spark.sql.catalyst.types.PhysicalDataType
    +import org.apache.spark.sql.catalyst.util.quoteIfNeeded
    +import org.apache.spark.sql.connector.expressions.{Expression, LiteralValue, NamedReference}
    +import org.apache.spark.sql.connector.expressions.filter.Predicate
    +import org.apache.spark.sql.types._
    +import org.apache.spark.unsafe.types.UTF8String
    +
    +/**
    + * The values that a column can have in the rows that match the filters of a query: null if
    + * `nullAllowed`, NaN if `nanAllowed`, for a float or double column, and the other values in one
    + * of the `ranges`, or any of them without ranges. A data source can skip the data whose statistics
    + * show that it has no value in the domain of a column, but never a row whose values are in their
    + * domains: Spark evaluates the filters after reading anyway.
    + *
    + * @param path the index of the column in the read schema, and then the index of the field in each
    + *             struct, for a field of a struct
    + * @param name the names of the column and of its fields
    + * @param ranges sorted ranges, which neither overlap nor touch, of the values other than null and
    + *               NaN, in the internal representation of Spark. None if the column can have any of
    + *               them, and empty if it can have none.
    + */
    +case class ColumnDomain(
    +    path: Seq[Int],
    +    name: Seq[String],
    +    dataType: DataType,
    +    nullAllowed: Boolean,
    +    nanAllowed: Boolean,
    +    ranges: Option[Seq[ValueRange]]) {
    +
    +  private def ordering: Ordering[Any] = PhysicalDataType.ordering(dataType)
    +
    +  /** Whether the domain has the value, in the internal representation of Spark. */
    +  def contains(value: Any): Boolean = value match {
    +    case null => nullAllowed
    +    case f: Float if f.isNaN => nanAllowed
    +    case d: Double if d.isNaN => nanAllowed
    +    case _ => ranges.forall(_.exists(_.contains(value, ordering)))
    +  }
    +
    +  override def toString: String = {
    +    def literal(value: Any): String = Literal(value, dataType).sql
    +    val values = ranges match {
    +      case None => Seq("ANY")
    +      case Some(ranges) => ranges.map {
    +        case ValueRange(Some(low), true, Some(high), true) if ordering.equiv(low, high) =>
    +          literal(low)
    +        case range =>
    +          (if (range.lowInclusive) "[" else "(") + range.low.map(literal).getOrElse("-inf") +
    +            ", " + range.high.map(literal).getOrElse("+inf") +
    +            (if (range.highInclusive) "]" else ")")
    +      }
    +    }
    +    val special = (if (nullAllowed) Seq("NULL") else Nil) ++ (if (nanAllowed) Seq("NaN") else Nil)
    +    val all = special ++ values
    +    s"${name.map(quoteIfNeeded).mkString(".")}: ${if (all.isEmpty) "NONE" else all.mkString(", ")}"
    +  }
    +}
    +
    +/**
    + * A range of values in the internal representation of Spark: the values above `low`, or equal to
    + * it if `lowInclusive`, and below `high`, or equal to it if `highInclusive`. A bound that is None
    + * is unbounded, and is not inclusive.
    + */
    +case class ValueRange(low: Option[Any], lowInclusive: Boolean, high: Option[Any],
    +    highInclusive: Boolean) {
    +
    +  def contains(value: Any, ordering: Ordering[Any]): Boolean = {
    +    low.forall { l =>
    +      val c = ordering.compare(value, l)
    +      c > 0 || (c == 0 && lowInclusive)
    +    } && high.forall { h =>
    +      val c = ordering.compare(value, h)
    +      c < 0 || (c == 0 && highInclusive)
    +    }
    +  }
    +}
    +
    +/**
    + * The domains that a query passes to a data source, and the predicates that each of them comes
    + * from.
    + *
    + * @param domains the domains, at most one for each column, sorted by path
    + * @param columns the paths of the columns that each predicate constrains
    + */
    +case class ColumnDomains(domains: Seq[ColumnDomain], columns: Seq[Set[Seq[Int]]]) {
    +
    +  /**
    +   * Returns the predicates that constrain only the columns whose domains are used, given whether
    +   * the data source uses each domain.
    +   */
    +  def pushedPredicates(predicates: Array[Predicate], used: Seq[Boolean]): Array[Predicate] = {
    +    val usedPaths = domains.zip(used).collect { case (domain, true) => domain.path }.toSet
    +    predicates.zip(columns).collect {
    +      case (predicate, paths) if paths.nonEmpty && paths.subsetOf(usedPaths) => predicate
    +    }
    +  }
    +}
    +
    +/**
    + * Derives the domains of the columns that the predicates of a query constrain, the ones that Data
    + * Source V2 pushes to a scan, combined with AND. A domain is a superset of the values that a column
    + * has in the rows for which all the predicates are true: Spark derives it from the comparisons of
    + * a column with literals, IN, IS NULL, IS NOT NULL and STARTS_WITH, under AND, OR and NOT, with the
    + * semantics of Spark SQL. Comparisons with null are null, NaN is equal to NaN and greater than any
    + * other value, -0.0 is equal to 0.0, and strings and binary values are compared by their bytes, as
    + * unsigned bytes. A predicate that cannot be expressed this way does not constrain any column. Only
    + * the columns and the fields of structs of the types that a data source can compare get a domain:
    + * not the strings of a non-binary collation, nor arrays, maps and structs.
    + */
    +object ColumnDomains {
    +
    +  // A column that a predicate constrains, with its type.
    +  private case class Column(path: Seq[Int], name: Seq[String], dataType: DataType) {
    +    val ordering: Ordering[Any] = PhysicalDataType.ordering(dataType)
    +    val isFloating: Boolean = dataType == FloatType || dataType == DoubleType
    +  }
    +
    +  // The values that a column can have: see ColumnDomain.
    +  private case class Values(nullAllowed: Boolean, nanAllowed: Boolean,
    +      ranges: Option[Seq[ValueRange]])
    +
    +  private val NoValue = Values(nullAllowed = false, nanAllowed = false, Some(Nil))
    +  private val OnlyNull = Values(nullAllowed = true, nanAllowed = false, Some(Nil))
    +
    +  // The columns that the predicates constrain, with their values: a row can only make the
    +  // predicates true if each of these columns has one of the values. None when no row can.
    +  private type Constraint = Option[Map[Column, Values]]
    +  private val All: Constraint = Some(Map.empty)
    +  private val NoRow: Constraint = None
    +
    +  /** Derives the domains of the predicates for a scan of the schema. */
    +  def derive(predicates: Seq[Predicate], schema: StructType): ColumnDomains = {
    +    val constraints = predicates.map(constraint(_, negated = false, schema))
    +    val columns = constraints.map(_.map(_.keySet.map(_.path)).getOrElse(Set.empty[Seq[Int]]))
    +    val domains = constraints.foldLeft(All)(and) match {
    +      case Some(values) =>
    +        values.toSeq.map { case (column, v) =>
    +          ColumnDomain(column.path, column.name, column.dataType, v.nullAllowed, v.nanAllowed,
    +            v.ranges)
    +        }.sortBy(_.path)(Ordering.Implicits.seqOrdering[Seq, Int])
    +      // A predicate that is always false, which Spark usually removes before it scans the data.
    +      case None => Nil
    +    }
    +    ColumnDomains(domains, columns)
    +  }
    +
    +  // The rows for which the predicate is true, or false if negated: NOT moves to the leaves.
    +  private def constraint(predicate: Predicate, negated: Boolean, schema: StructType): Constraint = {
    +    def child(i: Int): Option[Predicate] = predicate.children().lift(i).collect {
    +      case p: Predicate => p
    +    }
    +    def both(combine: (Constraint, Constraint) => Constraint, negated: Boolean): Constraint = {
    +      (child(0), child(1)) match {
    +        case (Some(left), Some(right)) =>
    +          combine(constraint(left, negated, schema), constraint(right, negated, schema))
    +        case _ => All
    +      }
    +    }
    +    predicate.name() match {
    +      case "AND" => if (negated) both(or, negated = true) else both(and, negated = false)
    +      case "OR" => if (negated) both(and, negated = true) else both(or, negated = false)
    +      case "NOT" => child(0).map(constraint(_, !negated, schema)).getOrElse(All)
    +      case "ALWAYS_TRUE" => if (negated) NoRow else All
    +      case "ALWAYS_FALSE" => if (negated) All else NoRow
    +      case _ => leaf(predicate, negated, schema).getOrElse(All)
    +    }
    +  }
    +
    +  private def leaf(
    +      predicate: Predicate,
    +      negated: Boolean,
    +      schema: StructType): Option[Constraint] = {
    +    val children = predicate.children()
    +    predicate.name() match {
    +      case "IS_NULL" | "IS_NOT_NULL" if children.length == 1 =>
    +        column(children(0), schema).map { col =>
    +          val isNull = (predicate.name() == "IS_NULL") != negated
    +          single(col, if (isNull) OnlyNull else anyValue(col))
    +        }
    +      case op @ ("=" | "<>" | "<=>" | "<" | "<=" | ">" | ">=") if children.length == 2 =>
    +        val operands = (column(children(0), schema), column(children(1), schema)) match {
    +          case (Some(col), _) => literal(children(1), col).map((col, _, op))
    +          case (_, Some(col)) => literal(children(0), col).map((col, _, flip(op)))
    +          case _ => None
    +        }
    +        operands.map { case (col, value, op) => compare(col, value, op, negated) }
    +      case "IN" if children.nonEmpty =>
    +        column(children(0), schema).flatMap { col =>
    +          val values = children.tail.map(literal(_, col))
    +          if (values.forall(_.isDefined)) Some(in(col, values.map(_.get).toSeq, negated)) else None
    +        }
    +      case "STARTS_WITH" if children.length == 2 =>
    +        column(children(0), schema).filter(_.dataType.isInstanceOf[StringType]).flatMap { col =>
    +          literal(children(1), col).map(prefix => startsWith(col, prefix, negated))
    +        }
    +      case _ => None
    +    }
    +  }
    +
    +  private def flip(op: String): String = op match {
    +    case "<" => ">"
    +    case "<=" => ">="
    +    case ">" => "<"
    +    case ">=" => "<="
    +    case other => other
    +  }
    +
    +  private def compare(column: Column, value: Any, op: String, negated: Boolean): Constraint = {
    +    // NOT (x <=> v) is true for null, unless v is null.
    +    val nullAllowed = op == "<=>" && negated && value != null
    +    if (value == null) {
    +      // A comparison with null is null, and so is its negation, but x <=> NULL is x IS NULL.
    +      if (op == "<=>") single(column, if (negated) anyValue(column) else OnlyNull)
    +      else single(column, NoValue)
    +    } else if (isNaN(value)) {
    +      // NaN is equal to NaN and greater than any other value: (NaN, other values).
    +      val (nan, others) = (op, negated) match {
    +        case ("=" | "<=>" | ">=", false) | ("<>" | "<", true) => (true, Some(Nil))
    +        case ("=" | "<=>" | ">=", true) | ("<>" | "<", false) => (false, None)
    +        case ("<=", false) | (">", true) => (true, None)
    +        case ("<=", true) | (">", false) => (false, Some(Nil))
    +        case _ => throw SparkException.internalError(s"Unexpected comparison $op.")
    +      }
    +      single(column, Values(nullAllowed, nan, others))
    +    } else {
    +      val v = normalize(value)
    +      // NaN is greater than v, and not equal to it.
    +      val (nan, ranges) = (op, negated) match {
    +        case ("=" | "<=>", false) | ("<>", true) => (false, Seq(point(v)))
    +        case ("=" | "<=>", true) | ("<>", false) =>
    +          (true, Seq(below(v, inclusive = false), above(v, inclusive = false)))
    +        case ("<", false) | (">=", true) => (false, Seq(below(v, inclusive = false)))
    +        case ("<=", false) | (">", true) => (false, Seq(below(v, inclusive = true)))
    +        case (">", false) | ("<=", true) => (true, Seq(above(v, inclusive = false)))
    +        case (">=", false) | ("<", true) => (true, Seq(above(v, inclusive = true)))
    +        case _ => throw SparkException.internalError(s"Unexpected comparison $op.")
    +      }
    +      single(column, Values(nullAllowed, nan, Some(ranges)))
    +    }
    +  }
    +
    +  private def in(column: Column, values: Seq[Any], negated: Boolean): Constraint = {
    +    val nonNull = values.filter(_ != null)
    +    val hasNaN = nonNull.exists(isNaN)
    +    val points = nonNull.filterNot(isNaN).map(normalize).sorted(column.ordering)
    +      .foldLeft(List.empty[Any]) {
    +        case (last :: rest, v) if column.ordering.equiv(last, v) => last :: rest
    +        case (acc, v) => v :: acc
    +      }.reverse
    +    if (!negated) {
    +      single(column, Values(nullAllowed = false, hasNaN, Some(points.map(point))))
    +    } else if (nonNull.length < values.length) {
    +      // NOT (x IN (..., NULL)) is never true: it is false or null.
    +      single(column, NoValue)
    +    } else if (points.isEmpty) {
    +      single(column, Values(nullAllowed = false, !hasNaN, None))
    +    } else {
    +      // The values between the points.
    +      val bounds = None +: points.map(Some(_)) :+ None
    +      val gaps = bounds.zip(bounds.tail).map { case (low, high) =>
    +        ValueRange(low, lowInclusive = false, high = high, highInclusive = false)
    +      }
    +      single(column, Values(nullAllowed = false, !hasNaN, Some(gaps)))
    +    }
    +  }
    +
    +  private def startsWith(column: Column, prefix: Any, negated: Boolean): Constraint = {
    +    (prefix, negated) match {
    +      case (null, _) => single(column, NoValue)
    +      // The strings that do not start with the prefix are not a range. A value whose bytes are not
    +      // valid UTF-8 could even be in the range of the strings that do.
    +      case (_, true) => single(column, anyValue(column))
    +      case (prefix: UTF8String, false) if prefix.numBytes() == 0 => single(column, anyValue(column))
    +      case (prefix: UTF8String, false) =>
    +        val range = ValueRange(Some(prefix), lowInclusive = true, high = nextPrefix(prefix),
    +          highInclusive = false)
    +        single(column, Values(nullAllowed = false, nanAllowed = false, Some(Seq(range))))
    +      case _ => All
    +    }
    +  }
    +
    +  /**
    +   * Returns the smallest string that is greater than all the strings that start with the prefix,
    +   * in the order of their UTF-8 bytes, which is the order of their code points, or None if there
    +   * is none: the prefix with its last code point incremented, after dropping the trailing
    +   * U+10FFFF, the largest code point.
    +   */
    +  private[columnar] def nextPrefix(prefix: UTF8String): Option[UTF8String] = {
    +    val codePoints = prefix.toString.codePoints().toArray.toBuffer
    +    while (codePoints.nonEmpty && codePoints.last == Character.MAX_CODE_POINT) {
    +      codePoints.remove(codePoints.length - 1)
    +    }
    +    if (codePoints.isEmpty) {
    +      None
    +    } else {
    +      val last = codePoints.last + 1
    +      // Skips the surrogates, which are not code points of characters.
    +      codePoints(codePoints.length - 1) =
    +        if (last >= Character.MIN_SURROGATE && last <= Character.MAX_SURROGATE) {
    +          Character.MAX_SURROGATE + 1
    +        } else {
    +          last
    +        }
    +      Some(UTF8String.fromString(new String(codePoints.toArray, 0, codePoints.length)))
    +    }
    +  }
    +
    +  private def single(column: Column, values: Values): Constraint = {
    +    // Only floating-point columns have NaN.
    +    val normalized = values.copy(nanAllowed = values.nanAllowed && column.isFloating)
    +    if (isAll(column, normalized)) All else Some(Map(column -> normalized))
    +  }
    +
    +  private def point(v: Any): ValueRange =
    +    ValueRange(Some(v), lowInclusive = true, high = Some(v), highInclusive = true)
    +
    +  private def below(v: Any, inclusive: Boolean): ValueRange =
    +    ValueRange(None, lowInclusive = false, high = Some(v), highInclusive = inclusive)
    +
    +  private def above(v: Any, inclusive: Boolean): ValueRange =
    +    ValueRange(Some(v), lowInclusive = inclusive, high = None, highInclusive = false)
    +
    +  private def anyValue(column: Column): Values = {
    +    Values(nullAllowed = false, nanAllowed = column.isFloating, None)
    +  }
    +
    +  private def isAll(column: Column, values: Values): Boolean = {
    +    values.nullAllowed && values.ranges.isEmpty && (values.nanAllowed || !column.isFloating)
    +  }
    +
    +  private def isEmpty(values: Values): Boolean = {
    +    !values.nullAllowed && !values.nanAllowed && values.ranges.exists(_.isEmpty)
    +  }
    +
    +  // Whether no row can make the predicates true.
    +  private def matchesNoRow(constraint: Constraint): Boolean = {
    +    constraint.forall(_.values.exists(isEmpty))
    +  }
    +
    +  private def and(left: Constraint, right: Constraint): Constraint = (left, right) match {
    +    case (Some(l), Some(r)) =>
    +      Some((l.keySet ++ r.keySet).map { column =>
    +        column -> ((l.get(column), r.get(column)) match {
    +          case (Some(a), Some(b)) => intersect(column, a, b)
    +          case (a, b) => a.orElse(b).get
    +        })
    +      }.toMap)
    +    case _ => NoRow
    +  }
    +
    +  // A column that only one side constrains can have any value in the rows of the other side, so
    +  // only the columns that both sides constrain are constrained.
    +  private def or(left: Constraint, right: Constraint): Constraint = {
    +    if (matchesNoRow(left)) {
    +      right
    +    } else if (matchesNoRow(right)) {
    +      left
    +    } else {
    +      val (l, r) = (left.get, right.get)
    +      Some(l.keySet.intersect(r.keySet).map(column => column -> union(column, l(column), r(column)))
    +        .filterNot { case (column, values) => isAll(column, values) }.toMap)
    +    }
    +  }
    +
    +  private def intersect(column: Column, a: Values, b: Values): Values = Values(
    +    a.nullAllowed && b.nullAllowed,
    +    a.nanAllowed && b.nanAllowed,
    +    (a.ranges, b.ranges) match {
    +      case (Some(x), Some(y)) => Some(intersectRanges(x, y, column.ordering))
    +      case (x, y) => x.orElse(y)
    +    })
    +
    +  private def union(column: Column, a: Values, b: Values): Values = Values(
    +    a.nullAllowed || b.nullAllowed,
    +    a.nanAllowed || b.nanAllowed,
    +    (a.ranges, b.ranges) match {
    +      case (Some(x), Some(y)) =>
    +        unionRanges(x, y, column.ordering) match {
    +          // All the values.
    +          case Seq(ValueRange(None, _, None, _)) => None
    +          case ranges => Some(ranges)
    +        }
    +      case _ => None
    +    })
    +
    +  // A negative value when `a` starts before `b`.
    +  private def compareLows(a: ValueRange, b: ValueRange, ordering: Ordering[Any]): Int = {
    +    (a.low, b.low) match {
    +      case (None, None) => 0
    +      case (None, _) => -1
    +      case (_, None) => 1
    +      case (Some(x), Some(y)) =>
    +        val c = ordering.compare(x, y)
    +        if (c != 0 || a.lowInclusive == b.lowInclusive) c else if (a.lowInclusive) -1 else 1
    +    }
    +  }
    +
    +  // A negative value when `a` ends before `b`.
    +  private def compareHighs(a: ValueRange, b: ValueRange, ordering: Ordering[Any]): Int = {
    +    (a.high, b.high) match {
    +      case (None, None) => 0
    +      case (None, _) => 1
    +      case (_, None) => -1
    +      case (Some(x), Some(y)) =>
    +        val c = ordering.compare(x, y)
    +        if (c != 0 || a.highInclusive == b.highInclusive) c else if (a.highInclusive) 1 else -1
    +    }
    +  }
    +
    +  private def isEmptyRange(range: ValueRange, ordering: Ordering[Any]): Boolean = {
    +    (range.low, range.high) match {
    +      case (Some(low), Some(high)) =>
    +        val c = ordering.compare(low, high)
    +        c > 0 || (c == 0 && !(range.lowInclusive && range.highInclusive))
    +      case _ => false
    +    }
    +  }
    +
    +  // Intersects two lists of sorted ranges that neither overlap nor touch, by sweeping them.
    +  private def intersectRanges(
    +      a: Seq[ValueRange],
    +      b: Seq[ValueRange],
    +      ordering: Ordering[Any]): Seq[ValueRange] = {
    +    val result = ArrayBuffer.empty[ValueRange]
    +    var i = 0
    +    var j = 0
    +    while (i < a.length && j < b.length) {
    +      val (x, y) = (a(i), b(j))

    Done in daba613: intersectRanges sweeps indexed copies of both inputs (toIndexedSeq), so it is linear again. The new test "the domains of long IN lists" combines IN and NOT IN lists of 100,000 values with a range of the same column, and takes about 0.2 seconds, against 91 seconds before.

    HyukjinKwon HyukjinKwon commented on code on Oct 30, 2026 12:03 UTC
    Code Review
    sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnarDataSourceSuite.scala:1
    @@ -83,6 +83,34 @@ class ColumnarDataSourceSuite extends QueryTest with SharedSparkSession {
         assert(scan(limited).getMetaData()("PushedLimit") == "LIMIT 2")
       }
     
    +  test("push down the domains of filtered columns") {
    +    val df = spark.read.format(format).option("end", "100").load()
    +      .filter("id >= 40 AND id < 50 AND name <> 'x'")
    +    checkAnswer(df, (40L until 50L).map(id => Row(id, s"name$id")))
    +    // The data source only uses the domain of id, to read the ids in it.
    +    val metadata = scan(df).getMetaData()
    +    assert(metadata("PushedDomains") == "[id: [40L, 50L)]")
    +    val pushed = metadata("PushedFilters")
    +    assert(pushed.contains("id >= 40") && pushed.contains("id < 50"), pushed)
    +    assert(!pushed.contains("name"), pushed)
    +    assert(scan(df).toBatch.planInputPartitions().toSeq ==
    +      Seq(TestRangePartition(40, 45), TestRangePartition(45, 50)))
    +
    +    // A filter that is not a domain is not pushed, and Spark evaluates all the filters after
    +    // reading: here, the data source reads all the ids that are not 3.

    Done in daba613: the test now reads id <> 3 AND id < 8. It asserts the partitions [0, 4) and [4, 8), which include 3, and an answer without 3, so it fails if Spark stops evaluating the pushed predicates after the scan. The comment of the id % 2 = 0 case now says that the data source reads all the ids, and the case checks that only NOT (id = 3) is pushed.

    HyukjinKwon HyukjinKwon commented on code on Oct 30, 2026 12:03 UTC
    Code Review
    sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/ffi/NativeDataSourceSuite.scala:1
    @@ -394,6 +399,88 @@ class NativeDataSourceSuite extends QueryTest with SharedSparkSession {
         assert(!scan(filtered).getMetaData().contains("PushedLimit"))
       }
     
    +  nativeTest("push down the domains of filtered columns") {
    +    val file = new File(Utils.createTempDir(), "domains")
    +    def readIn(session: SparkSession, options: (String, String)*): DataFrame = {
    +      file.delete()
    +      range(session, Seq("end" -> "45", "domains_path" -> file.getPath) ++ options: _*)
    +    }
    +    def read(options: (String, String)*): DataFrame = {
    +      readIn(newSession(defaultPackage), options: _*)
    +    }
    +    // The domains that the library got: for each, the path of the column, whether null and NaN are
    +    // in the domain, and the ranges.
    +    def received(): Seq[String] = Files.readAllLines(file.toPath, UTF_8).asScala.toSeq
    +
    +    // The library reads the blocks of 10 rows whose ids may match, [10, 20) and [20, 30), with all
    +    // their rows, and Spark filters the rows after reading.
    +    val df = read().filter("id > 13 AND id < 27")
    +    checkRows(df, (14L until 27L).map(expectedRow))
    +    assert(received() == Seq("0 - - (13,27)"))

    Done in daba613: the native test now also reads with NOT (id <=> 5) (null and two ranges), name IS NULL (null without ranges), id NOT IN (5, 20) (three ranges) and id < 3 OR (id > 22 AND id < 25), whose two ranges make the library skip three of its five blocks. Each case asserts the null flag and all the ranges that the library receives, and the rows. The collated case now reads with use_domains = all and domains_path, and checks that the library only gets the domain of id, and that the filter on the collated column is not shown as pushed.

    HyukjinKwon HyukjinKwon commented on code on Oct 30, 2026 12:03 UTC
    Code Review
    sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnDomainsSuite.scala:1
    @@ -0,0 +1,305 @@
    +/*
    + * 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.
    + */
    +package org.apache.spark.sql.execution.datasources.v2.columnar
    +
    +import java.sql.Date
    +
    +import scala.jdk.CollectionConverters._
    +import scala.util.Random
    +
    +import org.apache.spark.sql.{QueryTest, Row}
    +import org.apache.spark.sql.catalyst.CatalystTypeConverters
    +import org.apache.spark.sql.catalyst.expressions.{Literal, PredicateHelper}
    +import org.apache.spark.sql.catalyst.plans.logical.Filter
    +import org.apache.spark.sql.connector.expressions.filter.Predicate
    +import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Strategy
    +import org.apache.spark.sql.functions.expr
    +import org.apache.spark.sql.test.SharedSparkSession
    +import org.apache.spark.sql.types._
    +import org.apache.spark.unsafe.types.UTF8String
    +
    +/** Tests how [[ColumnDomains]] derives the domains of columns from the predicates of a query. */
    +class ColumnDomainsSuite extends QueryTest with SharedSparkSession with PredicateHelper {
    +
    +  private val schema = StructType.fromDDL("id BIGINT, i INT, d DOUBLE, f FLOAT, s STRING, " +
    +    "b BINARY, flag BOOLEAN, dt DATE, ts TIMESTAMP, dec DECIMAL(10, 2), " +
    +    "st STRUCT<x: INT, y: STRING>, arr ARRAY<INT>, c STRING COLLATE UTF8_LCASE")
    +
    +  private def char(codePoint: Int): String = new String(Character.toChars(codePoint))
    +
    +  /**
    +   * The predicates that Data Source V2 pushes for the filter, as in the analyzed plan with the
    +   * constants folded: the optimizer would rewrite some of them, such as NOT (x > 1).
    +   */
    +  private def predicates(filter: String, schema: StructType): Seq[Predicate] = {
    +    val df = spark.createDataFrame(Seq.empty[Row].asJava, schema)
    +    val condition = df.where(filter).queryExecution.analyzed.collectFirst {
    +      case Filter(condition, _) => condition
    +    }.get
    +    splitConjunctivePredicates(condition.transformUp {
    +      case e if e.foldable && !e.isInstanceOf[Literal] => Literal.create(e.eval(), e.dataType)
    +    }).flatMap(DataSourceV2Strategy.translateFilterV2)
    +  }
    +
    +  private def domains(filter: String): Seq[String] = {
    +    ColumnDomains.derive(predicates(filter, schema), schema).domains.map(_.toString)
    +  }
    +
    +  test("comparisons, IN and null checks") {
    +    assert(domains("id > 5") == Seq("id: (5L, +inf)"))
    +    assert(domains("5 < id") == Seq("id: (5L, +inf)"))
    +    assert(domains("id >= 5 AND id < 10") == Seq("id: [5L, 10L)"))
    +    assert(domains("id <= 5") == Seq("id: (-inf, 5L]"))
    +    assert(domains("id = 5") == Seq("id: 5L"))
    +    assert(domains("id <> 5") == Seq("id: (-inf, 5L), (5L, +inf)"))
    +    assert(domains("id <=> 5") == Seq("id: 5L"))
    +    // x <=> v is true for null when false, and so is NOT (x <=> v).

    Done in daba613, with the suggested wording.

    spark-test spark-test commented on Oct 30, 2026 12:55 UTC
    Contributor

    The AI review requested by @HyukjinKwon did not finish. A committer can add the ai-review-requested label again to retry.

    <!-- SPARK_OSS_REVIEW_REQUEST 34684729586 -->

    spark-test spark-test commented on code on Oct 30, 2026 16:07 UTC
    Code Review
    sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnDomainsSuite.scala:1
    @@ -0,0 +1,381 @@
    +/*
    + * 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.
    + */
    +package org.apache.spark.sql.execution.datasources.v2.columnar
    +
    +import java.sql.Date
    +
    +import scala.jdk.CollectionConverters._
    +import scala.util.Random
    +
    +import org.scalatest.concurrent.TimeLimits
    +import org.scalatest.time.SpanSugar._
    +
    +import org.apache.spark.sql.{Column, QueryTest, Row}
    +import org.apache.spark.sql.catalyst.{CatalystTypeConverters, InternalRow}
    +import org.apache.spark.sql.catalyst.expressions.{Literal, PredicateHelper}
    +import org.apache.spark.sql.catalyst.plans.logical.Filter
    +import org.apache.spark.sql.connector.expressions.{Expression => V2Expression, FieldReference, LiteralValue}
    +import org.apache.spark.sql.connector.expressions.filter.Predicate
    +import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Strategy
    +import org.apache.spark.sql.functions.{col, expr, not}
    +import org.apache.spark.sql.internal.SQLConf
    +import org.apache.spark.sql.test.SharedSparkSession
    +import org.apache.spark.sql.types._
    +import org.apache.spark.unsafe.types.UTF8String
    +
    +/** Tests how [[ColumnDomains]] derives the domains of columns from the predicates of a query. */
    +class ColumnDomainsSuite extends QueryTest with SharedSparkSession with PredicateHelper
    +  with TimeLimits {
    +
    +  private val schema = StructType.fromDDL("id BIGINT, i INT, d DOUBLE, f FLOAT, s STRING, " +
    +    "b BINARY, flag BOOLEAN, dt DATE, ts TIMESTAMP, dec DECIMAL(10, 2), " +
    +    "st STRUCT<x: INT, y: STRING>, arr ARRAY<INT>, c STRING COLLATE UTF8_LCASE")
    +
    +  private def char(codePoint: Int): String = new String(Character.toChars(codePoint))
    +
    +  /**
    +   * The predicates that Data Source V2 pushes for the filter, as in the analyzed plan with the
    +   * constants folded: the optimizer would rewrite some of them, such as NOT (x > 1).
    +   */
    +  private def predicates(filter: String, schema: StructType): Seq[Predicate] = {
    +    predicates(expr(filter), schema)
    +  }
    +
    +  private def predicates(filter: Column, schema: StructType): Seq[Predicate] = {
    +    val df = spark.createDataFrame(Seq.empty[Row].asJava, schema)
    +    val condition = df.where(filter).queryExecution.analyzed.collectFirst {
    +      case Filter(condition, _) => condition
    +    }.get
    +    splitConjunctivePredicates(condition.transformUp {
    +      case e if e.foldable && !e.isInstanceOf[Literal] => Literal.create(e.eval(), e.dataType)
    +    }).flatMap(DataSourceV2Strategy.translateFilterV2)
    +  }
    +
    +  private def domains(filter: String): Seq[String] = domains(expr(filter))
    +
    +  private def domains(filter: Column): Seq[String] = {
    +    ColumnDomains.derive(predicates(filter, schema), schema).domains.map(_.toString)
    +  }
    +
    +  test("comparisons, IN and null checks") {
    +    assert(domains("id > 5") == Seq("id: (5L, +inf)"))
    +    assert(domains("5 < id") == Seq("id: (5L, +inf)"))
    +    assert(domains("id >= 5 AND id < 10") == Seq("id: [5L, 10L)"))
    +    assert(domains("id <= 5") == Seq("id: (-inf, 5L]"))
    +    assert(domains("id = 5") == Seq("id: 5L"))
    +    assert(domains("id <> 5") == Seq("id: (-inf, 5L), (5L, +inf)"))
    +    assert(domains("id <=> 5") == Seq("id: 5L"))
    +    // x <=> v is false, not null, when x is null, so NOT (x <=> v) is true for null.
    +    assert(domains("NOT (id <=> 5)") == Seq("id: NULL, (-inf, 5L), (5L, +inf)"))
    +    assert(domains("id <=> NULL") == Seq("id: NULL"))
    +    assert(domains("NOT (id <=> NULL)") == Seq("id: ANY"))
    +    assert(domains("id IS NULL") == Seq("id: NULL"))
    +    assert(domains("id IS NOT NULL") == Seq("id: ANY"))
    +    assert(domains("id IN (3, 1, 2, 3)") == Seq("id: 1L, 2L, 3L"))
    +    assert(domains("id NOT IN (1, 3)") == Seq("id: (-inf, 1L), (1L, 3L), (3L, +inf)"))
    +    // Comparisons with null are null: so is NOT (x IN (..., NULL)), which matches no row.

    Nit (P3): When x equals a listed value, x IN (..., NULL) is true, so NOT (x IN (..., NULL)) is false, not null. The expression is false or null and never true. That is why NONE is the right domain, and it is what the comment in ColumnDomains.in says. As written, this comment teaches the wrong rule for exactly the NOT IN-with-NULL case.

        // Comparisons with null are null, and NOT (x IN (..., NULL)) is false or null: never true.
    

    Verification:

  • Inspection: The comment above the NOT IN-with-NULL assertions states that the expression is false or null, never true, and no longer claims that it is null, matching the explanation in the derivation code.
  • spark-test spark-test commented on code on Oct 30, 2026 16:07 UTC
    Code Review
    sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnDomainsSuite.scala:1
    @@ -0,0 +1,381 @@
    +/*
    + * 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.
    + */
    +package org.apache.spark.sql.execution.datasources.v2.columnar
    +
    +import java.sql.Date
    +
    +import scala.jdk.CollectionConverters._
    +import scala.util.Random
    +
    +import org.scalatest.concurrent.TimeLimits
    +import org.scalatest.time.SpanSugar._
    +
    +import org.apache.spark.sql.{Column, QueryTest, Row}
    +import org.apache.spark.sql.catalyst.{CatalystTypeConverters, InternalRow}
    +import org.apache.spark.sql.catalyst.expressions.{Literal, PredicateHelper}
    +import org.apache.spark.sql.catalyst.plans.logical.Filter
    +import org.apache.spark.sql.connector.expressions.{Expression => V2Expression, FieldReference, LiteralValue}
    +import org.apache.spark.sql.connector.expressions.filter.Predicate
    +import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Strategy
    +import org.apache.spark.sql.functions.{col, expr, not}
    +import org.apache.spark.sql.internal.SQLConf
    +import org.apache.spark.sql.test.SharedSparkSession
    +import org.apache.spark.sql.types._
    +import org.apache.spark.unsafe.types.UTF8String
    +
    +/** Tests how [[ColumnDomains]] derives the domains of columns from the predicates of a query. */
    +class ColumnDomainsSuite extends QueryTest with SharedSparkSession with PredicateHelper
    +  with TimeLimits {
    +
    +  private val schema = StructType.fromDDL("id BIGINT, i INT, d DOUBLE, f FLOAT, s STRING, " +
    +    "b BINARY, flag BOOLEAN, dt DATE, ts TIMESTAMP, dec DECIMAL(10, 2), " +
    +    "st STRUCT<x: INT, y: STRING>, arr ARRAY<INT>, c STRING COLLATE UTF8_LCASE")
    +
    +  private def char(codePoint: Int): String = new String(Character.toChars(codePoint))
    +
    +  /**
    +   * The predicates that Data Source V2 pushes for the filter, as in the analyzed plan with the
    +   * constants folded: the optimizer would rewrite some of them, such as NOT (x > 1).
    +   */
    +  private def predicates(filter: String, schema: StructType): Seq[Predicate] = {
    +    predicates(expr(filter), schema)
    +  }
    +
    +  private def predicates(filter: Column, schema: StructType): Seq[Predicate] = {
    +    val df = spark.createDataFrame(Seq.empty[Row].asJava, schema)
    +    val condition = df.where(filter).queryExecution.analyzed.collectFirst {
    +      case Filter(condition, _) => condition
    +    }.get
    +    splitConjunctivePredicates(condition.transformUp {
    +      case e if e.foldable && !e.isInstanceOf[Literal] => Literal.create(e.eval(), e.dataType)
    +    }).flatMap(DataSourceV2Strategy.translateFilterV2)
    +  }
    +
    +  private def domains(filter: String): Seq[String] = domains(expr(filter))
    +
    +  private def domains(filter: Column): Seq[String] = {
    +    ColumnDomains.derive(predicates(filter, schema), schema).domains.map(_.toString)
    +  }
    +
    +  test("comparisons, IN and null checks") {
    +    assert(domains("id > 5") == Seq("id: (5L, +inf)"))
    +    assert(domains("5 < id") == Seq("id: (5L, +inf)"))
    +    assert(domains("id >= 5 AND id < 10") == Seq("id: [5L, 10L)"))
    +    assert(domains("id <= 5") == Seq("id: (-inf, 5L]"))
    +    assert(domains("id = 5") == Seq("id: 5L"))
    +    assert(domains("id <> 5") == Seq("id: (-inf, 5L), (5L, +inf)"))
    +    assert(domains("id <=> 5") == Seq("id: 5L"))
    +    // x <=> v is false, not null, when x is null, so NOT (x <=> v) is true for null.
    +    assert(domains("NOT (id <=> 5)") == Seq("id: NULL, (-inf, 5L), (5L, +inf)"))
    +    assert(domains("id <=> NULL") == Seq("id: NULL"))
    +    assert(domains("NOT (id <=> NULL)") == Seq("id: ANY"))
    +    assert(domains("id IS NULL") == Seq("id: NULL"))
    +    assert(domains("id IS NOT NULL") == Seq("id: ANY"))
    +    assert(domains("id IN (3, 1, 2, 3)") == Seq("id: 1L, 2L, 3L"))
    +    assert(domains("id NOT IN (1, 3)") == Seq("id: (-inf, 1L), (1L, 3L), (3L, +inf)"))
    +    // Comparisons with null are null: so is NOT (x IN (..., NULL)), which matches no row.
    +    assert(domains("id = NULL") == Seq("id: NONE"))
    +    assert(domains("NOT (id = NULL)") == Seq("id: NONE"))
    +    assert(domains("id IN (1, NULL)") == Seq("id: 1L"))
    +    assert(domains("NOT (id IN (1, NULL))") == Seq("id: NONE"))
    +    // x IN (), which only the DataFrame API builds, is never true: it is false, and null for null
    +    // with spark.sql.legacy.nullInEmptyListBehavior. So NOT (x IN ()) constrains no column.
    +    assert(domains(col("id").isin()) == Seq("id: NONE"))
    +    assert(domains(not(col("id").isin())).isEmpty)
    +    assert(domains(not(col("id").isInCollection(Nil)) && col("id") > 5) == Seq("id: (5L, +inf)"))
    +    assert(domains("id = 1 AND id = 2") == Seq("id: NONE"))
    +    // The domains of all the predicates, which are combined with AND, at most one per column.
    +    assert(domains("id > 5 AND i = 1 AND id < 8") == Seq("id: (5L, 8L)", "i: 1"))
    +    assert(domains("true").isEmpty)
    +    assert(ColumnDomains.derive(predicates("false", schema), schema).domains.isEmpty)
    +  }
    +
    +  test("AND, OR and NOT") {
    +    assert(domains("id > 5 OR id < 0") == Seq("id: (-inf, 0L), (5L, +inf)"))
    +    assert(domains("id > 5 OR id > 3") == Seq("id: (3L, +inf)"))
    +    assert(domains("id >= 3 OR id = 3 OR id < 1") == Seq("id: (-inf, 1L), [3L, +inf)"))
    +    // [1, 2) and [2, 3] touch, and so do (-inf, 5) and [5, +inf), which then constrain id to not
    +    // be null only.
    +    assert(domains("(id >= 1 AND id < 2) OR (id >= 2 AND id <= 3)") == Seq("id: [1L, 3L]"))
    +    assert(domains("id < 5 OR id >= 5") == Seq("id: ANY"))
    +    assert(domains("id < 5 OR id >= 5 OR id IS NULL").isEmpty)
    +    // A column that only one side of OR constrains can have any value in the rows of the other.
    +    assert(domains("id > 5 OR i > 5").isEmpty)
    +    assert(domains("id > 5 AND (i > 1 OR id < 3)") == Seq("id: (5L, +inf)"))
    +    assert(domains("(id > 5 AND i = 1) OR (id < 0 AND i = 2)") ==
    +      Seq("id: (-inf, 0L), (5L, +inf)", "i: 1, 2"))
    +    // A side that matches no row does not widen the other.
    +    assert(domains("id = NULL OR i > 5") == Seq("i: (5, +inf)"))
    +    assert(domains("NOT (id > 5 OR i IS NULL)") == Seq("id: (-inf, 5L]", "i: ANY"))
    +    assert(domains("NOT (id > 5 AND i < 2)").isEmpty)
    +    assert(domains("NOT NOT (id > 5)") == Seq("id: (5L, +inf)"))
    +    // Predicates on other expressions constrain no column.
    +    assert(domains("id + 1 > 5").isEmpty)
    +    assert(domains("id = i").isEmpty)
    +    assert(domains("id + 1 > 5 AND id < 3") == Seq("id: (-inf, 3L)"))
    +    assert(domains("NOT (id + 1 > 5) AND id < 3") == Seq("id: (-inf, 3L)"))
    +  }
    +
    +  test("NaN and -0.0") {
    +    // NaN is equal to NaN and greater than any other value, including positive infinity.
    +    assert(domains("d > 1.0") == Seq("d: NaN, (1.0D, +inf)"))
    +    assert(domains("d < 1.0") == Seq("d: (-inf, 1.0D)"))
    +    assert(domains("d <> 1.0") == Seq("d: NaN, (-inf, 1.0D), (1.0D, +inf)"))
    +    assert(domains("NOT (d < 1.0)") == Seq("d: NaN, [1.0D, +inf)"))
    +    assert(domains("d > CAST('Infinity' AS DOUBLE)") ==
    +      Seq("d: NaN, (CAST('Infinity' AS DOUBLE), +inf)"))
    +    assert(domains("d = CAST('NaN' AS DOUBLE)") == Seq("d: NaN"))
    +    assert(domains("d <> CAST('NaN' AS DOUBLE)") == Seq("d: ANY"))
    +    assert(domains("d > CAST('NaN' AS DOUBLE)") == Seq("d: NONE"))
    +    assert(domains("d >= CAST('NaN' AS DOUBLE)") == Seq("d: NaN"))
    +    assert(domains("d < CAST('NaN' AS DOUBLE)") == Seq("d: ANY"))
    +    assert(domains("d <= CAST('NaN' AS DOUBLE)") == Seq("d: NaN, ANY"))
    +    assert(domains("d IN (1.0, CAST('NaN' AS DOUBLE))") == Seq("d: NaN, 1.0D"))
    +    assert(domains("d NOT IN (1.0)") == Seq("d: NaN, (-inf, 1.0D), (1.0D, +inf)"))
    +    assert(domains("d IS NOT NULL") == Seq("d: NaN, ANY"))
    +    // -0.0 is equal to 0.0, which a data source may order after -0.0.
    +    assert(domains("d = -0.0") == Seq("d: 0.0D"))

    Nit (P3): In SQL, -0.0 is a decimal literal, and a decimal zero has no sign: literals.sql.out records select -0.0 as decimal(1,1) with the value 0.0. So both filters here reach ColumnDomains with +0.0 and pass whether or not normalize runs. The property check's -0.0D cases do carry a negative zero, but they only go through ColumnDomain.contains, whose ordering treats -0.0 as equal to 0.0, and no native test filters on -0.0. The derivation itself is right. But if the normalization regressed, PushedDomains and the bounds that libraries get would show -0.0, and every test would still pass.

    A double literal and a cast from a string carry the sign, and the expected strings stay the same:

        assert(domains("d = -0.0D") == Seq("d: 0.0D"))
        assert(domains("f > CAST('-0.0' AS FLOAT)") == Seq("f: NaN, (CAST('0.0' AS FLOAT), +inf)"))
    

    Verification:

  • Regression: With the -0.0 normalization removed, the domain derived from a negative-zero double or float literal shows -0.0 and the assertion fails. With the normalization in place, the domain shows 0.0 and the assertion passes.

  • Behavior: Equality and range filters that compare a double or float column with negative zero derive bounds of 0.0, and the NaN flag of each domain is the same as for positive zero.
  • spark-test spark-test commented on code on Oct 30, 2026 16:07 UTC
    Code Review
    sql/core/src/test/resources/native-datasource/test_native_datasource.cc:1
    @@ -1075,6 +1083,108 @@ int pruneColumns(void* handle, const char* const* columns, int64_t count, bool*
       });
     }
     
    +bool boolAt(const ArrowArray* array, int64_t i) {
    +  int64_t bit = array->offset + i;
    +  return (static_cast<const uint8_t*>(array->buffers[1])[bit / 8] >> (bit % 8)) & 1;
    +}
    +
    +// Formats the ranges of a domain, such as "[1,5) (7,+inf)", after checking their schema.
    +std::string formatRanges(const SparkDsDomain* domain, const std::string& format) {
    +  const ArrowSchema* schema = domain->ranges_schema;
    +  const ArrowArray* array = domain->ranges;
    +  if (schema == nullptr || std::string(schema->format) != "+s" || schema->n_children != 4 ||
    +      array->n_children != 4) {
    +    throw std::runtime_error("the ranges are not a struct array of 4 fields");
    +  }
    +  const char* names[] = {"low", "high", "low_inclusive", "high_inclusive"};
    +  for (int i = 0; i < 4; i++) {
    +    std::string expected = i < 2 ? format : "b";
    +    if (std::string(schema->children[i]->name) != names[i] ||
    +        (!expected.empty() && std::string(schema->children[i]->format) != expected)) {
    +      throw std::runtime_error(std::string("unexpected field ") + schema->children[i]->name +
    +                               " of format " + schema->children[i]->format);
    +    }
    +  }
    +  std::string ranges;
    +  for (int64_t r = 0; r < array->length; r++) {
    +    bool low_inclusive = boolAt(array->children[2], r);
    +    bool high_inclusive = boolAt(array->children[3], r);
    +    std::string low = isValid(array->children[0], r)
    +                          ? formatValue(schema->children[0], array->children[0], r) : "-inf";
    +    std::string high = isValid(array->children[1], r)
    +                           ? formatValue(schema->children[1], array->children[1], r) : "+inf";
    +    ranges += std::string(r > 0 ? " " : "") + (low_inclusive ? "[" : "(") + low + "," + high +
    +              (high_inclusive ? "]" : ")");
    +  }
    +  return ranges;
    +}
    +
    +// The ids [lo, hi) that the domain of id has, as "lo,hi;lo,hi".
    +std::string idRanges(const SparkDsDomain* domain) {
    +  if (domain->ranges == nullptr) return std::to_string(INT64_MIN) + "," + std::to_string(INT64_MAX);
    +  const ArrowArray* array = domain->ranges;
    +  std::string result;
    +  for (int64_t r = 0; r < array->length; r++) {
    +    const ArrowArray* low = array->children[0];
    +    const ArrowArray* high = array->children[1];
    +    int64_t lo = INT64_MIN;
    +    int64_t hi = INT64_MAX;
    +    if (isValid(low, r)) {
    +      lo = static_cast<const int64_t*>(low->buffers[1])[low->offset + r];
    +      if (!boolAt(array->children[2], r) && lo < INT64_MAX) lo++;
    +    }
    +    if (isValid(high, r)) {
    +      hi = static_cast<const int64_t*>(high->buffers[1])[high->offset + r];
    +      if (boolAt(array->children[3], r) && hi < INT64_MAX) hi++;
    +    }
    +    result += (result.empty() ? "" : ";") + std::to_string(lo) + "," + std::to_string(hi);
    +  }
    +  return result;
    +}
    +
    +int pushDomains(void* handle, const SparkDsDomain* const* domains, int64_t count, bool* used) {

    Nit (P3): NativeArrow.exportDomains must release the ranges it exports for this call unless the library moved them, after a successful call and after a failing one. No test would notice if it stopped doing so, or if NativeLibrary.pushDomains stopped checking the status. This function never fails on request and never moves the ranges. report the errors of native code has no push_domains case, and no test reads the Arrow allocator.

    push_limit and prune_columns have no failure injection either, but they only pass an int and strings. push_domains is the first push step that hands the library Arrow memory, and that memory grows with the filters, such as one range for each value of an IN list. A leak would grow driver off-heap memory on every filtered native scan, and the native tests would not show it.

    A maybeFail step for push_domains, a case for it in report the errors of native code, and an allocator check around a filtered scan would cover both, as InProcessPythonRuntimeSuite does for a call that fails.

    Verification:

  • Regression: Injecting a push_domains failure makes the query fail with NATIVE_DATA_SOURCE_ERROR carrying the library's message, and the test fails if the status of push_domains is ignored.

  • Regression: The Arrow allocator's memory returns to its level from before the query once domains have been pushed, on both the success and the failure path, so leaking the exported ranges fails the test.
  • spark-test spark-test commented on Oct 30, 2026 16:07 UTC
    Reviewer

    Review summary

    All six findings of the previous review are fixed in daba613. NOT (x IN ()) now constrains no column. Fields of structs only get domains without null, and the header and guide say why. intersectRanges sweeps indexed copies, and a 100,000-value test guards it. The tests now observe a lost post-scan filter, null-allowing and multi-range domains, and the collation exclusion at the library boundary. The null-safe equality comment has the corrected wording.

    This round found three small test issues. None of them changes what a query returns:

  • A ColumnDomainsSuite comment says that NOT (x IN (..., NULL)) is null, but it is false when x is in the list.

  • The -0.0 assertions write -0.0, which SQL parses as a decimal zero without a sign, so they never exercise the normalization they describe.

  • No test fails push_domains or checks that Spark releases the Arrow ranges it exports for it.
  • The release-target question from the previous review is still open. It follows below, with one more consequence.

    Findings

    3 total: 0 P0, 0 P1, 0 P2, 3 P3.

    Nit (P3)

  • A test comment says that NOT (x IN (..., NULL)) is null — sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnDomainsSuite.scala:90 — see inline.

  • The -0.0 assertions never pass a negative zero to the derivation — sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnDomainsSuite.scala:151 — see inline.

  • No test fails push_domains or checks that its Arrow ranges are released — sql/core/src/test/resources/native-datasource/test_native_datasource.cc:1145 — see inline.
  • Re-review status

    Prior AI findings: 6 addressed, 0 still present; additional unresolved findings in this review: 3.

    New attribution: 0 newly introduced, 3 late catch, 0 previously raised, 0 unattributed.

    Remaining prior AI findings

    No prior AI findings remain.

    PR description suggestions

  • The title still uses the SPARK-XXXXX placeholder, while the body cites SPARK-60101 for this change.
  • Decision challenges

    Release line of push_domains: 4.4.0, or master-only 5.0.0 with a v1 table slot that branch-4.x could reuse?

    The previous review asked which release first ships this, and the question is still open: the config still declares 5.0.0, and the description still says that a library built against the 4.4 header has a smaller table. This review adds what a master-only target would mean for the function table.

    Verified in the checkout:

  • master is 5.0.0-SNAPSHOT, and origin/branch-4.x is 4.4.0-SNAPSHOT. The spark_datasource.h of branch-4.x is identical to the merge base, so its SparkDsLibrary ends at close_data_writer. The sibling spark.sql.dataSource.native.paths declares 4.4.0.

  • push_domains takes the slot after close_data_writer, and SPARK_DS_ABI_VERSION stays 1. NativeLibrary binds each function at its fixed offset whenever it fits in the size of the table (NativeLibrary.java:231).

  • The Compatibility section of the guide promises that, within a version, functions are only appended, and that a library built against an earlier header keeps working with later releases. It also promises version 1 in all the releases of Spark 4 from 4.4.0.
  • Suppose push_domains ships only from 5.0.0. Then the next function appended to the v1 table on branch-4.x takes the same offset. Spark 5.0 would call that function of a library built against the 4.x header as push_domains. A 4.x release would call the push_domains of a library built against the 5.0 header with the other function's signature. Neither the size of the table nor the ABI version tells the two apart.

    The code is consistent within each line, so this depends only on the release plan, which the code cannot settle:

  • If this also goes to branch-4.x, the config should declare 4.4.0, and the description's statement about the 4.4 header changes.

  • If it is master-only, could you say why in the description? The versioning guidance keeps master-only for breaking changes and dependency upgrades. Could you also say how version 1 stays aligned across the two lines? For example, branch-4.x could reserve or backport the push_domains slot before any other addition there.
  • Generated by Omnigent on Databricks
    <!-- SPARK_OSS_REVIEW_REQUEST 34701305274 -->

    <!-- SPARK_DEV_REVIEW_CODE {"findings":[{"delivery":"inline","fingerprint":"9ad3755bd83976ac0b42","id":"pass-b:test-comment-not-in-with-null"},{"delivery":"inline","fingerprint":"bf857a1c4a3eb8f94013","id":"pass-b:test-negative-zero-never-reaches-derivation"},{"delivery":"inline","fingerprint":"2d7b710de355234bb63f","id":"pass-b:test-push-domains-error-and-release-paths-untested"}],"head_sha":"87fe709f8826e509ede33f1bcf1a9f92c8e7071c","verdict_sha256":"e750570905ff507d07c3f0ac46c7f88d6fb28e26340ed1fb73a19f361cfcd9d2"} -->

    HyukjinKwon HyukjinKwon commented on code on Nov 03, 2026 23:58 UTC
    Code Review
    sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnDomainsSuite.scala:1
    @@ -0,0 +1,381 @@
    +/*
    + * 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.
    + */
    +package org.apache.spark.sql.execution.datasources.v2.columnar
    +
    +import java.sql.Date
    +
    +import scala.jdk.CollectionConverters._
    +import scala.util.Random
    +
    +import org.scalatest.concurrent.TimeLimits
    +import org.scalatest.time.SpanSugar._
    +
    +import org.apache.spark.sql.{Column, QueryTest, Row}
    +import org.apache.spark.sql.catalyst.{CatalystTypeConverters, InternalRow}
    +import org.apache.spark.sql.catalyst.expressions.{Literal, PredicateHelper}
    +import org.apache.spark.sql.catalyst.plans.logical.Filter
    +import org.apache.spark.sql.connector.expressions.{Expression => V2Expression, FieldReference, LiteralValue}
    +import org.apache.spark.sql.connector.expressions.filter.Predicate
    +import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Strategy
    +import org.apache.spark.sql.functions.{col, expr, not}
    +import org.apache.spark.sql.internal.SQLConf
    +import org.apache.spark.sql.test.SharedSparkSession
    +import org.apache.spark.sql.types._
    +import org.apache.spark.unsafe.types.UTF8String
    +
    +/** Tests how [[ColumnDomains]] derives the domains of columns from the predicates of a query. */
    +class ColumnDomainsSuite extends QueryTest with SharedSparkSession with PredicateHelper
    +  with TimeLimits {
    +
    +  private val schema = StructType.fromDDL("id BIGINT, i INT, d DOUBLE, f FLOAT, s STRING, " +
    +    "b BINARY, flag BOOLEAN, dt DATE, ts TIMESTAMP, dec DECIMAL(10, 2), " +
    +    "st STRUCT<x: INT, y: STRING>, arr ARRAY<INT>, c STRING COLLATE UTF8_LCASE")
    +
    +  private def char(codePoint: Int): String = new String(Character.toChars(codePoint))
    +
    +  /**
    +   * The predicates that Data Source V2 pushes for the filter, as in the analyzed plan with the
    +   * constants folded: the optimizer would rewrite some of them, such as NOT (x > 1).
    +   */
    +  private def predicates(filter: String, schema: StructType): Seq[Predicate] = {
    +    predicates(expr(filter), schema)
    +  }
    +
    +  private def predicates(filter: Column, schema: StructType): Seq[Predicate] = {
    +    val df = spark.createDataFrame(Seq.empty[Row].asJava, schema)
    +    val condition = df.where(filter).queryExecution.analyzed.collectFirst {
    +      case Filter(condition, _) => condition
    +    }.get
    +    splitConjunctivePredicates(condition.transformUp {
    +      case e if e.foldable && !e.isInstanceOf[Literal] => Literal.create(e.eval(), e.dataType)
    +    }).flatMap(DataSourceV2Strategy.translateFilterV2)
    +  }
    +
    +  private def domains(filter: String): Seq[String] = domains(expr(filter))
    +
    +  private def domains(filter: Column): Seq[String] = {
    +    ColumnDomains.derive(predicates(filter, schema), schema).domains.map(_.toString)
    +  }
    +
    +  test("comparisons, IN and null checks") {
    +    assert(domains("id > 5") == Seq("id: (5L, +inf)"))
    +    assert(domains("5 < id") == Seq("id: (5L, +inf)"))
    +    assert(domains("id >= 5 AND id < 10") == Seq("id: [5L, 10L)"))
    +    assert(domains("id <= 5") == Seq("id: (-inf, 5L]"))
    +    assert(domains("id = 5") == Seq("id: 5L"))
    +    assert(domains("id <> 5") == Seq("id: (-inf, 5L), (5L, +inf)"))
    +    assert(domains("id <=> 5") == Seq("id: 5L"))
    +    // x <=> v is false, not null, when x is null, so NOT (x <=> v) is true for null.
    +    assert(domains("NOT (id <=> 5)") == Seq("id: NULL, (-inf, 5L), (5L, +inf)"))
    +    assert(domains("id <=> NULL") == Seq("id: NULL"))
    +    assert(domains("NOT (id <=> NULL)") == Seq("id: ANY"))
    +    assert(domains("id IS NULL") == Seq("id: NULL"))
    +    assert(domains("id IS NOT NULL") == Seq("id: ANY"))
    +    assert(domains("id IN (3, 1, 2, 3)") == Seq("id: 1L, 2L, 3L"))
    +    assert(domains("id NOT IN (1, 3)") == Seq("id: (-inf, 1L), (1L, 3L), (3L, +inf)"))
    +    // Comparisons with null are null: so is NOT (x IN (..., NULL)), which matches no row.

    Done in 9fc11f6, as suggested.

    HyukjinKwon HyukjinKwon commented on code on Nov 03, 2026 23:59 UTC
    Code Review
    sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnDomainsSuite.scala:1
    @@ -0,0 +1,381 @@
    +/*
    + * 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.
    + */
    +package org.apache.spark.sql.execution.datasources.v2.columnar
    +
    +import java.sql.Date
    +
    +import scala.jdk.CollectionConverters._
    +import scala.util.Random
    +
    +import org.scalatest.concurrent.TimeLimits
    +import org.scalatest.time.SpanSugar._
    +
    +import org.apache.spark.sql.{Column, QueryTest, Row}
    +import org.apache.spark.sql.catalyst.{CatalystTypeConverters, InternalRow}
    +import org.apache.spark.sql.catalyst.expressions.{Literal, PredicateHelper}
    +import org.apache.spark.sql.catalyst.plans.logical.Filter
    +import org.apache.spark.sql.connector.expressions.{Expression => V2Expression, FieldReference, LiteralValue}
    +import org.apache.spark.sql.connector.expressions.filter.Predicate
    +import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Strategy
    +import org.apache.spark.sql.functions.{col, expr, not}
    +import org.apache.spark.sql.internal.SQLConf
    +import org.apache.spark.sql.test.SharedSparkSession
    +import org.apache.spark.sql.types._
    +import org.apache.spark.unsafe.types.UTF8String
    +
    +/** Tests how [[ColumnDomains]] derives the domains of columns from the predicates of a query. */
    +class ColumnDomainsSuite extends QueryTest with SharedSparkSession with PredicateHelper
    +  with TimeLimits {
    +
    +  private val schema = StructType.fromDDL("id BIGINT, i INT, d DOUBLE, f FLOAT, s STRING, " +
    +    "b BINARY, flag BOOLEAN, dt DATE, ts TIMESTAMP, dec DECIMAL(10, 2), " +
    +    "st STRUCT<x: INT, y: STRING>, arr ARRAY<INT>, c STRING COLLATE UTF8_LCASE")
    +
    +  private def char(codePoint: Int): String = new String(Character.toChars(codePoint))
    +
    +  /**
    +   * The predicates that Data Source V2 pushes for the filter, as in the analyzed plan with the
    +   * constants folded: the optimizer would rewrite some of them, such as NOT (x > 1).
    +   */
    +  private def predicates(filter: String, schema: StructType): Seq[Predicate] = {
    +    predicates(expr(filter), schema)
    +  }
    +
    +  private def predicates(filter: Column, schema: StructType): Seq[Predicate] = {
    +    val df = spark.createDataFrame(Seq.empty[Row].asJava, schema)
    +    val condition = df.where(filter).queryExecution.analyzed.collectFirst {
    +      case Filter(condition, _) => condition
    +    }.get
    +    splitConjunctivePredicates(condition.transformUp {
    +      case e if e.foldable && !e.isInstanceOf[Literal] => Literal.create(e.eval(), e.dataType)
    +    }).flatMap(DataSourceV2Strategy.translateFilterV2)
    +  }
    +
    +  private def domains(filter: String): Seq[String] = domains(expr(filter))
    +
    +  private def domains(filter: Column): Seq[String] = {
    +    ColumnDomains.derive(predicates(filter, schema), schema).domains.map(_.toString)
    +  }
    +
    +  test("comparisons, IN and null checks") {
    +    assert(domains("id > 5") == Seq("id: (5L, +inf)"))
    +    assert(domains("5 < id") == Seq("id: (5L, +inf)"))
    +    assert(domains("id >= 5 AND id < 10") == Seq("id: [5L, 10L)"))
    +    assert(domains("id <= 5") == Seq("id: (-inf, 5L]"))
    +    assert(domains("id = 5") == Seq("id: 5L"))
    +    assert(domains("id <> 5") == Seq("id: (-inf, 5L), (5L, +inf)"))
    +    assert(domains("id <=> 5") == Seq("id: 5L"))
    +    // x <=> v is false, not null, when x is null, so NOT (x <=> v) is true for null.
    +    assert(domains("NOT (id <=> 5)") == Seq("id: NULL, (-inf, 5L), (5L, +inf)"))
    +    assert(domains("id <=> NULL") == Seq("id: NULL"))
    +    assert(domains("NOT (id <=> NULL)") == Seq("id: ANY"))
    +    assert(domains("id IS NULL") == Seq("id: NULL"))
    +    assert(domains("id IS NOT NULL") == Seq("id: ANY"))
    +    assert(domains("id IN (3, 1, 2, 3)") == Seq("id: 1L, 2L, 3L"))
    +    assert(domains("id NOT IN (1, 3)") == Seq("id: (-inf, 1L), (1L, 3L), (3L, +inf)"))
    +    // Comparisons with null are null: so is NOT (x IN (..., NULL)), which matches no row.
    +    assert(domains("id = NULL") == Seq("id: NONE"))
    +    assert(domains("NOT (id = NULL)") == Seq("id: NONE"))
    +    assert(domains("id IN (1, NULL)") == Seq("id: 1L"))
    +    assert(domains("NOT (id IN (1, NULL))") == Seq("id: NONE"))
    +    // x IN (), which only the DataFrame API builds, is never true: it is false, and null for null
    +    // with spark.sql.legacy.nullInEmptyListBehavior. So NOT (x IN ()) constrains no column.
    +    assert(domains(col("id").isin()) == Seq("id: NONE"))
    +    assert(domains(not(col("id").isin())).isEmpty)
    +    assert(domains(not(col("id").isInCollection(Nil)) && col("id") > 5) == Seq("id: (5L, +inf)"))
    +    assert(domains("id = 1 AND id = 2") == Seq("id: NONE"))
    +    // The domains of all the predicates, which are combined with AND, at most one per column.
    +    assert(domains("id > 5 AND i = 1 AND id < 8") == Seq("id: (5L, 8L)", "i: 1"))
    +    assert(domains("true").isEmpty)
    +    assert(ColumnDomains.derive(predicates("false", schema), schema).domains.isEmpty)
    +  }
    +
    +  test("AND, OR and NOT") {
    +    assert(domains("id > 5 OR id < 0") == Seq("id: (-inf, 0L), (5L, +inf)"))
    +    assert(domains("id > 5 OR id > 3") == Seq("id: (3L, +inf)"))
    +    assert(domains("id >= 3 OR id = 3 OR id < 1") == Seq("id: (-inf, 1L), [3L, +inf)"))
    +    // [1, 2) and [2, 3] touch, and so do (-inf, 5) and [5, +inf), which then constrain id to not
    +    // be null only.
    +    assert(domains("(id >= 1 AND id < 2) OR (id >= 2 AND id <= 3)") == Seq("id: [1L, 3L]"))
    +    assert(domains("id < 5 OR id >= 5") == Seq("id: ANY"))
    +    assert(domains("id < 5 OR id >= 5 OR id IS NULL").isEmpty)
    +    // A column that only one side of OR constrains can have any value in the rows of the other.
    +    assert(domains("id > 5 OR i > 5").isEmpty)
    +    assert(domains("id > 5 AND (i > 1 OR id < 3)") == Seq("id: (5L, +inf)"))
    +    assert(domains("(id > 5 AND i = 1) OR (id < 0 AND i = 2)") ==
    +      Seq("id: (-inf, 0L), (5L, +inf)", "i: 1, 2"))
    +    // A side that matches no row does not widen the other.
    +    assert(domains("id = NULL OR i > 5") == Seq("i: (5, +inf)"))
    +    assert(domains("NOT (id > 5 OR i IS NULL)") == Seq("id: (-inf, 5L]", "i: ANY"))
    +    assert(domains("NOT (id > 5 AND i < 2)").isEmpty)
    +    assert(domains("NOT NOT (id > 5)") == Seq("id: (5L, +inf)"))
    +    // Predicates on other expressions constrain no column.
    +    assert(domains("id + 1 > 5").isEmpty)
    +    assert(domains("id = i").isEmpty)
    +    assert(domains("id + 1 > 5 AND id < 3") == Seq("id: (-inf, 3L)"))
    +    assert(domains("NOT (id + 1 > 5) AND id < 3") == Seq("id: (-inf, 3L)"))
    +  }
    +
    +  test("NaN and -0.0") {
    +    // NaN is equal to NaN and greater than any other value, including positive infinity.
    +    assert(domains("d > 1.0") == Seq("d: NaN, (1.0D, +inf)"))
    +    assert(domains("d < 1.0") == Seq("d: (-inf, 1.0D)"))
    +    assert(domains("d <> 1.0") == Seq("d: NaN, (-inf, 1.0D), (1.0D, +inf)"))
    +    assert(domains("NOT (d < 1.0)") == Seq("d: NaN, [1.0D, +inf)"))
    +    assert(domains("d > CAST('Infinity' AS DOUBLE)") ==
    +      Seq("d: NaN, (CAST('Infinity' AS DOUBLE), +inf)"))
    +    assert(domains("d = CAST('NaN' AS DOUBLE)") == Seq("d: NaN"))
    +    assert(domains("d <> CAST('NaN' AS DOUBLE)") == Seq("d: ANY"))
    +    assert(domains("d > CAST('NaN' AS DOUBLE)") == Seq("d: NONE"))
    +    assert(domains("d >= CAST('NaN' AS DOUBLE)") == Seq("d: NaN"))
    +    assert(domains("d < CAST('NaN' AS DOUBLE)") == Seq("d: ANY"))
    +    assert(domains("d <= CAST('NaN' AS DOUBLE)") == Seq("d: NaN, ANY"))
    +    assert(domains("d IN (1.0, CAST('NaN' AS DOUBLE))") == Seq("d: NaN, 1.0D"))
    +    assert(domains("d NOT IN (1.0)") == Seq("d: NaN, (-inf, 1.0D), (1.0D, +inf)"))
    +    assert(domains("d IS NOT NULL") == Seq("d: NaN, ANY"))
    +    // -0.0 is equal to 0.0, which a data source may order after -0.0.
    +    assert(domains("d = -0.0") == Seq("d: 0.0D"))

    Done in 9fc11f6: the cases now use d = -0.0D and f > CAST('-0.0' AS FLOAT), with the same expected strings, and a comment says why. With normalize removed, the double case now fails with List("d: -0.0D") did not equal List("d: 0.0D").

    HyukjinKwon HyukjinKwon commented on code on Nov 03, 2026 23:59 UTC
    Code Review
    sql/core/src/test/resources/native-datasource/test_native_datasource.cc:1
    @@ -1075,6 +1083,108 @@ int pruneColumns(void* handle, const char* const* columns, int64_t count, bool*
       });
     }
     
    +bool boolAt(const ArrowArray* array, int64_t i) {
    +  int64_t bit = array->offset + i;
    +  return (static_cast<const uint8_t*>(array->buffers[1])[bit / 8] >> (bit % 8)) & 1;
    +}
    +
    +// Formats the ranges of a domain, such as "[1,5) (7,+inf)", after checking their schema.
    +std::string formatRanges(const SparkDsDomain* domain, const std::string& format) {
    +  const ArrowSchema* schema = domain->ranges_schema;
    +  const ArrowArray* array = domain->ranges;
    +  if (schema == nullptr || std::string(schema->format) != "+s" || schema->n_children != 4 ||
    +      array->n_children != 4) {
    +    throw std::runtime_error("the ranges are not a struct array of 4 fields");
    +  }
    +  const char* names[] = {"low", "high", "low_inclusive", "high_inclusive"};
    +  for (int i = 0; i < 4; i++) {
    +    std::string expected = i < 2 ? format : "b";
    +    if (std::string(schema->children[i]->name) != names[i] ||
    +        (!expected.empty() && std::string(schema->children[i]->format) != expected)) {
    +      throw std::runtime_error(std::string("unexpected field ") + schema->children[i]->name +
    +                               " of format " + schema->children[i]->format);
    +    }
    +  }
    +  std::string ranges;
    +  for (int64_t r = 0; r < array->length; r++) {
    +    bool low_inclusive = boolAt(array->children[2], r);
    +    bool high_inclusive = boolAt(array->children[3], r);
    +    std::string low = isValid(array->children[0], r)
    +                          ? formatValue(schema->children[0], array->children[0], r) : "-inf";
    +    std::string high = isValid(array->children[1], r)
    +                           ? formatValue(schema->children[1], array->children[1], r) : "+inf";
    +    ranges += std::string(r > 0 ? " " : "") + (low_inclusive ? "[" : "(") + low + "," + high +
    +              (high_inclusive ? "]" : ")");
    +  }
    +  return ranges;
    +}
    +
    +// The ids [lo, hi) that the domain of id has, as "lo,hi;lo,hi".
    +std::string idRanges(const SparkDsDomain* domain) {
    +  if (domain->ranges == nullptr) return std::to_string(INT64_MIN) + "," + std::to_string(INT64_MAX);
    +  const ArrowArray* array = domain->ranges;
    +  std::string result;
    +  for (int64_t r = 0; r < array->length; r++) {
    +    const ArrowArray* low = array->children[0];
    +    const ArrowArray* high = array->children[1];
    +    int64_t lo = INT64_MIN;
    +    int64_t hi = INT64_MAX;
    +    if (isValid(low, r)) {
    +      lo = static_cast<const int64_t*>(low->buffers[1])[low->offset + r];
    +      if (!boolAt(array->children[2], r) && lo < INT64_MAX) lo++;
    +    }
    +    if (isValid(high, r)) {
    +      hi = static_cast<const int64_t*>(high->buffers[1])[high->offset + r];
    +      if (boolAt(array->children[3], r) && hi < INT64_MAX) hi++;
    +    }
    +    result += (result.empty() ? "" : ";") + std::to_string(lo) + "," + std::to_string(hi);
    +  }
    +  return result;
    +}
    +
    +int pushDomains(void* handle, const SparkDsDomain* const* domains, int64_t count, bool* used) {

    Done in 9fc11f6: the test library fails push_domains with the option fail set to push_domains. "report the errors of native code" checks that the query fails with NATIVE_DATA_SOURCE_ERROR and the message of the library. It also checks that ArrowUtils.rootAllocator gets back all its memory after the failure, and after a scan with an IN filter whose domains the library takes. With the release of the ranges removed from NativeArrow.exportDomains, the check fails with 68202 bytes still allocated.

    spark-test spark-test commented on code on Nov 04, 2026 15:24 UTC
    Code Review
    sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnarTable.scala:1
    @@ -83,6 +85,7 @@ class ColumnarScanBuilder(
         schema: StructType,
         createDataSource: () => ColumnarDataSource)
       extends ScanBuilder
    +  with SupportsPushDownV2Filters

    Non-blocking (P2): Because this mixes in SupportsPushDownV2Filters unconditionally, every filtered native batch scan now takes the V2 branch of PushDownUtils.pushFilters. That branch rebuilds the conjuncts that Spark evaluates after the scan as the translatable deterministic ones, then the untranslatable ones, then the nondeterministic ones (prioritizeFilters). On the base branch this builder implemented no filter interface, so pushFilters kept the conjuncts in their order. FilterExec evaluates them in that order and drops a row at the first false one.

    Take rand() < 0.01 AND lower(name) LIKE '%n1%'. LikeSimplification turns the LIKE into Contains(Lower(name), 'n1'), which V2 translates. So LOWER and CONTAINS now run on every scanned row instead of on the 1% of rows that rand() keeps, and the seeded rand() now runs only on their survivors, so it samples other rows. array_contains(tags, 'x') AND upper(name) = 'X' behaves the same, since array_contains is not translated. Such expensive conjuncts derive no domain, so skipping offsets the cost only when another conjunct gives the library a domain that it uses.

    Returning every predicate from pushPredicates does not keep the order. With spark.sql.dataSource.native.filterPushdown.enabled=false the builder still implements the interface, so turning the pushdown off does not restore the base branch's plan either. The reordering is Spark's heuristic for other V2 sources and helps the opposite shape, but here it also applies to filters that gain nothing from the pushdown.

    Recommended change: Keep the written conjunct order of the post-scan filter for native scans. Add an internal capability, declared by the columnar scan builder, meaning that every pushed predicate is also returned for evaluation after the scan; when a builder has it, the filter pushdown helper uses the conjuncts in their written order, nondeterministic ones included, as the post-scan filters instead of reordering them. Other Data Source V2 builders keep the current order.

    Why this works: The native builder still receives the translated deterministic predicates and derives domains from them, but the post-scan filter is the original conjunct list, so the base branch's evaluation order, and with it the work FilterExec does for each conjunct, stays the same whether or not domains are pushed and whatever the flag is set to.

    Scope: Post-scan filter construction for native batch scans

    Compatibility: Every pushed predicate is still evaluated after the scan, and the domains passed to libraries are unchanged.

    Risks: Native scans that push domains no longer get the translatable-first order either, so a filter that writes an expensive untranslatable conjunct first keeps running it first, as on the base branch; this returns to the base branch's behavior rather than adding a regression, and it is limited to native scans.

    Constraints: The capability stays internal, and only the columnar scan builder declares it, so the post-scan order of other V2 sources does not change. Nondeterministic conjuncts are still never pushed to the builder.

    Exclusions:

  • The PushedFilters entry with an empty list stays in the scan metadata when nothing is pushed, since formatted explain already hides it.
  • Success: For a native batch scan, the post-scan Filter keeps its conjuncts in the order they had above the scan, nondeterministic ones included, except that the conjuncts with subqueries still come last, as on the base branch, whether or not domains are pushed and whatever spark.sql.dataSource.native.filterPushdown.enabled is set to. With the flag off, the optimized plan of a native scan matches the base branch. Domains are still derived, pushed and reported as before, and results do not change. Other Data Source V2 sources keep their current post-scan order.

    Verification:

  • Regression: A native scan filtered by a selective nondeterministic conjunct written before an expensive translatable one, such as rand() < 0.01 AND lower(name) LIKE '%n1%', keeps the written conjunct order in its optimized post-scan Filter, with the flag on and off and for libraries with and without push_domains.

  • Behavior: Filters that constrain columns still push the same domains, report the same pushed filters and return the same rows.

  • Compatibility: The post-scan filter order of a Data Source V2 source with filter pushdown other than the native one is unchanged.
  • spark-test spark-test commented on code on Nov 04, 2026 15:24 UTC
    Code Review
    sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnDomains.scala:1
    @@ -0,0 +1,547 @@
    +/*
    + * 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.
    + */
    +package org.apache.spark.sql.execution.datasources.v2.columnar
    +
    +import scala.collection.mutable.ArrayBuffer
    +
    +import org.apache.spark.SparkException
    +import org.apache.spark.sql.catalyst.expressions.Literal
    +import org.apache.spark.sql.catalyst.types.PhysicalDataType
    +import org.apache.spark.sql.catalyst.util.quoteIfNeeded
    +import org.apache.spark.sql.connector.expressions.{Expression, LiteralValue, NamedReference}
    +import org.apache.spark.sql.connector.expressions.filter.Predicate
    +import org.apache.spark.sql.types._
    +import org.apache.spark.unsafe.types.UTF8String
    +
    +/**
    + * The values that a column can have in the rows that match the filters of a query: null if
    + * `nullAllowed`, NaN if `nanAllowed`, for a float or double column, and the other values in one
    + * of the `ranges`, or any of them without ranges. A data source can skip the data whose statistics
    + * show that it has no value in the domain of a column, but never a row whose values are in their
    + * domains: Spark evaluates the filters after reading anyway.
    + *
    + * @param path the index of the column in the read schema, and then the index of the field in each
    + *             struct, for a field of a struct
    + * @param name the names of the column and of its fields
    + * @param ranges sorted ranges, which neither overlap nor touch, of the values other than null and
    + *               NaN, in the internal representation of Spark. None if the column can have any of
    + *               them, and empty if it can have none.
    + */
    +case class ColumnDomain(
    +    path: Seq[Int],
    +    name: Seq[String],
    +    dataType: DataType,
    +    nullAllowed: Boolean,
    +    nanAllowed: Boolean,
    +    ranges: Option[Seq[ValueRange]]) {
    +
    +  private def ordering: Ordering[Any] = PhysicalDataType.ordering(dataType)
    +
    +  /** Whether the domain has the value, in the internal representation of Spark. */
    +  def contains(value: Any): Boolean = value match {
    +    case null => nullAllowed
    +    case f: Float if f.isNaN => nanAllowed
    +    case d: Double if d.isNaN => nanAllowed
    +    case _ => ranges.forall(_.exists(_.contains(value, ordering)))
    +  }
    +
    +  override def toString: String = {
    +    def literal(value: Any): String = Literal(value, dataType).sql
    +    val values = ranges match {
    +      case None => Seq("ANY")
    +      case Some(ranges) => ranges.map {
    +        case ValueRange(Some(low), true, Some(high), true) if ordering.equiv(low, high) =>
    +          literal(low)
    +        case range =>
    +          (if (range.lowInclusive) "[" else "(") + range.low.map(literal).getOrElse("-inf") +
    +            ", " + range.high.map(literal).getOrElse("+inf") +
    +            (if (range.highInclusive) "]" else ")")
    +      }
    +    }
    +    val special = (if (nullAllowed) Seq("NULL") else Nil) ++ (if (nanAllowed) Seq("NaN") else Nil)
    +    val all = special ++ values
    +    s"${name.map(quoteIfNeeded).mkString(".")}: ${if (all.isEmpty) "NONE" else all.mkString(", ")}"
    +  }
    +}
    +
    +/**
    + * A range of values in the internal representation of Spark: the values above `low`, or equal to
    + * it if `lowInclusive`, and below `high`, or equal to it if `highInclusive`. A bound that is None
    + * is unbounded, and is not inclusive.
    + */
    +case class ValueRange(low: Option[Any], lowInclusive: Boolean, high: Option[Any],
    +    highInclusive: Boolean) {
    +
    +  def contains(value: Any, ordering: Ordering[Any]): Boolean = {
    +    low.forall { l =>
    +      val c = ordering.compare(value, l)
    +      c > 0 || (c == 0 && lowInclusive)
    +    } && high.forall { h =>
    +      val c = ordering.compare(value, h)
    +      c < 0 || (c == 0 && highInclusive)
    +    }
    +  }
    +}
    +
    +/**
    + * The domains that a query passes to a data source, and the predicates that each of them comes
    + * from.
    + *
    + * @param domains the domains, at most one for each column, sorted by path
    + * @param columns the paths of the columns that each predicate constrains
    + */
    +case class ColumnDomains(domains: Seq[ColumnDomain], columns: Seq[Set[Seq[Int]]]) {
    +
    +  /**
    +   * Returns the predicates that constrain only the columns whose domains are used, given whether
    +   * the data source uses each domain.
    +   */
    +  def pushedPredicates(predicates: Array[Predicate], used: Seq[Boolean]): Array[Predicate] = {
    +    val usedPaths = domains.zip(used).collect { case (domain, true) => domain.path }.toSet
    +    predicates.zip(columns).collect {
    +      case (predicate, paths) if paths.nonEmpty && paths.subsetOf(usedPaths) => predicate
    +    }
    +  }
    +}
    +
    +/**
    + * Derives the domains of the columns that the predicates of a query constrain, the ones that Data
    + * Source V2 pushes to a scan, combined with AND. A domain is a superset of the values that a column
    + * has in the rows for which all the predicates are true: Spark derives it from the comparisons of
    + * a column with literals, IN, IS NULL, IS NOT NULL and STARTS_WITH, under AND, OR and NOT, with the
    + * semantics of Spark SQL. Comparisons with null are null, NaN is equal to NaN and greater than any
    + * other value, -0.0 is equal to 0.0, and strings and binary values are compared by their bytes, as
    + * unsigned bytes. A predicate that cannot be expressed this way does not constrain any column. Only
    + * the columns and the fields of structs of the types that a data source can compare get a domain:
    + * not the strings of a non-binary collation, nor arrays, maps and structs. A field of a struct only
    + * gets a domain that does not have null.
    + */
    +object ColumnDomains {
    +
    +  // A column that a predicate constrains, with its type.
    +  private case class Column(path: Seq[Int], name: Seq[String], dataType: DataType) {
    +    val ordering: Ordering[Any] = PhysicalDataType.ordering(dataType)
    +    val isFloating: Boolean = dataType == FloatType || dataType == DoubleType
    +  }
    +
    +  // The values that a column can have: see ColumnDomain.
    +  private case class Values(nullAllowed: Boolean, nanAllowed: Boolean,
    +      ranges: Option[Seq[ValueRange]])
    +
    +  private val NoValue = Values(nullAllowed = false, nanAllowed = false, Some(Nil))
    +  private val OnlyNull = Values(nullAllowed = true, nanAllowed = false, Some(Nil))
    +
    +  // The columns that the predicates constrain, with their values: a row can only make the
    +  // predicates true if each of these columns has one of the values. None when no row can.
    +  private type Constraint = Option[Map[Column, Values]]
    +  private val All: Constraint = Some(Map.empty)
    +  private val NoRow: Constraint = None
    +
    +  /** Derives the domains of the predicates for a scan of the schema. */
    +  def derive(predicates: Seq[Predicate], schema: StructType): ColumnDomains = {
    +    val constraints = predicates.map(constraint(_, negated = false, schema))
    +    val columns = constraints.map(_.map(_.keySet.map(_.path)).getOrElse(Set.empty[Seq[Int]]))
    +    val domains = constraints.foldLeft(All)(and) match {
    +      case Some(values) =>
    +        values.toSeq.collect {
    +          // A field of a struct is null in the rows where the struct, or a struct that contains it,
    +          // is null, which the statistics of its Arrow child array may not count as nulls. So a
    +          // field only gets a domain without null, which these rows never match.
    +          case (column, v) if column.path.length == 1 || !v.nullAllowed =>
    +            ColumnDomain(column.path, column.name, column.dataType, v.nullAllowed, v.nanAllowed,
    +              v.ranges)
    +        }.sortBy(_.path)(Ordering.Implicits.seqOrdering[Seq, Int])
    +      // A predicate that is always false, which Spark usually removes before it scans the data.
    +      case None => Nil
    +    }
    +    ColumnDomains(domains, columns)
    +  }
    +
    +  // The rows for which the predicate is true, or false if negated: NOT moves to the leaves.
    +  private def constraint(predicate: Predicate, negated: Boolean, schema: StructType): Constraint = {
    +    def child(i: Int): Option[Predicate] = predicate.children().lift(i).collect {
    +      case p: Predicate => p
    +    }
    +    def both(combine: (Constraint, Constraint) => Constraint, negated: Boolean): Constraint = {
    +      (child(0), child(1)) match {
    +        case (Some(left), Some(right)) =>
    +          combine(constraint(left, negated, schema), constraint(right, negated, schema))
    +        case _ => All
    +      }
    +    }
    +    predicate.name() match {
    +      case "AND" => if (negated) both(or, negated = true) else both(and, negated = false)
    +      case "OR" => if (negated) both(and, negated = true) else both(or, negated = false)
    +      case "NOT" => child(0).map(constraint(_, !negated, schema)).getOrElse(All)
    +      case "ALWAYS_TRUE" => if (negated) NoRow else All
    +      case "ALWAYS_FALSE" => if (negated) All else NoRow
    +      case _ => leaf(predicate, negated, schema).getOrElse(All)
    +    }
    +  }
    +
    +  private def leaf(
    +      predicate: Predicate,
    +      negated: Boolean,
    +      schema: StructType): Option[Constraint] = {
    +    val children = predicate.children()
    +    predicate.name() match {
    +      case "IS_NULL" | "IS_NOT_NULL" if children.length == 1 =>
    +        column(children(0), schema).map { col =>
    +          val isNull = (predicate.name() == "IS_NULL") != negated
    +          single(col, if (isNull) OnlyNull else anyValue(col))
    +        }
    +      case op @ ("=" | "<>" | "<=>" | "<" | "<=" | ">" | ">=") if children.length == 2 =>
    +        val operands = (column(children(0), schema), column(children(1), schema)) match {
    +          case (Some(col), _) => literal(children(1), col).map((col, _, op))
    +          case (_, Some(col)) => literal(children(0), col).map((col, _, flip(op)))
    +          case _ => None
    +        }
    +        operands.map { case (col, value, op) => compare(col, value, op, negated) }
    +      case "IN" if children.nonEmpty =>
    +        column(children(0), schema).flatMap { col =>
    +          val values = children.tail.map(literal(_, col))
    +          if (values.forall(_.isDefined)) Some(in(col, values.map(_.get).toSeq, negated)) else None
    +        }
    +      case "STARTS_WITH" if children.length == 2 =>
    +        column(children(0), schema).filter(_.dataType.isInstanceOf[StringType]).flatMap { col =>
    +          literal(children(1), col).map(prefix => startsWith(col, prefix, negated))
    +        }
    +      case _ => None
    +    }
    +  }
    +
    +  private def flip(op: String): String = op match {
    +    case "<" => ">"
    +    case "<=" => ">="
    +    case ">" => "<"
    +    case ">=" => "<="
    +    case other => other
    +  }
    +
    +  private def compare(column: Column, value: Any, op: String, negated: Boolean): Constraint = {
    +    // NOT (x <=> v) is true for null, unless v is null.
    +    val nullAllowed = op == "<=>" && negated && value != null
    +    if (value == null) {
    +      // A comparison with null is null, and so is its negation, but x <=> NULL is x IS NULL.
    +      if (op == "<=>") single(column, if (negated) anyValue(column) else OnlyNull)
    +      else single(column, NoValue)
    +    } else if (isNaN(value)) {
    +      // NaN is equal to NaN and greater than any other value: (NaN, other values).
    +      val (nan, others) = (op, negated) match {
    +        case ("=" | "<=>" | ">=", false) | ("<>" | "<", true) => (true, Some(Nil))
    +        case ("=" | "<=>" | ">=", true) | ("<>" | "<", false) => (false, None)
    +        case ("<=", false) | (">", true) => (true, None)
    +        case ("<=", true) | (">", false) => (false, Some(Nil))
    +        case _ => throw SparkException.internalError(s"Unexpected comparison $op.")
    +      }
    +      single(column, Values(nullAllowed, nan, others))
    +    } else {
    +      val v = normalize(value)
    +      // NaN is greater than v, and not equal to it.
    +      val (nan, ranges) = (op, negated) match {
    +        case ("=" | "<=>", false) | ("<>", true) => (false, Seq(point(v)))
    +        case ("=" | "<=>", true) | ("<>", false) =>
    +          (true, Seq(below(v, inclusive = false), above(v, inclusive = false)))
    +        case ("<", false) | (">=", true) => (false, Seq(below(v, inclusive = false)))
    +        case ("<=", false) | (">", true) => (false, Seq(below(v, inclusive = true)))
    +        case (">", false) | ("<=", true) => (true, Seq(above(v, inclusive = false)))
    +        case (">=", false) | ("<", true) => (true, Seq(above(v, inclusive = true)))
    +        case _ => throw SparkException.internalError(s"Unexpected comparison $op.")
    +      }
    +      single(column, Values(nullAllowed, nan, Some(ranges)))
    +    }
    +  }
    +
    +  private def in(column: Column, values: Seq[Any], negated: Boolean): Constraint = {
    +    val nonNull = values.filter(_ != null)
    +    val hasNaN = nonNull.exists(isNaN)
    +    val points = nonNull.filterNot(isNaN).map(normalize).sorted(column.ordering)
    +      .foldLeft(List.empty[Any]) {
    +        case (last :: rest, v) if column.ordering.equiv(last, v) => last :: rest
    +        case (acc, v) => v :: acc
    +      }.reverse
    +    if (values.isEmpty) {
    +      // x IN () is false, also for null, unless spark.sql.legacy.nullInEmptyListBehavior makes it
    +      // null for null. So it is never true, and NOT (x IN ()) is true for any value, and by
    +      // default for null.
    +      if (negated) All else single(column, NoValue)
    +    } else if (!negated) {
    +      single(column, Values(nullAllowed = false, hasNaN, Some(points.map(point))))
    +    } else if (nonNull.length < values.length) {
    +      // NOT (x IN (..., NULL)) is never true: it is false or null.
    +      single(column, NoValue)
    +    } else if (points.isEmpty) {
    +      // NOT (x IN (NaN)) is true for the values other than NaN.
    +      single(column, Values(nullAllowed = false, !hasNaN, None))
    +    } else {
    +      // The values between the points.
    +      val bounds = None +: points.map(Some(_)) :+ None
    +      val gaps = bounds.zip(bounds.tail).map { case (low, high) =>
    +        ValueRange(low, lowInclusive = false, high = high, highInclusive = false)
    +      }
    +      single(column, Values(nullAllowed = false, !hasNaN, Some(gaps)))
    +    }
    +  }
    +
    +  private def startsWith(column: Column, prefix: Any, negated: Boolean): Constraint = {
    +    (prefix, negated) match {
    +      case (null, _) => single(column, NoValue)
    +      // The strings that do not start with the prefix are not a range. A value whose bytes are not
    +      // valid UTF-8 could even be in the range of the strings that do.
    +      case (_, true) => single(column, anyValue(column))
    +      case (prefix: UTF8String, false) if prefix.numBytes() == 0 => single(column, anyValue(column))
    +      case (prefix: UTF8String, false) =>
    +        val range = ValueRange(Some(prefix), lowInclusive = true, high = nextPrefix(prefix),
    +          highInclusive = false)
    +        single(column, Values(nullAllowed = false, nanAllowed = false, Some(Seq(range))))
    +      case _ => All
    +    }
    +  }
    +
    +  /**
    +   * Returns the smallest string that is greater than all the strings that start with the prefix,
    +   * in the order of their UTF-8 bytes, which is the order of their code points, or None if there
    +   * is none: the prefix with its last code point incremented, after dropping the trailing
    +   * U+10FFFF, the largest code point.
    +   */
    +  private[columnar] def nextPrefix(prefix: UTF8String): Option[UTF8String] = {
    +    val codePoints = prefix.toString.codePoints().toArray.toBuffer
    +    while (codePoints.nonEmpty && codePoints.last == Character.MAX_CODE_POINT) {
    +      codePoints.remove(codePoints.length - 1)
    +    }
    +    if (codePoints.isEmpty) {
    +      None
    +    } else {
    +      val last = codePoints.last + 1
    +      // Skips the surrogates, which are not code points of characters.
    +      codePoints(codePoints.length - 1) =
    +        if (last >= Character.MIN_SURROGATE && last <= Character.MAX_SURROGATE) {
    +          Character.MAX_SURROGATE + 1
    +        } else {
    +          last
    +        }
    +      Some(UTF8String.fromString(new String(codePoints.toArray, 0, codePoints.length)))
    +    }
    +  }
    +
    +  private def single(column: Column, values: Values): Constraint = {
    +    // Only floating-point columns have NaN.
    +    val normalized = values.copy(nanAllowed = values.nanAllowed && column.isFloating)
    +    if (isAll(column, normalized)) All else Some(Map(column -> normalized))
    +  }
    +
    +  private def point(v: Any): ValueRange =
    +    ValueRange(Some(v), lowInclusive = true, high = Some(v), highInclusive = true)
    +
    +  private def below(v: Any, inclusive: Boolean): ValueRange =
    +    ValueRange(None, lowInclusive = false, high = Some(v), highInclusive = inclusive)
    +
    +  private def above(v: Any, inclusive: Boolean): ValueRange =
    +    ValueRange(Some(v), lowInclusive = inclusive, high = None, highInclusive = false)
    +
    +  private def anyValue(column: Column): Values = {
    +    Values(nullAllowed = false, nanAllowed = column.isFloating, None)
    +  }
    +
    +  private def isAll(column: Column, values: Values): Boolean = {
    +    values.nullAllowed && values.ranges.isEmpty && (values.nanAllowed || !column.isFloating)
    +  }
    +
    +  private def isEmpty(values: Values): Boolean = {
    +    !values.nullAllowed && !values.nanAllowed && values.ranges.exists(_.isEmpty)
    +  }
    +
    +  // Whether no row can make the predicates true.
    +  private def matchesNoRow(constraint: Constraint): Boolean = {
    +    constraint.forall(_.values.exists(isEmpty))
    +  }
    +
    +  private def and(left: Constraint, right: Constraint): Constraint = (left, right) match {
    +    case (Some(l), Some(r)) =>
    +      Some((l.keySet ++ r.keySet).map { column =>

    Nit (P3): (l.keySet ++ r.keySet).map { ... } builds a Set of (Column, Values) pairs before .toMap. From the fifth element on, Scala 2.13's Set builder switches to a HashSet and hashes every pair, and the case-class hash of Values walks its whole list of ranges; a Decimal bound even builds a BigDecimal to hash. derive folds every pushed predicate through and, so once five columns are constrained, each further predicate rehashes all the ranges of an earlier IN list. An example is d IN (<10,000 decimals>) AND a > 1 AND b > 1 AND c > 1 AND e > 1 with its inferred IS NOT NULL filters.

    Mapping through an iterator, (l.keySet ++ r.keySet).iterator.map { ... }.toMap, or folding r into l, gives the same map and hashes only the columns. or builds its map the same way.

    Verification:

  • Regression: Deriving the domains of an IN list of thousands of decimal values combined with predicates on five or more other columns takes time proportional to the number of values, not to the number of values times the number of predicates.

  • Behavior: The domains derived in the existing rule cases and in the randomized check against Spark's evaluation are unchanged.
  • spark-test spark-test commented on Nov 04, 2026 15:24 UTC
    Reviewer

    Review summary

    All three findings of the previous review are fixed in 9fc11f6. The comment on NOT (x IN (..., NULL)) now says that it is false or null. The -0.0 cases use literals that keep the sign of the zero. The test library can fail push_domains, and allocator checks confirm that Spark releases the exported ranges after a failure and after a success.

    This round found six more issues. None of them makes a query return wrong results:

  • ColumnarScanBuilder now implements SupportsPushDownV2Filters, so Spark reorders the conjuncts that it evaluates after every filtered native scan, translatable ones first, also with spark.sql.dataSource.native.filterPushdown.enabled off. Filters that put a cheap, selective conjunct before an expensive translatable one get slower than on the base branch.

  • Two steps of the domain derivation do avoidable planning work. and rehashes every range of earlier IN lists once five columns are constrained, and left-deep OR chains re-sort the accumulated ranges at every node.

  • The guide and the header say that the plan shows PushedFilters and PushedDomains, but only the formatted plan and the SQL UI do.

  • Two test gaps: no test library moves the domain ranges, as Arrow importers do, and no test covers tinyint, smallint or timestamp_ntz domains.
  • Two questions for the author follow: the release-line question of the previous review, which is still open, and a new one.

    Cross-cutting observations

  • Long value lists, IN and NOT IN lists and long OR chains, are the inputs on which this change does the most work outside the scan itself, both while it derives the domains and after.
  • The two derivation fixes do not depend on the answer to the domain-size question, because any cap on the number of ranges would only apply once the derivation has run.

    Findings

    6 total: 0 P0, 0 P1, 1 P2, 5 P3.

    Non-blocking (P2)

  • Native scans now reorder the conjuncts evaluated after the scan, even with the flag off — sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnarTable.scala:88 — see inline.
  • Nit (P3)

  • and rehashes all accumulated ranges once five columns are constrained — sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnDomains.scala:375 — see inline.

  • Left-deep OR chains make the domain derivation quadratic — sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnDomains.scala:488 — see inline.

  • PushedFilters and PushedDomains only show in the formatted plan — docs/sql-native-data-sources.md:221 — see inline.

  • No test library moves the domain ranges, as Arrow importers do — sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/ffi/NativeDataSourceSuite.scala:997 — see inline.

  • No test covers tinyint, smallint or timestamp_ntz domains — sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnDomainsSuite.scala:44 — see inline.
  • Re-review status

    Prior AI findings: 3 no longer raised, 0 still raised; additional unresolved findings in this review: 6.

    New attribution: 0 newly introduced, 6 late catch, 0 previously raised, 0 unattributed.

    PR description suggestions

  • The title still has the SPARK-XXXXX placeholder. This is a separate, non-trivial change after SPARK-60101, so it needs its own JIRA ticket in the title, for example a sub-task of SPARK-60101.
  • Decision challenges

    Release line of push_domains and its config: 4.4.0, or master-only 5.0.0?

    The previous two reviews asked this, and it is still open: the config still declares 5.0.0, and the description still says that a library built against the 4.4 header has a smaller table.

    Verified again at this head:

  • spark.sql.dataSource.native.filterPushdown.enabled declares .version("5.0.0"), master's version, while spark.sql.dataSource.native.enabled and spark.sql.dataSource.native.paths declare 4.4.0.

  • branch-4.x was set to 4.4.0 and already has native data sources. Its spark_datasource.h is identical to the base of this PR, without push_domains.

  • push_domains takes the table slot after close_data_writer, and SPARK_DS_ABI_VERSION stays 1. NativeLibrary binds each function at its fixed offset whenever the library's table is large enough.
  • So if push_domains ships only from 5.0.0, the next function that branch-4.x appends to version 1 gets the same offset, and neither the table size nor the ABI version tells the two apart. If it also ships in 4.4.0, the config declares the wrong version.

    Could you confirm which release first ships push_domains? If it is 4.4.0, the config should declare 4.4.0. If it is master-only, how will branch-4.x keep version 1 aligned? For example, it could reserve the slot before any other addition there. Either way, the header and the guide could say from which release Spark calls push_domains.

    Should Spark bound the domains of long IN and NOT IN lists?

    Verified in the checkout:

  • ColumnDomains.in turns an IN list into one point range per distinct value, and a NOT IN list into n+1 gaps, with no bound or compaction.

  • NativeArrow.exportDomains exports every range. For a used domain, ColumnarScan.getMetaData renders all of them in PushedDomains, next to the whole predicate in PushedFilters. Formatted explain prints both without abbreviation, and the SQL UI shows the formatted plan by default.

  • The header asks a library to skip only data whose statistics show no value in a domain, without saying how to match. Both examples in the description and the test library check every range against every file or block.
  • So with id IN (<100,000 values>) and a library that uses the domain, Spark exports 100,000 ranges, and every formatted plan of the query lists the values twice. A library that follows the examples over 10,000 files makes about 10^9 comparisons on the driver while planning. The base branch does none of this work, but it also skips no data.

    What this review cannot settle is which trade-off fits the workloads you expect. Spark could compact a domain beyond some number of ranges, for example to its hull, which is still a superset. The header could tell libraries that the ranges are sorted, so that they can binary-search them. Or the cost may be acceptable for the list sizes you expect. Which do you intend?

    Generated by Omnigent on Databricks
    <!-- SPARK_OSS_REVIEW_REQUEST 35078364469 -->

    <!-- SPARK_DEV_REVIEW_CODE {"findings":[{"delivery":"inline","fingerprint":"bdc6adc0ccfe588717cf","id":"pass-b:post-scan-conjunct-reorder"},{"delivery":"inline","fingerprint":"6c2751ccf63e466dbf6d","id":"pass-b:and-rehashes-accumulated-ranges"},{"delivery":"inline","fingerprint":"5a31a3d881d1a253a1dc","id":"pass-b:or-chains-quadratic-union"},{"delivery":"inline","fingerprint":"7bd52b1615d682f93bff","id":"pass-b:pushed-metadata-only-in-formatted-plan"},{"delivery":"inline","fingerprint":"13d0e0f9ca2c07f4eb02","id":"pass-b:moved-domain-ranges-untested"},{"delivery":"inline","fingerprint":"4944fc78d5d1dfa704d7","id":"pass-b:narrow-integral-and-ntz-domains-untested"}],"head_sha":"d204cbc31f382eaea8aa2cf0b338ad6323354469","verdict_sha256":"81c2cae7f12d3a9c486289dc6a393cb5f23eac58dfb96d52b73a52cab9e6a173"} -->

    spark-test spark-test commented on code on Nov 04, 2026 15:24 UTC
    Code Review
    sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnDomains.scala:1
    @@ -0,0 +1,547 @@
    +/*
    + * 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.
    + */
    +package org.apache.spark.sql.execution.datasources.v2.columnar
    +
    +import scala.collection.mutable.ArrayBuffer
    +
    +import org.apache.spark.SparkException
    +import org.apache.spark.sql.catalyst.expressions.Literal
    +import org.apache.spark.sql.catalyst.types.PhysicalDataType
    +import org.apache.spark.sql.catalyst.util.quoteIfNeeded
    +import org.apache.spark.sql.connector.expressions.{Expression, LiteralValue, NamedReference}
    +import org.apache.spark.sql.connector.expressions.filter.Predicate
    +import org.apache.spark.sql.types._
    +import org.apache.spark.unsafe.types.UTF8String
    +
    +/**
    + * The values that a column can have in the rows that match the filters of a query: null if
    + * `nullAllowed`, NaN if `nanAllowed`, for a float or double column, and the other values in one
    + * of the `ranges`, or any of them without ranges. A data source can skip the data whose statistics
    + * show that it has no value in the domain of a column, but never a row whose values are in their
    + * domains: Spark evaluates the filters after reading anyway.
    + *
    + * @param path the index of the column in the read schema, and then the index of the field in each
    + *             struct, for a field of a struct
    + * @param name the names of the column and of its fields
    + * @param ranges sorted ranges, which neither overlap nor touch, of the values other than null and
    + *               NaN, in the internal representation of Spark. None if the column can have any of
    + *               them, and empty if it can have none.
    + */
    +case class ColumnDomain(
    +    path: Seq[Int],
    +    name: Seq[String],
    +    dataType: DataType,
    +    nullAllowed: Boolean,
    +    nanAllowed: Boolean,
    +    ranges: Option[Seq[ValueRange]]) {
    +
    +  private def ordering: Ordering[Any] = PhysicalDataType.ordering(dataType)
    +
    +  /** Whether the domain has the value, in the internal representation of Spark. */
    +  def contains(value: Any): Boolean = value match {
    +    case null => nullAllowed
    +    case f: Float if f.isNaN => nanAllowed
    +    case d: Double if d.isNaN => nanAllowed
    +    case _ => ranges.forall(_.exists(_.contains(value, ordering)))
    +  }
    +
    +  override def toString: String = {
    +    def literal(value: Any): String = Literal(value, dataType).sql
    +    val values = ranges match {
    +      case None => Seq("ANY")
    +      case Some(ranges) => ranges.map {
    +        case ValueRange(Some(low), true, Some(high), true) if ordering.equiv(low, high) =>
    +          literal(low)
    +        case range =>
    +          (if (range.lowInclusive) "[" else "(") + range.low.map(literal).getOrElse("-inf") +
    +            ", " + range.high.map(literal).getOrElse("+inf") +
    +            (if (range.highInclusive) "]" else ")")
    +      }
    +    }
    +    val special = (if (nullAllowed) Seq("NULL") else Nil) ++ (if (nanAllowed) Seq("NaN") else Nil)
    +    val all = special ++ values
    +    s"${name.map(quoteIfNeeded).mkString(".")}: ${if (all.isEmpty) "NONE" else all.mkString(", ")}"
    +  }
    +}
    +
    +/**
    + * A range of values in the internal representation of Spark: the values above `low`, or equal to
    + * it if `lowInclusive`, and below `high`, or equal to it if `highInclusive`. A bound that is None
    + * is unbounded, and is not inclusive.
    + */
    +case class ValueRange(low: Option[Any], lowInclusive: Boolean, high: Option[Any],
    +    highInclusive: Boolean) {
    +
    +  def contains(value: Any, ordering: Ordering[Any]): Boolean = {
    +    low.forall { l =>
    +      val c = ordering.compare(value, l)
    +      c > 0 || (c == 0 && lowInclusive)
    +    } && high.forall { h =>
    +      val c = ordering.compare(value, h)
    +      c < 0 || (c == 0 && highInclusive)
    +    }
    +  }
    +}
    +
    +/**
    + * The domains that a query passes to a data source, and the predicates that each of them comes
    + * from.
    + *
    + * @param domains the domains, at most one for each column, sorted by path
    + * @param columns the paths of the columns that each predicate constrains
    + */
    +case class ColumnDomains(domains: Seq[ColumnDomain], columns: Seq[Set[Seq[Int]]]) {
    +
    +  /**
    +   * Returns the predicates that constrain only the columns whose domains are used, given whether
    +   * the data source uses each domain.
    +   */
    +  def pushedPredicates(predicates: Array[Predicate], used: Seq[Boolean]): Array[Predicate] = {
    +    val usedPaths = domains.zip(used).collect { case (domain, true) => domain.path }.toSet
    +    predicates.zip(columns).collect {
    +      case (predicate, paths) if paths.nonEmpty && paths.subsetOf(usedPaths) => predicate
    +    }
    +  }
    +}
    +
    +/**
    + * Derives the domains of the columns that the predicates of a query constrain, the ones that Data
    + * Source V2 pushes to a scan, combined with AND. A domain is a superset of the values that a column
    + * has in the rows for which all the predicates are true: Spark derives it from the comparisons of
    + * a column with literals, IN, IS NULL, IS NOT NULL and STARTS_WITH, under AND, OR and NOT, with the
    + * semantics of Spark SQL. Comparisons with null are null, NaN is equal to NaN and greater than any
    + * other value, -0.0 is equal to 0.0, and strings and binary values are compared by their bytes, as
    + * unsigned bytes. A predicate that cannot be expressed this way does not constrain any column. Only
    + * the columns and the fields of structs of the types that a data source can compare get a domain:
    + * not the strings of a non-binary collation, nor arrays, maps and structs. A field of a struct only
    + * gets a domain that does not have null.
    + */
    +object ColumnDomains {
    +
    +  // A column that a predicate constrains, with its type.
    +  private case class Column(path: Seq[Int], name: Seq[String], dataType: DataType) {
    +    val ordering: Ordering[Any] = PhysicalDataType.ordering(dataType)
    +    val isFloating: Boolean = dataType == FloatType || dataType == DoubleType
    +  }
    +
    +  // The values that a column can have: see ColumnDomain.
    +  private case class Values(nullAllowed: Boolean, nanAllowed: Boolean,
    +      ranges: Option[Seq[ValueRange]])
    +
    +  private val NoValue = Values(nullAllowed = false, nanAllowed = false, Some(Nil))
    +  private val OnlyNull = Values(nullAllowed = true, nanAllowed = false, Some(Nil))
    +
    +  // The columns that the predicates constrain, with their values: a row can only make the
    +  // predicates true if each of these columns has one of the values. None when no row can.
    +  private type Constraint = Option[Map[Column, Values]]
    +  private val All: Constraint = Some(Map.empty)
    +  private val NoRow: Constraint = None
    +
    +  /** Derives the domains of the predicates for a scan of the schema. */
    +  def derive(predicates: Seq[Predicate], schema: StructType): ColumnDomains = {
    +    val constraints = predicates.map(constraint(_, negated = false, schema))
    +    val columns = constraints.map(_.map(_.keySet.map(_.path)).getOrElse(Set.empty[Seq[Int]]))
    +    val domains = constraints.foldLeft(All)(and) match {
    +      case Some(values) =>
    +        values.toSeq.collect {
    +          // A field of a struct is null in the rows where the struct, or a struct that contains it,
    +          // is null, which the statistics of its Arrow child array may not count as nulls. So a
    +          // field only gets a domain without null, which these rows never match.
    +          case (column, v) if column.path.length == 1 || !v.nullAllowed =>
    +            ColumnDomain(column.path, column.name, column.dataType, v.nullAllowed, v.nanAllowed,
    +              v.ranges)
    +        }.sortBy(_.path)(Ordering.Implicits.seqOrdering[Seq, Int])
    +      // A predicate that is always false, which Spark usually removes before it scans the data.
    +      case None => Nil
    +    }
    +    ColumnDomains(domains, columns)
    +  }
    +
    +  // The rows for which the predicate is true, or false if negated: NOT moves to the leaves.
    +  private def constraint(predicate: Predicate, negated: Boolean, schema: StructType): Constraint = {
    +    def child(i: Int): Option[Predicate] = predicate.children().lift(i).collect {
    +      case p: Predicate => p
    +    }
    +    def both(combine: (Constraint, Constraint) => Constraint, negated: Boolean): Constraint = {
    +      (child(0), child(1)) match {
    +        case (Some(left), Some(right)) =>
    +          combine(constraint(left, negated, schema), constraint(right, negated, schema))
    +        case _ => All
    +      }
    +    }
    +    predicate.name() match {
    +      case "AND" => if (negated) both(or, negated = true) else both(and, negated = false)
    +      case "OR" => if (negated) both(and, negated = true) else both(or, negated = false)
    +      case "NOT" => child(0).map(constraint(_, !negated, schema)).getOrElse(All)
    +      case "ALWAYS_TRUE" => if (negated) NoRow else All
    +      case "ALWAYS_FALSE" => if (negated) All else NoRow
    +      case _ => leaf(predicate, negated, schema).getOrElse(All)
    +    }
    +  }
    +
    +  private def leaf(
    +      predicate: Predicate,
    +      negated: Boolean,
    +      schema: StructType): Option[Constraint] = {
    +    val children = predicate.children()
    +    predicate.name() match {
    +      case "IS_NULL" | "IS_NOT_NULL" if children.length == 1 =>
    +        column(children(0), schema).map { col =>
    +          val isNull = (predicate.name() == "IS_NULL") != negated
    +          single(col, if (isNull) OnlyNull else anyValue(col))
    +        }
    +      case op @ ("=" | "<>" | "<=>" | "<" | "<=" | ">" | ">=") if children.length == 2 =>
    +        val operands = (column(children(0), schema), column(children(1), schema)) match {
    +          case (Some(col), _) => literal(children(1), col).map((col, _, op))
    +          case (_, Some(col)) => literal(children(0), col).map((col, _, flip(op)))
    +          case _ => None
    +        }
    +        operands.map { case (col, value, op) => compare(col, value, op, negated) }
    +      case "IN" if children.nonEmpty =>
    +        column(children(0), schema).flatMap { col =>
    +          val values = children.tail.map(literal(_, col))
    +          if (values.forall(_.isDefined)) Some(in(col, values.map(_.get).toSeq, negated)) else None
    +        }
    +      case "STARTS_WITH" if children.length == 2 =>
    +        column(children(0), schema).filter(_.dataType.isInstanceOf[StringType]).flatMap { col =>
    +          literal(children(1), col).map(prefix => startsWith(col, prefix, negated))
    +        }
    +      case _ => None
    +    }
    +  }
    +
    +  private def flip(op: String): String = op match {
    +    case "<" => ">"
    +    case "<=" => ">="
    +    case ">" => "<"
    +    case ">=" => "<="
    +    case other => other
    +  }
    +
    +  private def compare(column: Column, value: Any, op: String, negated: Boolean): Constraint = {
    +    // NOT (x <=> v) is true for null, unless v is null.
    +    val nullAllowed = op == "<=>" && negated && value != null
    +    if (value == null) {
    +      // A comparison with null is null, and so is its negation, but x <=> NULL is x IS NULL.
    +      if (op == "<=>") single(column, if (negated) anyValue(column) else OnlyNull)
    +      else single(column, NoValue)
    +    } else if (isNaN(value)) {
    +      // NaN is equal to NaN and greater than any other value: (NaN, other values).
    +      val (nan, others) = (op, negated) match {
    +        case ("=" | "<=>" | ">=", false) | ("<>" | "<", true) => (true, Some(Nil))
    +        case ("=" | "<=>" | ">=", true) | ("<>" | "<", false) => (false, None)
    +        case ("<=", false) | (">", true) => (true, None)
    +        case ("<=", true) | (">", false) => (false, Some(Nil))
    +        case _ => throw SparkException.internalError(s"Unexpected comparison $op.")
    +      }
    +      single(column, Values(nullAllowed, nan, others))
    +    } else {
    +      val v = normalize(value)
    +      // NaN is greater than v, and not equal to it.
    +      val (nan, ranges) = (op, negated) match {
    +        case ("=" | "<=>", false) | ("<>", true) => (false, Seq(point(v)))
    +        case ("=" | "<=>", true) | ("<>", false) =>
    +          (true, Seq(below(v, inclusive = false), above(v, inclusive = false)))
    +        case ("<", false) | (">=", true) => (false, Seq(below(v, inclusive = false)))
    +        case ("<=", false) | (">", true) => (false, Seq(below(v, inclusive = true)))
    +        case (">", false) | ("<=", true) => (true, Seq(above(v, inclusive = false)))
    +        case (">=", false) | ("<", true) => (true, Seq(above(v, inclusive = true)))
    +        case _ => throw SparkException.internalError(s"Unexpected comparison $op.")
    +      }
    +      single(column, Values(nullAllowed, nan, Some(ranges)))
    +    }
    +  }
    +
    +  private def in(column: Column, values: Seq[Any], negated: Boolean): Constraint = {
    +    val nonNull = values.filter(_ != null)
    +    val hasNaN = nonNull.exists(isNaN)
    +    val points = nonNull.filterNot(isNaN).map(normalize).sorted(column.ordering)
    +      .foldLeft(List.empty[Any]) {
    +        case (last :: rest, v) if column.ordering.equiv(last, v) => last :: rest
    +        case (acc, v) => v :: acc
    +      }.reverse
    +    if (values.isEmpty) {
    +      // x IN () is false, also for null, unless spark.sql.legacy.nullInEmptyListBehavior makes it
    +      // null for null. So it is never true, and NOT (x IN ()) is true for any value, and by
    +      // default for null.
    +      if (negated) All else single(column, NoValue)
    +    } else if (!negated) {
    +      single(column, Values(nullAllowed = false, hasNaN, Some(points.map(point))))
    +    } else if (nonNull.length < values.length) {
    +      // NOT (x IN (..., NULL)) is never true: it is false or null.
    +      single(column, NoValue)
    +    } else if (points.isEmpty) {
    +      // NOT (x IN (NaN)) is true for the values other than NaN.
    +      single(column, Values(nullAllowed = false, !hasNaN, None))
    +    } else {
    +      // The values between the points.
    +      val bounds = None +: points.map(Some(_)) :+ None
    +      val gaps = bounds.zip(bounds.tail).map { case (low, high) =>
    +        ValueRange(low, lowInclusive = false, high = high, highInclusive = false)
    +      }
    +      single(column, Values(nullAllowed = false, !hasNaN, Some(gaps)))
    +    }
    +  }
    +
    +  private def startsWith(column: Column, prefix: Any, negated: Boolean): Constraint = {
    +    (prefix, negated) match {
    +      case (null, _) => single(column, NoValue)
    +      // The strings that do not start with the prefix are not a range. A value whose bytes are not
    +      // valid UTF-8 could even be in the range of the strings that do.
    +      case (_, true) => single(column, anyValue(column))
    +      case (prefix: UTF8String, false) if prefix.numBytes() == 0 => single(column, anyValue(column))
    +      case (prefix: UTF8String, false) =>
    +        val range = ValueRange(Some(prefix), lowInclusive = true, high = nextPrefix(prefix),
    +          highInclusive = false)
    +        single(column, Values(nullAllowed = false, nanAllowed = false, Some(Seq(range))))
    +      case _ => All
    +    }
    +  }
    +
    +  /**
    +   * Returns the smallest string that is greater than all the strings that start with the prefix,
    +   * in the order of their UTF-8 bytes, which is the order of their code points, or None if there
    +   * is none: the prefix with its last code point incremented, after dropping the trailing
    +   * U+10FFFF, the largest code point.
    +   */
    +  private[columnar] def nextPrefix(prefix: UTF8String): Option[UTF8String] = {
    +    val codePoints = prefix.toString.codePoints().toArray.toBuffer
    +    while (codePoints.nonEmpty && codePoints.last == Character.MAX_CODE_POINT) {
    +      codePoints.remove(codePoints.length - 1)
    +    }
    +    if (codePoints.isEmpty) {
    +      None
    +    } else {
    +      val last = codePoints.last + 1
    +      // Skips the surrogates, which are not code points of characters.
    +      codePoints(codePoints.length - 1) =
    +        if (last >= Character.MIN_SURROGATE && last <= Character.MAX_SURROGATE) {
    +          Character.MAX_SURROGATE + 1
    +        } else {
    +          last
    +        }
    +      Some(UTF8String.fromString(new String(codePoints.toArray, 0, codePoints.length)))
    +    }
    +  }
    +
    +  private def single(column: Column, values: Values): Constraint = {
    +    // Only floating-point columns have NaN.
    +    val normalized = values.copy(nanAllowed = values.nanAllowed && column.isFloating)
    +    if (isAll(column, normalized)) All else Some(Map(column -> normalized))
    +  }
    +
    +  private def point(v: Any): ValueRange =
    +    ValueRange(Some(v), lowInclusive = true, high = Some(v), highInclusive = true)
    +
    +  private def below(v: Any, inclusive: Boolean): ValueRange =
    +    ValueRange(None, lowInclusive = false, high = Some(v), highInclusive = inclusive)
    +
    +  private def above(v: Any, inclusive: Boolean): ValueRange =
    +    ValueRange(Some(v), lowInclusive = inclusive, high = None, highInclusive = false)
    +
    +  private def anyValue(column: Column): Values = {
    +    Values(nullAllowed = false, nanAllowed = column.isFloating, None)
    +  }
    +
    +  private def isAll(column: Column, values: Values): Boolean = {
    +    values.nullAllowed && values.ranges.isEmpty && (values.nanAllowed || !column.isFloating)
    +  }
    +
    +  private def isEmpty(values: Values): Boolean = {
    +    !values.nullAllowed && !values.nanAllowed && values.ranges.exists(_.isEmpty)
    +  }
    +
    +  // Whether no row can make the predicates true.
    +  private def matchesNoRow(constraint: Constraint): Boolean = {
    +    constraint.forall(_.values.exists(isEmpty))
    +  }
    +
    +  private def and(left: Constraint, right: Constraint): Constraint = (left, right) match {
    +    case (Some(l), Some(r)) =>
    +      Some((l.keySet ++ r.keySet).map { column =>
    +        column -> ((l.get(column), r.get(column)) match {
    +          case (Some(a), Some(b)) => intersect(column, a, b)
    +          case (a, b) => a.orElse(b).get
    +        })
    +      }.toMap)
    +    case _ => NoRow
    +  }
    +
    +  // A column that only one side constrains can have any value in the rows of the other side, so
    +  // only the columns that both sides constrain are constrained.
    +  private def or(left: Constraint, right: Constraint): Constraint = {
    +    if (matchesNoRow(left)) {
    +      right
    +    } else if (matchesNoRow(right)) {
    +      left
    +    } else {
    +      val (l, r) = (left.get, right.get)
    +      Some(l.keySet.intersect(r.keySet).map(column => column -> union(column, l(column), r(column)))
    +        .filterNot { case (column, values) => isAll(column, values) }.toMap)
    +    }
    +  }
    +
    +  private def intersect(column: Column, a: Values, b: Values): Values = Values(
    +    a.nullAllowed && b.nullAllowed,
    +    a.nanAllowed && b.nanAllowed,
    +    (a.ranges, b.ranges) match {
    +      case (Some(x), Some(y)) => Some(intersectRanges(x, y, column.ordering))
    +      case (x, y) => x.orElse(y)
    +    })
    +
    +  private def union(column: Column, a: Values, b: Values): Values = Values(
    +    a.nullAllowed || b.nullAllowed,
    +    a.nanAllowed || b.nanAllowed,
    +    (a.ranges, b.ranges) match {
    +      case (Some(x), Some(y)) =>
    +        unionRanges(x, y, column.ordering) match {
    +          // All the values.
    +          case Seq(ValueRange(None, _, None, _)) => None
    +          case ranges => Some(ranges)
    +        }
    +      case _ => None
    +    })
    +
    +  // A negative value when `a` starts before `b`.
    +  private def compareLows(a: ValueRange, b: ValueRange, ordering: Ordering[Any]): Int = {
    +    (a.low, b.low) match {
    +      case (None, None) => 0
    +      case (None, _) => -1
    +      case (_, None) => 1
    +      case (Some(x), Some(y)) =>
    +        val c = ordering.compare(x, y)
    +        if (c != 0 || a.lowInclusive == b.lowInclusive) c else if (a.lowInclusive) -1 else 1
    +    }
    +  }
    +
    +  // A negative value when `a` ends before `b`.
    +  private def compareHighs(a: ValueRange, b: ValueRange, ordering: Ordering[Any]): Int = {
    +    (a.high, b.high) match {
    +      case (None, None) => 0
    +      case (None, _) => 1
    +      case (_, None) => -1
    +      case (Some(x), Some(y)) =>
    +        val c = ordering.compare(x, y)
    +        if (c != 0 || a.highInclusive == b.highInclusive) c else if (a.highInclusive) 1 else -1
    +    }
    +  }
    +
    +  private def isEmptyRange(range: ValueRange, ordering: Ordering[Any]): Boolean = {
    +    (range.low, range.high) match {
    +      case (Some(low), Some(high)) =>
    +        val c = ordering.compare(low, high)
    +        c > 0 || (c == 0 && !(range.lowInclusive && range.highInclusive))
    +      case _ => false
    +    }
    +  }
    +
    +  // Intersects two lists of sorted ranges that neither overlap nor touch, by sweeping them.
    +  private def intersectRanges(
    +      left: Seq[ValueRange],
    +      right: Seq[ValueRange],
    +      ordering: Ordering[Any]): Seq[ValueRange] = {
    +    // The ranges are usually lists, such as those of IN, so the sweep indexes copies of them.
    +    val (a, b) = (left.toIndexedSeq, right.toIndexedSeq)
    +    val result = ArrayBuffer.empty[ValueRange]
    +    var i = 0
    +    var j = 0
    +    while (i < a.length && j < b.length) {
    +      val (x, y) = (a(i), b(j))
    +      val low = if (compareLows(x, y, ordering) >= 0) x else y
    +      val high = if (compareHighs(x, y, ordering) <= 0) x else y
    +      val range = ValueRange(low.low, low.lowInclusive, high.high, high.highInclusive)
    +      if (!isEmptyRange(range, ordering)) {
    +        result += range
    +      }
    +      // Moves past the range that ends first.
    +      if (compareHighs(x, y, ordering) <= 0) i += 1 else j += 1
    +    }
    +    result.toSeq
    +  }
    +
    +  // Merges two lists of sorted ranges, and the ranges that overlap or touch, such as [1, 2) and
    +  // [2, 3].
    +  private def unionRanges(
    +      a: Seq[ValueRange],
    +      b: Seq[ValueRange],
    +      ordering: Ordering[Any]): Seq[ValueRange] = {
    +    def touches(first: ValueRange, next: ValueRange): Boolean = (first.high, next.low) match {
    +      case (Some(high), Some(low)) =>
    +        val c = ordering.compare(low, high)
    +        c < 0 || (c == 0 && (first.highInclusive || next.lowInclusive))
    +      case _ => true
    +    }
    +    (a ++ b).sortWith(compareLows(_, _, ordering) < 0).foldLeft(List.empty[ValueRange]) {

    Nit (P3): Each OR node calls unionRanges with the ranges of its two sides, and this line concatenates them, sorts the result and folds it into a new list. A disjunction built with the DataFrame API, such as ids.map(v => col("id") === v).reduce(_ || _), is a left-deep tree. So the i-th OR node copies, sorts and rebuilds the i ranges accumulated so far, and no optimizer rule turns such a chain of equalities into IN. With 10,000 ids that is on the order of 10^8 range operations on the driver while planning, about a second by estimate, where one sort of the whole chain would do.

    Collecting the disjuncts of nested ORs, and of ANDs under NOT, before a single union per column would make it O(k log k). It needs to keep the current rules for disjuncts that match no row and for columns that only some disjuncts constrain.

    Verification:

  • Regression: Deriving the domains of a left-deep OR chain of tens of thousands of equalities on one column, as reduce(_ || _) builds it, takes time proportional to k log k.

  • Behavior: The domains of OR and negated AND combinations in the existing rule cases and in the randomized check are unchanged.
  • spark-test spark-test commented on code on Nov 04, 2026 15:24 UTC
    Code Review
    docs/sql-native-data-sources.md:1
    @@ -169,12 +170,67 @@ a write that runs for long, or blocks, for example on network I/O, should check
     regularly and use timeouts. The task reaper, `spark.task.reaper.enabled` and
     `spark.task.reaper.killTimeout`, kills an executor whose killed task does not end.
     
    +### Filter Pushdown
    +
    +Spark does not pass the filters of a query to a library as expressions, which a library would have
    +to evaluate with the exact semantics of Spark SQL. It passes the *domains* of the columns that the
    +filters constrain instead: for each column, the values that it can have in the rows that match,
    +which a library compares with the statistics of its data to skip what cannot match, such as files,
    +row groups or blocks. With `push_domains`, a reader gets a `SparkDsDomain` for each column, with:
    +
    +- `path`: the index of the column in the schema to read, and then the index of the field in each
    +  struct, for a field of a struct;
    +- `null_allowed` and `nan_allowed`: whether null and NaN are in the domain;
    +- `ranges`: the ranges of the other values in the domain, as a struct array whose fields are
    +  `low` and `high`, of the Arrow type of the column, with a null bound for no bound, and
    +  `low_inclusive` and `high_inclusive`. The ranges are sorted and do not overlap. A single value
    +  is a range whose bounds are equal and inclusive, and `ranges` is `NULL` when all the other
    +  values are in the domain.
    +
    +For example:
    +
    +| Filter | Domain |
    +|--------|--------|
    +| `id > 5 AND id <= 10` | `id`: `(5, 10]` |
    +| `id IN (1, 3) OR id IS NULL` | `id`: null, `[1, 1]`, `[3, 3]` |
    +| `NOT (id = 5)` | `id`: `(-inf, 5)`, `(5, +inf)` |
    +| `value > 1.5`, for a `double` column | `value`: NaN, `(1.5, +inf)` |
    +| `name LIKE 'ab%'`, which is `STARTS_WITH(name, 'ab')` | `name`: `['ab', 'ac')` |
    +| `s.x = 1 AND name IS NOT NULL` | `s.x`: `[1, 1]`; `name`: all the values but null |
    +| `id > 5 OR name = 'a'` | none: each side only constrains one of the columns |
    +
    +Spark derives the domains from the comparisons of a column with literals (`=`, `<>`, `<=>`, `<`,
    +`<=`, `>`, `>=`), `IN`, `IS NULL`, `IS NOT NULL` and `STARTS_WITH`, combined with `AND`, `OR` and
    +`NOT`, with the semantics of Spark SQL: comparisons with null are null, so that
    +`NOT (id IN (1, NULL))` matches no row, NaN is equal to NaN and greater than any other value, and
    +-0.0 is equal to 0.0. A domain has all the values of its column in the rows for which the filters
    +are true, and may have others: a column that only one side of an `OR` constrains gets no domain
    +from it, and the other filters, such as `id + 1 > 5`, `a = b` or `ENDS_WITH(name, 'x')`, constrain
    +no column. Columns of strings with a non-binary collation, such as `UTF8_LCASE`, and arrays, maps
    +and structs, get no domain. A field of a struct is null in the rows where the struct, or a struct
    +that contains it, is null, whatever the Arrow child array of the field holds there, so statistics
    +computed from that array may not count these rows as nulls: Spark only passes domains without null
    +for the fields of structs.
    +
    +A library compares values with the order of Spark SQL: numbers, dates and timestamps by their
    +values, with -0.0 equal to 0.0 (use IEEE 754 comparisons, not a total order such as
    +`f64::total_cmp`), strings by their UTF-8 bytes, binary values as unsigned bytes, and false before
    +true. It must never skip a row whose values are all in their domains, which Spark cannot detect,
    +but it can return rows that are not: Spark evaluates all the filters again after reading. So a
    +library only uses the domains to read less data, and Spark does not push a `LIMIT` down with a
    +filter. The library sets `used` to whether it uses each domain, and the plan of the query shows the

    Nit (P3): ColumnarScan exposes PushedFilters and PushedDomains only through getMetaData, which only DataSourceV2ScanExecBase.verboseStringWithOperatorId prints. BatchScanExec.simpleString, which df.explain(), EXPLAIN and EXPLAIN EXTENDED print, shows the output, the scan's description and RuntimeFilters, and here the description is just the short name of the data source. So a library author who checks with df.explain() whether Spark pushed a domain sees neither entry and would conclude that nothing was pushed. They only appear with EXPLAIN FORMATTED, df.explain("formatted") and in the SQL UI.

    The push_domains comment in spark_datasource.h makes the same claim. Naming the formatted plan and the SQL UI in both places fixes it.

    Verification:

  • Inspection: The guide's and the header's statements about where PushedFilters and PushedDomains appear match a native scan's metadata, which only formatted explain and the SQL UI print.
  • spark-test spark-test commented on code on Nov 04, 2026 15:24 UTC
    Code Review
    sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/ffi/NativeDataSourceSuite.scala:1
    @@ -881,6 +994,16 @@ class NativeDataSourceSuite extends QueryTest with SharedSparkSession {
         check("plan a scan of", "injected failure in plan") { session =>
           range(session, "fail" -> "plan").collect()
         }
    +    // Spark releases the ranges of the domains that it pushes down, after a failure of push_domains

    Nit (P3): These checks cover a failing push_domains and a successful one, but in both cases Spark releases the ranges itself, since the test library only reads domain->ranges in place. The header also lets a library move the ranges and their schema to take ownership, and both examples in the description do so (arrow-rs from_ffi, Arrow C++ ImportArray). NativeArrow.exportDomains relies on that when it calls release and close on both structs and then closes the root. If that cleanup ever freed the exported buffers whatever the library did, a library that keeps the moved ranges in its reader for partitions would read freed memory, and every test here would still pass.

    A test library option could cover that path: move the ranges in push_domains, read them when planning the partitions, and release them in close_reader, with allocator checks before and after the reader is closed.

    This extends an existing discussion.

    Verification:

  • Regression: With a library that moves the ranges and releases them when the reader is closed, the query returns the right rows, the library reads valid ranges after the call, the Arrow allocator still holds them until the reader is closed, and it is back to its baseline afterwards.
  • spark-test spark-test commented on code on Nov 04, 2026 15:24 UTC
    Code Review
    sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnDomainsSuite.scala:1
    @@ -0,0 +1,383 @@
    +/*
    + * 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.
    + */
    +package org.apache.spark.sql.execution.datasources.v2.columnar
    +
    +import java.sql.Date
    +
    +import scala.jdk.CollectionConverters._
    +import scala.util.Random
    +
    +import org.scalatest.concurrent.TimeLimits
    +import org.scalatest.time.SpanSugar._
    +
    +import org.apache.spark.sql.{Column, QueryTest, Row}
    +import org.apache.spark.sql.catalyst.{CatalystTypeConverters, InternalRow}
    +import org.apache.spark.sql.catalyst.expressions.{Literal, PredicateHelper}
    +import org.apache.spark.sql.catalyst.plans.logical.Filter
    +import org.apache.spark.sql.connector.expressions.{Expression => V2Expression, FieldReference, LiteralValue}
    +import org.apache.spark.sql.connector.expressions.filter.Predicate
    +import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Strategy
    +import org.apache.spark.sql.functions.{col, expr, not}
    +import org.apache.spark.sql.internal.SQLConf
    +import org.apache.spark.sql.test.SharedSparkSession
    +import org.apache.spark.sql.types._
    +import org.apache.spark.unsafe.types.UTF8String
    +
    +/** Tests how [[ColumnDomains]] derives the domains of columns from the predicates of a query. */
    +class ColumnDomainsSuite extends QueryTest with SharedSparkSession with PredicateHelper
    +  with TimeLimits {
    +
    +  private val schema = StructType.fromDDL("id BIGINT, i INT, d DOUBLE, f FLOAT, s STRING, " +

    Nit (P3): The header promises domains for tinyint, smallint and timestamp_ntz columns, and isComparable accepts ByteType, ShortType and TimestampNTZType. But none of these schemas has such a column, and neither does ColumnarDataSourceSuite or the native test library. The gap is wider for tinyint and smallint: t = 1 compares CAST(t AS INT) in the analyzed plan that predicates reads, so the column only gets a domain after the optimizer's UnwrapCastInBinaryComparison. Dropping one of these types from isComparable, or a change that keeps the cast, would silently stop data skipping on such columns, and every suite would still pass.

    Cases for these types here would cover the derivation. An end-to-end case in which t = 1 on a tinyint column gets its domain after optimization would cover the cast unwrapping. For that case, the JVM test planner would have to report the column's domain, since today it only reads bigint bounds of the first column.

    Verification:

  • Regression: Filters such as t = 1 on a tinyint column and s < 10 on a smallint column of a pushdown scan push a domain for the column, and a timestamp_ntz comparison derives a domain with timestamp_ntz bounds.
  • HyukjinKwon HyukjinKwon commented on code on Nov 04, 2026 17:17 UTC
    Code Review
    sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnarTable.scala:1
    @@ -83,6 +85,7 @@ class ColumnarScanBuilder(
         schema: StructType,
         createDataSource: () => ColumnarDataSource)
       extends ScanBuilder
    +  with SupportsPushDownV2Filters

    Done in ad6187b, as recommended: the new internal mix-in EvaluatesAllPushedPredicates (in org.apache.spark.sql.internal.connector) tells PushDownUtils.pushFilters that a SupportsPushDownV2Filters builder returns all the predicates that it gets, and then the post-scan filters are the filters in the order of the query, nondeterministic ones included, instead of the translated ones first. ColumnarScanBuilder declares it, so this only changes native scans, with the flag on and off; other V2 sources keep their order. New test in ColumnarDataSourceSuite, "keep the order of the filters that Spark evaluates after a scan": rand(0) < 0.5 AND lower(name) LIKE '%e1%' keeps rand before the Contains with the flag on and off, and it fails without the mix-in.

    HyukjinKwon HyukjinKwon commented on code on Nov 04, 2026 17:17 UTC
    Code Review
    sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnDomains.scala:1
    @@ -0,0 +1,547 @@
    +/*
    + * 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.
    + */
    +package org.apache.spark.sql.execution.datasources.v2.columnar
    +
    +import scala.collection.mutable.ArrayBuffer
    +
    +import org.apache.spark.SparkException
    +import org.apache.spark.sql.catalyst.expressions.Literal
    +import org.apache.spark.sql.catalyst.types.PhysicalDataType
    +import org.apache.spark.sql.catalyst.util.quoteIfNeeded
    +import org.apache.spark.sql.connector.expressions.{Expression, LiteralValue, NamedReference}
    +import org.apache.spark.sql.connector.expressions.filter.Predicate
    +import org.apache.spark.sql.types._
    +import org.apache.spark.unsafe.types.UTF8String
    +
    +/**
    + * The values that a column can have in the rows that match the filters of a query: null if
    + * `nullAllowed`, NaN if `nanAllowed`, for a float or double column, and the other values in one
    + * of the `ranges`, or any of them without ranges. A data source can skip the data whose statistics
    + * show that it has no value in the domain of a column, but never a row whose values are in their
    + * domains: Spark evaluates the filters after reading anyway.
    + *
    + * @param path the index of the column in the read schema, and then the index of the field in each
    + *             struct, for a field of a struct
    + * @param name the names of the column and of its fields
    + * @param ranges sorted ranges, which neither overlap nor touch, of the values other than null and
    + *               NaN, in the internal representation of Spark. None if the column can have any of
    + *               them, and empty if it can have none.
    + */
    +case class ColumnDomain(
    +    path: Seq[Int],
    +    name: Seq[String],
    +    dataType: DataType,
    +    nullAllowed: Boolean,
    +    nanAllowed: Boolean,
    +    ranges: Option[Seq[ValueRange]]) {
    +
    +  private def ordering: Ordering[Any] = PhysicalDataType.ordering(dataType)
    +
    +  /** Whether the domain has the value, in the internal representation of Spark. */
    +  def contains(value: Any): Boolean = value match {
    +    case null => nullAllowed
    +    case f: Float if f.isNaN => nanAllowed
    +    case d: Double if d.isNaN => nanAllowed
    +    case _ => ranges.forall(_.exists(_.contains(value, ordering)))
    +  }
    +
    +  override def toString: String = {
    +    def literal(value: Any): String = Literal(value, dataType).sql
    +    val values = ranges match {
    +      case None => Seq("ANY")
    +      case Some(ranges) => ranges.map {
    +        case ValueRange(Some(low), true, Some(high), true) if ordering.equiv(low, high) =>
    +          literal(low)
    +        case range =>
    +          (if (range.lowInclusive) "[" else "(") + range.low.map(literal).getOrElse("-inf") +
    +            ", " + range.high.map(literal).getOrElse("+inf") +
    +            (if (range.highInclusive) "]" else ")")
    +      }
    +    }
    +    val special = (if (nullAllowed) Seq("NULL") else Nil) ++ (if (nanAllowed) Seq("NaN") else Nil)
    +    val all = special ++ values
    +    s"${name.map(quoteIfNeeded).mkString(".")}: ${if (all.isEmpty) "NONE" else all.mkString(", ")}"
    +  }
    +}
    +
    +/**
    + * A range of values in the internal representation of Spark: the values above `low`, or equal to
    + * it if `lowInclusive`, and below `high`, or equal to it if `highInclusive`. A bound that is None
    + * is unbounded, and is not inclusive.
    + */
    +case class ValueRange(low: Option[Any], lowInclusive: Boolean, high: Option[Any],
    +    highInclusive: Boolean) {
    +
    +  def contains(value: Any, ordering: Ordering[Any]): Boolean = {
    +    low.forall { l =>
    +      val c = ordering.compare(value, l)
    +      c > 0 || (c == 0 && lowInclusive)
    +    } && high.forall { h =>
    +      val c = ordering.compare(value, h)
    +      c < 0 || (c == 0 && highInclusive)
    +    }
    +  }
    +}
    +
    +/**
    + * The domains that a query passes to a data source, and the predicates that each of them comes
    + * from.
    + *
    + * @param domains the domains, at most one for each column, sorted by path
    + * @param columns the paths of the columns that each predicate constrains
    + */
    +case class ColumnDomains(domains: Seq[ColumnDomain], columns: Seq[Set[Seq[Int]]]) {
    +
    +  /**
    +   * Returns the predicates that constrain only the columns whose domains are used, given whether
    +   * the data source uses each domain.
    +   */
    +  def pushedPredicates(predicates: Array[Predicate], used: Seq[Boolean]): Array[Predicate] = {
    +    val usedPaths = domains.zip(used).collect { case (domain, true) => domain.path }.toSet
    +    predicates.zip(columns).collect {
    +      case (predicate, paths) if paths.nonEmpty && paths.subsetOf(usedPaths) => predicate
    +    }
    +  }
    +}
    +
    +/**
    + * Derives the domains of the columns that the predicates of a query constrain, the ones that Data
    + * Source V2 pushes to a scan, combined with AND. A domain is a superset of the values that a column
    + * has in the rows for which all the predicates are true: Spark derives it from the comparisons of
    + * a column with literals, IN, IS NULL, IS NOT NULL and STARTS_WITH, under AND, OR and NOT, with the
    + * semantics of Spark SQL. Comparisons with null are null, NaN is equal to NaN and greater than any
    + * other value, -0.0 is equal to 0.0, and strings and binary values are compared by their bytes, as
    + * unsigned bytes. A predicate that cannot be expressed this way does not constrain any column. Only
    + * the columns and the fields of structs of the types that a data source can compare get a domain:
    + * not the strings of a non-binary collation, nor arrays, maps and structs. A field of a struct only
    + * gets a domain that does not have null.
    + */
    +object ColumnDomains {
    +
    +  // A column that a predicate constrains, with its type.
    +  private case class Column(path: Seq[Int], name: Seq[String], dataType: DataType) {
    +    val ordering: Ordering[Any] = PhysicalDataType.ordering(dataType)
    +    val isFloating: Boolean = dataType == FloatType || dataType == DoubleType
    +  }
    +
    +  // The values that a column can have: see ColumnDomain.
    +  private case class Values(nullAllowed: Boolean, nanAllowed: Boolean,
    +      ranges: Option[Seq[ValueRange]])
    +
    +  private val NoValue = Values(nullAllowed = false, nanAllowed = false, Some(Nil))
    +  private val OnlyNull = Values(nullAllowed = true, nanAllowed = false, Some(Nil))
    +
    +  // The columns that the predicates constrain, with their values: a row can only make the
    +  // predicates true if each of these columns has one of the values. None when no row can.
    +  private type Constraint = Option[Map[Column, Values]]
    +  private val All: Constraint = Some(Map.empty)
    +  private val NoRow: Constraint = None
    +
    +  /** Derives the domains of the predicates for a scan of the schema. */
    +  def derive(predicates: Seq[Predicate], schema: StructType): ColumnDomains = {
    +    val constraints = predicates.map(constraint(_, negated = false, schema))
    +    val columns = constraints.map(_.map(_.keySet.map(_.path)).getOrElse(Set.empty[Seq[Int]]))
    +    val domains = constraints.foldLeft(All)(and) match {
    +      case Some(values) =>
    +        values.toSeq.collect {
    +          // A field of a struct is null in the rows where the struct, or a struct that contains it,
    +          // is null, which the statistics of its Arrow child array may not count as nulls. So a
    +          // field only gets a domain without null, which these rows never match.
    +          case (column, v) if column.path.length == 1 || !v.nullAllowed =>
    +            ColumnDomain(column.path, column.name, column.dataType, v.nullAllowed, v.nanAllowed,
    +              v.ranges)
    +        }.sortBy(_.path)(Ordering.Implicits.seqOrdering[Seq, Int])
    +      // A predicate that is always false, which Spark usually removes before it scans the data.
    +      case None => Nil
    +    }
    +    ColumnDomains(domains, columns)
    +  }
    +
    +  // The rows for which the predicate is true, or false if negated: NOT moves to the leaves.
    +  private def constraint(predicate: Predicate, negated: Boolean, schema: StructType): Constraint = {
    +    def child(i: Int): Option[Predicate] = predicate.children().lift(i).collect {
    +      case p: Predicate => p
    +    }
    +    def both(combine: (Constraint, Constraint) => Constraint, negated: Boolean): Constraint = {
    +      (child(0), child(1)) match {
    +        case (Some(left), Some(right)) =>
    +          combine(constraint(left, negated, schema), constraint(right, negated, schema))
    +        case _ => All
    +      }
    +    }
    +    predicate.name() match {
    +      case "AND" => if (negated) both(or, negated = true) else both(and, negated = false)
    +      case "OR" => if (negated) both(and, negated = true) else both(or, negated = false)
    +      case "NOT" => child(0).map(constraint(_, !negated, schema)).getOrElse(All)
    +      case "ALWAYS_TRUE" => if (negated) NoRow else All
    +      case "ALWAYS_FALSE" => if (negated) All else NoRow
    +      case _ => leaf(predicate, negated, schema).getOrElse(All)
    +    }
    +  }
    +
    +  private def leaf(
    +      predicate: Predicate,
    +      negated: Boolean,
    +      schema: StructType): Option[Constraint] = {
    +    val children = predicate.children()
    +    predicate.name() match {
    +      case "IS_NULL" | "IS_NOT_NULL" if children.length == 1 =>
    +        column(children(0), schema).map { col =>
    +          val isNull = (predicate.name() == "IS_NULL") != negated
    +          single(col, if (isNull) OnlyNull else anyValue(col))
    +        }
    +      case op @ ("=" | "<>" | "<=>" | "<" | "<=" | ">" | ">=") if children.length == 2 =>
    +        val operands = (column(children(0), schema), column(children(1), schema)) match {
    +          case (Some(col), _) => literal(children(1), col).map((col, _, op))
    +          case (_, Some(col)) => literal(children(0), col).map((col, _, flip(op)))
    +          case _ => None
    +        }
    +        operands.map { case (col, value, op) => compare(col, value, op, negated) }
    +      case "IN" if children.nonEmpty =>
    +        column(children(0), schema).flatMap { col =>
    +          val values = children.tail.map(literal(_, col))
    +          if (values.forall(_.isDefined)) Some(in(col, values.map(_.get).toSeq, negated)) else None
    +        }
    +      case "STARTS_WITH" if children.length == 2 =>
    +        column(children(0), schema).filter(_.dataType.isInstanceOf[StringType]).flatMap { col =>
    +          literal(children(1), col).map(prefix => startsWith(col, prefix, negated))
    +        }
    +      case _ => None
    +    }
    +  }
    +
    +  private def flip(op: String): String = op match {
    +    case "<" => ">"
    +    case "<=" => ">="
    +    case ">" => "<"
    +    case ">=" => "<="
    +    case other => other
    +  }
    +
    +  private def compare(column: Column, value: Any, op: String, negated: Boolean): Constraint = {
    +    // NOT (x <=> v) is true for null, unless v is null.
    +    val nullAllowed = op == "<=>" && negated && value != null
    +    if (value == null) {
    +      // A comparison with null is null, and so is its negation, but x <=> NULL is x IS NULL.
    +      if (op == "<=>") single(column, if (negated) anyValue(column) else OnlyNull)
    +      else single(column, NoValue)
    +    } else if (isNaN(value)) {
    +      // NaN is equal to NaN and greater than any other value: (NaN, other values).
    +      val (nan, others) = (op, negated) match {
    +        case ("=" | "<=>" | ">=", false) | ("<>" | "<", true) => (true, Some(Nil))
    +        case ("=" | "<=>" | ">=", true) | ("<>" | "<", false) => (false, None)
    +        case ("<=", false) | (">", true) => (true, None)
    +        case ("<=", true) | (">", false) => (false, Some(Nil))
    +        case _ => throw SparkException.internalError(s"Unexpected comparison $op.")
    +      }
    +      single(column, Values(nullAllowed, nan, others))
    +    } else {
    +      val v = normalize(value)
    +      // NaN is greater than v, and not equal to it.
    +      val (nan, ranges) = (op, negated) match {
    +        case ("=" | "<=>", false) | ("<>", true) => (false, Seq(point(v)))
    +        case ("=" | "<=>", true) | ("<>", false) =>
    +          (true, Seq(below(v, inclusive = false), above(v, inclusive = false)))
    +        case ("<", false) | (">=", true) => (false, Seq(below(v, inclusive = false)))
    +        case ("<=", false) | (">", true) => (false, Seq(below(v, inclusive = true)))
    +        case (">", false) | ("<=", true) => (true, Seq(above(v, inclusive = false)))
    +        case (">=", false) | ("<", true) => (true, Seq(above(v, inclusive = true)))
    +        case _ => throw SparkException.internalError(s"Unexpected comparison $op.")
    +      }
    +      single(column, Values(nullAllowed, nan, Some(ranges)))
    +    }
    +  }
    +
    +  private def in(column: Column, values: Seq[Any], negated: Boolean): Constraint = {
    +    val nonNull = values.filter(_ != null)
    +    val hasNaN = nonNull.exists(isNaN)
    +    val points = nonNull.filterNot(isNaN).map(normalize).sorted(column.ordering)
    +      .foldLeft(List.empty[Any]) {
    +        case (last :: rest, v) if column.ordering.equiv(last, v) => last :: rest
    +        case (acc, v) => v :: acc
    +      }.reverse
    +    if (values.isEmpty) {
    +      // x IN () is false, also for null, unless spark.sql.legacy.nullInEmptyListBehavior makes it
    +      // null for null. So it is never true, and NOT (x IN ()) is true for any value, and by
    +      // default for null.
    +      if (negated) All else single(column, NoValue)
    +    } else if (!negated) {
    +      single(column, Values(nullAllowed = false, hasNaN, Some(points.map(point))))
    +    } else if (nonNull.length < values.length) {
    +      // NOT (x IN (..., NULL)) is never true: it is false or null.
    +      single(column, NoValue)
    +    } else if (points.isEmpty) {
    +      // NOT (x IN (NaN)) is true for the values other than NaN.
    +      single(column, Values(nullAllowed = false, !hasNaN, None))
    +    } else {
    +      // The values between the points.
    +      val bounds = None +: points.map(Some(_)) :+ None
    +      val gaps = bounds.zip(bounds.tail).map { case (low, high) =>
    +        ValueRange(low, lowInclusive = false, high = high, highInclusive = false)
    +      }
    +      single(column, Values(nullAllowed = false, !hasNaN, Some(gaps)))
    +    }
    +  }
    +
    +  private def startsWith(column: Column, prefix: Any, negated: Boolean): Constraint = {
    +    (prefix, negated) match {
    +      case (null, _) => single(column, NoValue)
    +      // The strings that do not start with the prefix are not a range. A value whose bytes are not
    +      // valid UTF-8 could even be in the range of the strings that do.
    +      case (_, true) => single(column, anyValue(column))
    +      case (prefix: UTF8String, false) if prefix.numBytes() == 0 => single(column, anyValue(column))
    +      case (prefix: UTF8String, false) =>
    +        val range = ValueRange(Some(prefix), lowInclusive = true, high = nextPrefix(prefix),
    +          highInclusive = false)
    +        single(column, Values(nullAllowed = false, nanAllowed = false, Some(Seq(range))))
    +      case _ => All
    +    }
    +  }
    +
    +  /**
    +   * Returns the smallest string that is greater than all the strings that start with the prefix,
    +   * in the order of their UTF-8 bytes, which is the order of their code points, or None if there
    +   * is none: the prefix with its last code point incremented, after dropping the trailing
    +   * U+10FFFF, the largest code point.
    +   */
    +  private[columnar] def nextPrefix(prefix: UTF8String): Option[UTF8String] = {
    +    val codePoints = prefix.toString.codePoints().toArray.toBuffer
    +    while (codePoints.nonEmpty && codePoints.last == Character.MAX_CODE_POINT) {
    +      codePoints.remove(codePoints.length - 1)
    +    }
    +    if (codePoints.isEmpty) {
    +      None
    +    } else {
    +      val last = codePoints.last + 1
    +      // Skips the surrogates, which are not code points of characters.
    +      codePoints(codePoints.length - 1) =
    +        if (last >= Character.MIN_SURROGATE && last <= Character.MAX_SURROGATE) {
    +          Character.MAX_SURROGATE + 1
    +        } else {
    +          last
    +        }
    +      Some(UTF8String.fromString(new String(codePoints.toArray, 0, codePoints.length)))
    +    }
    +  }
    +
    +  private def single(column: Column, values: Values): Constraint = {
    +    // Only floating-point columns have NaN.
    +    val normalized = values.copy(nanAllowed = values.nanAllowed && column.isFloating)
    +    if (isAll(column, normalized)) All else Some(Map(column -> normalized))
    +  }
    +
    +  private def point(v: Any): ValueRange =
    +    ValueRange(Some(v), lowInclusive = true, high = Some(v), highInclusive = true)
    +
    +  private def below(v: Any, inclusive: Boolean): ValueRange =
    +    ValueRange(None, lowInclusive = false, high = Some(v), highInclusive = inclusive)
    +
    +  private def above(v: Any, inclusive: Boolean): ValueRange =
    +    ValueRange(Some(v), lowInclusive = inclusive, high = None, highInclusive = false)
    +
    +  private def anyValue(column: Column): Values = {
    +    Values(nullAllowed = false, nanAllowed = column.isFloating, None)
    +  }
    +
    +  private def isAll(column: Column, values: Values): Boolean = {
    +    values.nullAllowed && values.ranges.isEmpty && (values.nanAllowed || !column.isFloating)
    +  }
    +
    +  private def isEmpty(values: Values): Boolean = {
    +    !values.nullAllowed && !values.nanAllowed && values.ranges.exists(_.isEmpty)
    +  }
    +
    +  // Whether no row can make the predicates true.
    +  private def matchesNoRow(constraint: Constraint): Boolean = {
    +    constraint.forall(_.values.exists(isEmpty))
    +  }
    +
    +  private def and(left: Constraint, right: Constraint): Constraint = (left, right) match {
    +    case (Some(l), Some(r)) =>
    +      Some((l.keySet ++ r.keySet).map { column =>

    Done in ad6187b: and builds its map through an iterator, so only the columns are hashed. or became a single merge of all the disjuncts (see the next comment), which builds its map the same way. The new test "the domains of long chains of ORs, and of IN lists with other columns" also combines an IN list of 20,000 values with predicates on five other columns.

    HyukjinKwon HyukjinKwon commented on code on Nov 04, 2026 17:17 UTC
    Code Review
    sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnDomains.scala:1
    @@ -0,0 +1,547 @@
    +/*
    + * 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.
    + */
    +package org.apache.spark.sql.execution.datasources.v2.columnar
    +
    +import scala.collection.mutable.ArrayBuffer
    +
    +import org.apache.spark.SparkException
    +import org.apache.spark.sql.catalyst.expressions.Literal
    +import org.apache.spark.sql.catalyst.types.PhysicalDataType
    +import org.apache.spark.sql.catalyst.util.quoteIfNeeded
    +import org.apache.spark.sql.connector.expressions.{Expression, LiteralValue, NamedReference}
    +import org.apache.spark.sql.connector.expressions.filter.Predicate
    +import org.apache.spark.sql.types._
    +import org.apache.spark.unsafe.types.UTF8String
    +
    +/**
    + * The values that a column can have in the rows that match the filters of a query: null if
    + * `nullAllowed`, NaN if `nanAllowed`, for a float or double column, and the other values in one
    + * of the `ranges`, or any of them without ranges. A data source can skip the data whose statistics
    + * show that it has no value in the domain of a column, but never a row whose values are in their
    + * domains: Spark evaluates the filters after reading anyway.
    + *
    + * @param path the index of the column in the read schema, and then the index of the field in each
    + *             struct, for a field of a struct
    + * @param name the names of the column and of its fields
    + * @param ranges sorted ranges, which neither overlap nor touch, of the values other than null and
    + *               NaN, in the internal representation of Spark. None if the column can have any of
    + *               them, and empty if it can have none.
    + */
    +case class ColumnDomain(
    +    path: Seq[Int],
    +    name: Seq[String],
    +    dataType: DataType,
    +    nullAllowed: Boolean,
    +    nanAllowed: Boolean,
    +    ranges: Option[Seq[ValueRange]]) {
    +
    +  private def ordering: Ordering[Any] = PhysicalDataType.ordering(dataType)
    +
    +  /** Whether the domain has the value, in the internal representation of Spark. */
    +  def contains(value: Any): Boolean = value match {
    +    case null => nullAllowed
    +    case f: Float if f.isNaN => nanAllowed
    +    case d: Double if d.isNaN => nanAllowed
    +    case _ => ranges.forall(_.exists(_.contains(value, ordering)))
    +  }
    +
    +  override def toString: String = {
    +    def literal(value: Any): String = Literal(value, dataType).sql
    +    val values = ranges match {
    +      case None => Seq("ANY")
    +      case Some(ranges) => ranges.map {
    +        case ValueRange(Some(low), true, Some(high), true) if ordering.equiv(low, high) =>
    +          literal(low)
    +        case range =>
    +          (if (range.lowInclusive) "[" else "(") + range.low.map(literal).getOrElse("-inf") +
    +            ", " + range.high.map(literal).getOrElse("+inf") +
    +            (if (range.highInclusive) "]" else ")")
    +      }
    +    }
    +    val special = (if (nullAllowed) Seq("NULL") else Nil) ++ (if (nanAllowed) Seq("NaN") else Nil)
    +    val all = special ++ values
    +    s"${name.map(quoteIfNeeded).mkString(".")}: ${if (all.isEmpty) "NONE" else all.mkString(", ")}"
    +  }
    +}
    +
    +/**
    + * A range of values in the internal representation of Spark: the values above `low`, or equal to
    + * it if `lowInclusive`, and below `high`, or equal to it if `highInclusive`. A bound that is None
    + * is unbounded, and is not inclusive.
    + */
    +case class ValueRange(low: Option[Any], lowInclusive: Boolean, high: Option[Any],
    +    highInclusive: Boolean) {
    +
    +  def contains(value: Any, ordering: Ordering[Any]): Boolean = {
    +    low.forall { l =>
    +      val c = ordering.compare(value, l)
    +      c > 0 || (c == 0 && lowInclusive)
    +    } && high.forall { h =>
    +      val c = ordering.compare(value, h)
    +      c < 0 || (c == 0 && highInclusive)
    +    }
    +  }
    +}
    +
    +/**
    + * The domains that a query passes to a data source, and the predicates that each of them comes
    + * from.
    + *
    + * @param domains the domains, at most one for each column, sorted by path
    + * @param columns the paths of the columns that each predicate constrains
    + */
    +case class ColumnDomains(domains: Seq[ColumnDomain], columns: Seq[Set[Seq[Int]]]) {
    +
    +  /**
    +   * Returns the predicates that constrain only the columns whose domains are used, given whether
    +   * the data source uses each domain.
    +   */
    +  def pushedPredicates(predicates: Array[Predicate], used: Seq[Boolean]): Array[Predicate] = {
    +    val usedPaths = domains.zip(used).collect { case (domain, true) => domain.path }.toSet
    +    predicates.zip(columns).collect {
    +      case (predicate, paths) if paths.nonEmpty && paths.subsetOf(usedPaths) => predicate
    +    }
    +  }
    +}
    +
    +/**
    + * Derives the domains of the columns that the predicates of a query constrain, the ones that Data
    + * Source V2 pushes to a scan, combined with AND. A domain is a superset of the values that a column
    + * has in the rows for which all the predicates are true: Spark derives it from the comparisons of
    + * a column with literals, IN, IS NULL, IS NOT NULL and STARTS_WITH, under AND, OR and NOT, with the
    + * semantics of Spark SQL. Comparisons with null are null, NaN is equal to NaN and greater than any
    + * other value, -0.0 is equal to 0.0, and strings and binary values are compared by their bytes, as
    + * unsigned bytes. A predicate that cannot be expressed this way does not constrain any column. Only
    + * the columns and the fields of structs of the types that a data source can compare get a domain:
    + * not the strings of a non-binary collation, nor arrays, maps and structs. A field of a struct only
    + * gets a domain that does not have null.
    + */
    +object ColumnDomains {
    +
    +  // A column that a predicate constrains, with its type.
    +  private case class Column(path: Seq[Int], name: Seq[String], dataType: DataType) {
    +    val ordering: Ordering[Any] = PhysicalDataType.ordering(dataType)
    +    val isFloating: Boolean = dataType == FloatType || dataType == DoubleType
    +  }
    +
    +  // The values that a column can have: see ColumnDomain.
    +  private case class Values(nullAllowed: Boolean, nanAllowed: Boolean,
    +      ranges: Option[Seq[ValueRange]])
    +
    +  private val NoValue = Values(nullAllowed = false, nanAllowed = false, Some(Nil))
    +  private val OnlyNull = Values(nullAllowed = true, nanAllowed = false, Some(Nil))
    +
    +  // The columns that the predicates constrain, with their values: a row can only make the
    +  // predicates true if each of these columns has one of the values. None when no row can.
    +  private type Constraint = Option[Map[Column, Values]]
    +  private val All: Constraint = Some(Map.empty)
    +  private val NoRow: Constraint = None
    +
    +  /** Derives the domains of the predicates for a scan of the schema. */
    +  def derive(predicates: Seq[Predicate], schema: StructType): ColumnDomains = {
    +    val constraints = predicates.map(constraint(_, negated = false, schema))
    +    val columns = constraints.map(_.map(_.keySet.map(_.path)).getOrElse(Set.empty[Seq[Int]]))
    +    val domains = constraints.foldLeft(All)(and) match {
    +      case Some(values) =>
    +        values.toSeq.collect {
    +          // A field of a struct is null in the rows where the struct, or a struct that contains it,
    +          // is null, which the statistics of its Arrow child array may not count as nulls. So a
    +          // field only gets a domain without null, which these rows never match.
    +          case (column, v) if column.path.length == 1 || !v.nullAllowed =>
    +            ColumnDomain(column.path, column.name, column.dataType, v.nullAllowed, v.nanAllowed,
    +              v.ranges)
    +        }.sortBy(_.path)(Ordering.Implicits.seqOrdering[Seq, Int])
    +      // A predicate that is always false, which Spark usually removes before it scans the data.
    +      case None => Nil
    +    }
    +    ColumnDomains(domains, columns)
    +  }
    +
    +  // The rows for which the predicate is true, or false if negated: NOT moves to the leaves.
    +  private def constraint(predicate: Predicate, negated: Boolean, schema: StructType): Constraint = {
    +    def child(i: Int): Option[Predicate] = predicate.children().lift(i).collect {
    +      case p: Predicate => p
    +    }
    +    def both(combine: (Constraint, Constraint) => Constraint, negated: Boolean): Constraint = {
    +      (child(0), child(1)) match {
    +        case (Some(left), Some(right)) =>
    +          combine(constraint(left, negated, schema), constraint(right, negated, schema))
    +        case _ => All
    +      }
    +    }
    +    predicate.name() match {
    +      case "AND" => if (negated) both(or, negated = true) else both(and, negated = false)
    +      case "OR" => if (negated) both(and, negated = true) else both(or, negated = false)
    +      case "NOT" => child(0).map(constraint(_, !negated, schema)).getOrElse(All)
    +      case "ALWAYS_TRUE" => if (negated) NoRow else All
    +      case "ALWAYS_FALSE" => if (negated) All else NoRow
    +      case _ => leaf(predicate, negated, schema).getOrElse(All)
    +    }
    +  }
    +
    +  private def leaf(
    +      predicate: Predicate,
    +      negated: Boolean,
    +      schema: StructType): Option[Constraint] = {
    +    val children = predicate.children()
    +    predicate.name() match {
    +      case "IS_NULL" | "IS_NOT_NULL" if children.length == 1 =>
    +        column(children(0), schema).map { col =>
    +          val isNull = (predicate.name() == "IS_NULL") != negated
    +          single(col, if (isNull) OnlyNull else anyValue(col))
    +        }
    +      case op @ ("=" | "<>" | "<=>" | "<" | "<=" | ">" | ">=") if children.length == 2 =>
    +        val operands = (column(children(0), schema), column(children(1), schema)) match {
    +          case (Some(col), _) => literal(children(1), col).map((col, _, op))
    +          case (_, Some(col)) => literal(children(0), col).map((col, _, flip(op)))
    +          case _ => None
    +        }
    +        operands.map { case (col, value, op) => compare(col, value, op, negated) }
    +      case "IN" if children.nonEmpty =>
    +        column(children(0), schema).flatMap { col =>
    +          val values = children.tail.map(literal(_, col))
    +          if (values.forall(_.isDefined)) Some(in(col, values.map(_.get).toSeq, negated)) else None
    +        }
    +      case "STARTS_WITH" if children.length == 2 =>
    +        column(children(0), schema).filter(_.dataType.isInstanceOf[StringType]).flatMap { col =>
    +          literal(children(1), col).map(prefix => startsWith(col, prefix, negated))
    +        }
    +      case _ => None
    +    }
    +  }
    +
    +  private def flip(op: String): String = op match {
    +    case "<" => ">"
    +    case "<=" => ">="
    +    case ">" => "<"
    +    case ">=" => "<="
    +    case other => other
    +  }
    +
    +  private def compare(column: Column, value: Any, op: String, negated: Boolean): Constraint = {
    +    // NOT (x <=> v) is true for null, unless v is null.
    +    val nullAllowed = op == "<=>" && negated && value != null
    +    if (value == null) {
    +      // A comparison with null is null, and so is its negation, but x <=> NULL is x IS NULL.
    +      if (op == "<=>") single(column, if (negated) anyValue(column) else OnlyNull)
    +      else single(column, NoValue)
    +    } else if (isNaN(value)) {
    +      // NaN is equal to NaN and greater than any other value: (NaN, other values).
    +      val (nan, others) = (op, negated) match {
    +        case ("=" | "<=>" | ">=", false) | ("<>" | "<", true) => (true, Some(Nil))
    +        case ("=" | "<=>" | ">=", true) | ("<>" | "<", false) => (false, None)
    +        case ("<=", false) | (">", true) => (true, None)
    +        case ("<=", true) | (">", false) => (false, Some(Nil))
    +        case _ => throw SparkException.internalError(s"Unexpected comparison $op.")
    +      }
    +      single(column, Values(nullAllowed, nan, others))
    +    } else {
    +      val v = normalize(value)
    +      // NaN is greater than v, and not equal to it.
    +      val (nan, ranges) = (op, negated) match {
    +        case ("=" | "<=>", false) | ("<>", true) => (false, Seq(point(v)))
    +        case ("=" | "<=>", true) | ("<>", false) =>
    +          (true, Seq(below(v, inclusive = false), above(v, inclusive = false)))
    +        case ("<", false) | (">=", true) => (false, Seq(below(v, inclusive = false)))
    +        case ("<=", false) | (">", true) => (false, Seq(below(v, inclusive = true)))
    +        case (">", false) | ("<=", true) => (true, Seq(above(v, inclusive = false)))
    +        case (">=", false) | ("<", true) => (true, Seq(above(v, inclusive = true)))
    +        case _ => throw SparkException.internalError(s"Unexpected comparison $op.")
    +      }
    +      single(column, Values(nullAllowed, nan, Some(ranges)))
    +    }
    +  }
    +
    +  private def in(column: Column, values: Seq[Any], negated: Boolean): Constraint = {
    +    val nonNull = values.filter(_ != null)
    +    val hasNaN = nonNull.exists(isNaN)
    +    val points = nonNull.filterNot(isNaN).map(normalize).sorted(column.ordering)
    +      .foldLeft(List.empty[Any]) {
    +        case (last :: rest, v) if column.ordering.equiv(last, v) => last :: rest
    +        case (acc, v) => v :: acc
    +      }.reverse
    +    if (values.isEmpty) {
    +      // x IN () is false, also for null, unless spark.sql.legacy.nullInEmptyListBehavior makes it
    +      // null for null. So it is never true, and NOT (x IN ()) is true for any value, and by
    +      // default for null.
    +      if (negated) All else single(column, NoValue)
    +    } else if (!negated) {
    +      single(column, Values(nullAllowed = false, hasNaN, Some(points.map(point))))
    +    } else if (nonNull.length < values.length) {
    +      // NOT (x IN (..., NULL)) is never true: it is false or null.
    +      single(column, NoValue)
    +    } else if (points.isEmpty) {
    +      // NOT (x IN (NaN)) is true for the values other than NaN.
    +      single(column, Values(nullAllowed = false, !hasNaN, None))
    +    } else {
    +      // The values between the points.
    +      val bounds = None +: points.map(Some(_)) :+ None
    +      val gaps = bounds.zip(bounds.tail).map { case (low, high) =>
    +        ValueRange(low, lowInclusive = false, high = high, highInclusive = false)
    +      }
    +      single(column, Values(nullAllowed = false, !hasNaN, Some(gaps)))
    +    }
    +  }
    +
    +  private def startsWith(column: Column, prefix: Any, negated: Boolean): Constraint = {
    +    (prefix, negated) match {
    +      case (null, _) => single(column, NoValue)
    +      // The strings that do not start with the prefix are not a range. A value whose bytes are not
    +      // valid UTF-8 could even be in the range of the strings that do.
    +      case (_, true) => single(column, anyValue(column))
    +      case (prefix: UTF8String, false) if prefix.numBytes() == 0 => single(column, anyValue(column))
    +      case (prefix: UTF8String, false) =>
    +        val range = ValueRange(Some(prefix), lowInclusive = true, high = nextPrefix(prefix),
    +          highInclusive = false)
    +        single(column, Values(nullAllowed = false, nanAllowed = false, Some(Seq(range))))
    +      case _ => All
    +    }
    +  }
    +
    +  /**
    +   * Returns the smallest string that is greater than all the strings that start with the prefix,
    +   * in the order of their UTF-8 bytes, which is the order of their code points, or None if there
    +   * is none: the prefix with its last code point incremented, after dropping the trailing
    +   * U+10FFFF, the largest code point.
    +   */
    +  private[columnar] def nextPrefix(prefix: UTF8String): Option[UTF8String] = {
    +    val codePoints = prefix.toString.codePoints().toArray.toBuffer
    +    while (codePoints.nonEmpty && codePoints.last == Character.MAX_CODE_POINT) {
    +      codePoints.remove(codePoints.length - 1)
    +    }
    +    if (codePoints.isEmpty) {
    +      None
    +    } else {
    +      val last = codePoints.last + 1
    +      // Skips the surrogates, which are not code points of characters.
    +      codePoints(codePoints.length - 1) =
    +        if (last >= Character.MIN_SURROGATE && last <= Character.MAX_SURROGATE) {
    +          Character.MAX_SURROGATE + 1
    +        } else {
    +          last
    +        }
    +      Some(UTF8String.fromString(new String(codePoints.toArray, 0, codePoints.length)))
    +    }
    +  }
    +
    +  private def single(column: Column, values: Values): Constraint = {
    +    // Only floating-point columns have NaN.
    +    val normalized = values.copy(nanAllowed = values.nanAllowed && column.isFloating)
    +    if (isAll(column, normalized)) All else Some(Map(column -> normalized))
    +  }
    +
    +  private def point(v: Any): ValueRange =
    +    ValueRange(Some(v), lowInclusive = true, high = Some(v), highInclusive = true)
    +
    +  private def below(v: Any, inclusive: Boolean): ValueRange =
    +    ValueRange(None, lowInclusive = false, high = Some(v), highInclusive = inclusive)
    +
    +  private def above(v: Any, inclusive: Boolean): ValueRange =
    +    ValueRange(Some(v), lowInclusive = inclusive, high = None, highInclusive = false)
    +
    +  private def anyValue(column: Column): Values = {
    +    Values(nullAllowed = false, nanAllowed = column.isFloating, None)
    +  }
    +
    +  private def isAll(column: Column, values: Values): Boolean = {
    +    values.nullAllowed && values.ranges.isEmpty && (values.nanAllowed || !column.isFloating)
    +  }
    +
    +  private def isEmpty(values: Values): Boolean = {
    +    !values.nullAllowed && !values.nanAllowed && values.ranges.exists(_.isEmpty)
    +  }
    +
    +  // Whether no row can make the predicates true.
    +  private def matchesNoRow(constraint: Constraint): Boolean = {
    +    constraint.forall(_.values.exists(isEmpty))
    +  }
    +
    +  private def and(left: Constraint, right: Constraint): Constraint = (left, right) match {
    +    case (Some(l), Some(r)) =>
    +      Some((l.keySet ++ r.keySet).map { column =>
    +        column -> ((l.get(column), r.get(column)) match {
    +          case (Some(a), Some(b)) => intersect(column, a, b)
    +          case (a, b) => a.orElse(b).get
    +        })
    +      }.toMap)
    +    case _ => NoRow
    +  }
    +
    +  // A column that only one side constrains can have any value in the rows of the other side, so
    +  // only the columns that both sides constrain are constrained.
    +  private def or(left: Constraint, right: Constraint): Constraint = {
    +    if (matchesNoRow(left)) {
    +      right
    +    } else if (matchesNoRow(right)) {
    +      left
    +    } else {
    +      val (l, r) = (left.get, right.get)
    +      Some(l.keySet.intersect(r.keySet).map(column => column -> union(column, l(column), r(column)))
    +        .filterNot { case (column, values) => isAll(column, values) }.toMap)
    +    }
    +  }
    +
    +  private def intersect(column: Column, a: Values, b: Values): Values = Values(
    +    a.nullAllowed && b.nullAllowed,
    +    a.nanAllowed && b.nanAllowed,
    +    (a.ranges, b.ranges) match {
    +      case (Some(x), Some(y)) => Some(intersectRanges(x, y, column.ordering))
    +      case (x, y) => x.orElse(y)
    +    })
    +
    +  private def union(column: Column, a: Values, b: Values): Values = Values(
    +    a.nullAllowed || b.nullAllowed,
    +    a.nanAllowed || b.nanAllowed,
    +    (a.ranges, b.ranges) match {
    +      case (Some(x), Some(y)) =>
    +        unionRanges(x, y, column.ordering) match {
    +          // All the values.
    +          case Seq(ValueRange(None, _, None, _)) => None
    +          case ranges => Some(ranges)
    +        }
    +      case _ => None
    +    })
    +
    +  // A negative value when `a` starts before `b`.
    +  private def compareLows(a: ValueRange, b: ValueRange, ordering: Ordering[Any]): Int = {
    +    (a.low, b.low) match {
    +      case (None, None) => 0
    +      case (None, _) => -1
    +      case (_, None) => 1
    +      case (Some(x), Some(y)) =>
    +        val c = ordering.compare(x, y)
    +        if (c != 0 || a.lowInclusive == b.lowInclusive) c else if (a.lowInclusive) -1 else 1
    +    }
    +  }
    +
    +  // A negative value when `a` ends before `b`.
    +  private def compareHighs(a: ValueRange, b: ValueRange, ordering: Ordering[Any]): Int = {
    +    (a.high, b.high) match {
    +      case (None, None) => 0
    +      case (None, _) => 1
    +      case (_, None) => -1
    +      case (Some(x), Some(y)) =>
    +        val c = ordering.compare(x, y)
    +        if (c != 0 || a.highInclusive == b.highInclusive) c else if (a.highInclusive) 1 else -1
    +    }
    +  }
    +
    +  private def isEmptyRange(range: ValueRange, ordering: Ordering[Any]): Boolean = {
    +    (range.low, range.high) match {
    +      case (Some(low), Some(high)) =>
    +        val c = ordering.compare(low, high)
    +        c > 0 || (c == 0 && !(range.lowInclusive && range.highInclusive))
    +      case _ => false
    +    }
    +  }
    +
    +  // Intersects two lists of sorted ranges that neither overlap nor touch, by sweeping them.
    +  private def intersectRanges(
    +      left: Seq[ValueRange],
    +      right: Seq[ValueRange],
    +      ordering: Ordering[Any]): Seq[ValueRange] = {
    +    // The ranges are usually lists, such as those of IN, so the sweep indexes copies of them.
    +    val (a, b) = (left.toIndexedSeq, right.toIndexedSeq)
    +    val result = ArrayBuffer.empty[ValueRange]
    +    var i = 0
    +    var j = 0
    +    while (i < a.length && j < b.length) {
    +      val (x, y) = (a(i), b(j))
    +      val low = if (compareLows(x, y, ordering) >= 0) x else y
    +      val high = if (compareHighs(x, y, ordering) <= 0) x else y
    +      val range = ValueRange(low.low, low.lowInclusive, high.high, high.highInclusive)
    +      if (!isEmptyRange(range, ordering)) {
    +        result += range
    +      }
    +      // Moves past the range that ends first.
    +      if (compareHighs(x, y, ordering) <= 0) i += 1 else j += 1
    +    }
    +    result.toSeq
    +  }
    +
    +  // Merges two lists of sorted ranges, and the ranges that overlap or touch, such as [1, 2) and
    +  // [2, 3].
    +  private def unionRanges(
    +      a: Seq[ValueRange],
    +      b: Seq[ValueRange],
    +      ordering: Ordering[Any]): Seq[ValueRange] = {
    +    def touches(first: ValueRange, next: ValueRange): Boolean = (first.high, next.low) match {
    +      case (Some(high), Some(low)) =>
    +        val c = ordering.compare(low, high)
    +        c < 0 || (c == 0 && (first.highInclusive || next.lowInclusive))
    +      case _ => true
    +    }
    +    (a ++ b).sortWith(compareLows(_, _, ordering) < 0).foldLeft(List.empty[ValueRange]) {

    Done in ad6187b: constraint collects the disjuncts of a chain of ORs, and of ANDs under NOT, with nested NOTs, using a stack of its own (a chain of 20,000 ORs is deeper than the stack of the thread), and orAll merges them at once: the columns that all the disjuncts constrain, with one sort of all their ranges. It keeps the rules of the pairwise version: a disjunct that matches no row adds no row, and a column that only some disjuncts constrain is not constrained. New test: a left-deep chain of 20,000 equalities, as reduce(_ || _) builds it, gives the domain of the IN list of the same values, and NOT of a chain of <> gives the points.

    HyukjinKwon HyukjinKwon commented on code on Nov 04, 2026 17:17 UTC
    Code Review
    docs/sql-native-data-sources.md:1
    @@ -169,12 +170,67 @@ a write that runs for long, or blocks, for example on network I/O, should check
     regularly and use timeouts. The task reaper, `spark.task.reaper.enabled` and
     `spark.task.reaper.killTimeout`, kills an executor whose killed task does not end.
     
    +### Filter Pushdown
    +
    +Spark does not pass the filters of a query to a library as expressions, which a library would have
    +to evaluate with the exact semantics of Spark SQL. It passes the *domains* of the columns that the
    +filters constrain instead: for each column, the values that it can have in the rows that match,
    +which a library compares with the statistics of its data to skip what cannot match, such as files,
    +row groups or blocks. With `push_domains`, a reader gets a `SparkDsDomain` for each column, with:
    +
    +- `path`: the index of the column in the schema to read, and then the index of the field in each
    +  struct, for a field of a struct;
    +- `null_allowed` and `nan_allowed`: whether null and NaN are in the domain;
    +- `ranges`: the ranges of the other values in the domain, as a struct array whose fields are
    +  `low` and `high`, of the Arrow type of the column, with a null bound for no bound, and
    +  `low_inclusive` and `high_inclusive`. The ranges are sorted and do not overlap. A single value
    +  is a range whose bounds are equal and inclusive, and `ranges` is `NULL` when all the other
    +  values are in the domain.
    +
    +For example:
    +
    +| Filter | Domain |
    +|--------|--------|
    +| `id > 5 AND id <= 10` | `id`: `(5, 10]` |
    +| `id IN (1, 3) OR id IS NULL` | `id`: null, `[1, 1]`, `[3, 3]` |
    +| `NOT (id = 5)` | `id`: `(-inf, 5)`, `(5, +inf)` |
    +| `value > 1.5`, for a `double` column | `value`: NaN, `(1.5, +inf)` |
    +| `name LIKE 'ab%'`, which is `STARTS_WITH(name, 'ab')` | `name`: `['ab', 'ac')` |
    +| `s.x = 1 AND name IS NOT NULL` | `s.x`: `[1, 1]`; `name`: all the values but null |
    +| `id > 5 OR name = 'a'` | none: each side only constrains one of the columns |
    +
    +Spark derives the domains from the comparisons of a column with literals (`=`, `<>`, `<=>`, `<`,
    +`<=`, `>`, `>=`), `IN`, `IS NULL`, `IS NOT NULL` and `STARTS_WITH`, combined with `AND`, `OR` and
    +`NOT`, with the semantics of Spark SQL: comparisons with null are null, so that
    +`NOT (id IN (1, NULL))` matches no row, NaN is equal to NaN and greater than any other value, and
    +-0.0 is equal to 0.0. A domain has all the values of its column in the rows for which the filters
    +are true, and may have others: a column that only one side of an `OR` constrains gets no domain
    +from it, and the other filters, such as `id + 1 > 5`, `a = b` or `ENDS_WITH(name, 'x')`, constrain
    +no column. Columns of strings with a non-binary collation, such as `UTF8_LCASE`, and arrays, maps
    +and structs, get no domain. A field of a struct is null in the rows where the struct, or a struct
    +that contains it, is null, whatever the Arrow child array of the field holds there, so statistics
    +computed from that array may not count these rows as nulls: Spark only passes domains without null
    +for the fields of structs.
    +
    +A library compares values with the order of Spark SQL: numbers, dates and timestamps by their
    +values, with -0.0 equal to 0.0 (use IEEE 754 comparisons, not a total order such as
    +`f64::total_cmp`), strings by their UTF-8 bytes, binary values as unsigned bytes, and false before
    +true. It must never skip a row whose values are all in their domains, which Spark cannot detect,
    +but it can return rows that are not: Spark evaluates all the filters again after reading. So a
    +library only uses the domains to read less data, and Spark does not push a `LIMIT` down with a
    +filter. The library sets `used` to whether it uses each domain, and the plan of the query shows the

    Fixed in ad6187b: the guide now says that the formatted plan (EXPLAIN FORMATTED, or df.explain("formatted")) and the SQL tab of the Spark UI show PushedFilters and PushedDomains, and the comment of used in spark_datasource.h says the same.

    Reviewers
    Assignees
    HyukjinKwon HyukjinKwon
    Labels
    risk: low confidence: 92.6% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 62.1% (MEDIUM) · Higher = larger blast radius
    62.1%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 92.6% · Lower = rushed or shallow review
    92.6%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 4.6% · Safe to merge
    4.6%
    Repository