Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ The playground config holds `[[catalogs]]` entries with `name`, `type` (`rest` o

`FileScanTaskProviderBuilder` converts the projection to column names and the filters to a single Iceberg `Predicate` (`read/predicate.rs`). Lazy discovery advertises the session's target partition count and shares one discovery stream per execution. In a parallel lazy scan, a producer sends planned file tasks to one unbounded Flume queue. Each partition takes a receiver on first poll; a late reader can claim remaining tasks without restarting discovery. A single-partition scan reads directly without a queue. Use DataFusion's `reset_plan_states` to run the same parallel scan again; partition-open order is not an execution boundary. `IcebergDataSource` reads tasks with a shared `ArrowReader` and applies fetch per partition. Eager planning still collects tasks into round-robin groups.

The base table provider reports every filter as `Inexact`, so DataFusion re-applies the original filters after the scan. The pushed-down predicate therefore only has to be *implied by* the original filter. It may match extra rows but must never drop a row that matches. Unconvertible parts are dropped: an `AND` keeps whichever side converted, while an `OR` needs both sides. Preserve this soundness rule when extending `predicate.rs`; for example, it is why casts and some NaN arithmetic are deliberately not pushed down. Removing a cast is left to DataFusion's simplifier (`unwrap_cast_in_comparison`), which rewrites a comparison only when the result doesn't change.
The base table provider reports every filter as `Inexact`, so DataFusion re-applies the original filters after the scan. The pushed-down predicate therefore only has to be *implied by* the original filter. It may match extra rows but must never drop a row that matches. Unconvertible parts are dropped: an `AND` keeps whichever side converted, while an `OR` needs both sides. Preserve this soundness rule when extending `predicate.rs`; for example, it is why casts and some NaN arithmetic are deliberately not pushed down. Comparisons and `IN` lists with float literals go through `float_comparison` and `float_in_list`, because DataFusion and Iceberg compare NaN and -0.0 differently. Removing a cast is left to DataFusion's simplifier (`unwrap_cast_in_comparison`), which rewrites a comparison only when the result doesn't change.

### Write path (`IcebergTableProvider::insert_into`)

Expand Down Expand Up @@ -129,7 +129,7 @@ Library code returns `datafusion::error::Result`. Convert iceberg errors with `t
## Dependencies

- **iceberg-rust:** `iceberg` and `iceberg-catalog-rest` are git dependencies on `apache/iceberg-rust`, pinned to the same `rev` in the root `Cargo.toml`. The writers, partition splitting, table properties, encryption, and metadata tables all come from there. A missing API usually has to land upstream first; then bump both `rev`s together.
- **Arrow/Parquet version:** DataFusion, iceberg-rust, and `crates/datafusion`'s direct `parquet` dependency must all resolve to one Arrow/Parquet version (currently 60.x). For that reason Dependabot skips semver-major `datafusion*`/`parquet` bumps. Do those upgrades manually, together with a compatible iceberg-rust `rev`.
- **Arrow/Parquet version:** DataFusion, iceberg-rust, and `crates/datafusion`'s direct `parquet` dependency must all resolve to one Arrow/Parquet version (currently 60.x). For that reason Dependabot skips semver-major `datafusion*`/`parquet` bumps. Do those upgrades manually, together with a compatible iceberg-rust `rev`. Float filter pushdown copies DataFusion's NaN rules, which apache/datafusion#26091 may change; `float_predicate_pushdown.slt` checks them, and the TODO on `float_comparison` says what to update.

## Conventions

Expand Down
258 changes: 249 additions & 9 deletions crates/datafusion/src/read/predicate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
// specific language governing permissions and limitations
// under the License.

use std::cmp::Ordering;

use datafusion::arrow::datatypes::DataType;
use datafusion::logical_expr::expr::{InList, ScalarFunction};
use datafusion::logical_expr::{BinaryExpr, Expr, Like, Operator};
Expand All @@ -27,7 +29,8 @@ enum Converted {
/// Matches exactly the rows the filter matches.
Exact(Predicate),
/// Implied by the filter but not equivalent to it, because an unconvertible
/// AND operand was dropped. Sound to push down, unsound to negate.
/// AND operand was dropped, or because the filter matches some NaN rows but
/// not others. Sound to push down, unsound to negate.
Implied(Predicate),
}

Expand Down Expand Up @@ -73,7 +76,7 @@ fn predicate(expr: &Expr) -> Option<Converted> {
op: Operator::Or,
right,
}) => return Some(or(predicate(left)?, predicate(right)?)),
Expr::BinaryExpr(binary) => comparison(binary)?,
Expr::BinaryExpr(binary) => return comparison(binary),
Expr::Not(inner) => match column(inner) {
// NOT of a bare boolean column: `col = false`
Some(column) => column.equal_to(Datum::bool(false)),
Expand All @@ -89,10 +92,10 @@ fn predicate(expr: &Expr) -> Option<Converted> {
}) => {
let column = column(expr)?;
let datums = list.iter().map(literal).collect::<Option<Vec<_>>>()?;
if *negated {
column.is_not_in(datums)
} else {
column.is_in(datums)
match float_values(&datums) {
Some(values) => return Some(float_in_list(column, &values, *negated)),
None if *negated => column.is_not_in(datums),
None => column.is_in(datums),
}
}
Expr::IsNull(expr) => column(expr)?.is_null(),
Expand Down Expand Up @@ -164,7 +167,7 @@ fn or(left: Converted, right: Converted) -> Converted {
}

/// Converts `column op literal`, or `literal op column` with `op` swapped.
fn comparison(binary: &BinaryExpr) -> Option<Predicate> {
fn comparison(binary: &BinaryExpr) -> Option<Converted> {
let (column, op, datum) = match (column(&binary.left), literal(&binary.right)) {
(Some(column), Some(datum)) => (column, binary.op, datum),
_ => (
Expand All @@ -182,7 +185,156 @@ fn comparison(binary: &BinaryExpr) -> Option<Predicate> {
Operator::GtEq => PredicateOperator::GreaterThanOrEq,
_ => return None,
};
Some(Predicate::Binary(BinaryExpression::new(op, column, datum)))
if let PrimitiveLiteral::Double(value) = datum.literal() {
return Some(float_comparison(column, op, value.0));
}
let predicate = Predicate::Binary(BinaryExpression::new(op, column, datum));
Some(Converted::Exact(predicate))
}

/// Converts `column op value` for a float `value`, so that it keeps the rows
/// DataFusion's comparison matches.
///
/// DataFusion treats -0.0 as equal to 0.0 (see
/// `datafusion::common::float_semantics`), but compares NaN by its bits: a NaN
/// with the sign bit set is less than every number and one without is greater,
/// and two NaNs are equal only if their bits are. Iceberg skips files by its own
/// rules: -0.0 is less than 0.0, and no comparison matches NaN, only `IS NAN` and
/// `IS NOT NAN` do, and those can't tell NaNs apart. So this compares the values
/// other than NaN, with a zero standing for both zeros, and then adds or excludes
/// the NaN rows; see [`with_nan`].
///
/// TODO: When apache/datafusion#26091 makes every NaN equal and greater than every
/// number, a NaN row compares with a number as `Greater` only, and with a NaN
/// literal as `Equal` only, and every number is less than a NaN literal.
/// `float_predicate_pushdown.slt` checks the current rules and fails when they
/// change.
fn float_comparison(column: Reference, op: PredicateOperator, value: f64) -> Converted {
use Ordering::{Equal, Greater, Less};
if value.is_nan() {
// Every number is less than a NaN literal, or greater if the literal's sign
// bit is set.
let number = if value.is_sign_negative() {
Greater
} else {
Less
};
let numbers = if holds(op, number) {
Predicate::AlwaysTrue
} else {
Predicate::AlwaysFalse
};
// A NaN row may be less than, equal to or greater than it, by its bits.
return with_nan(
column,
numbers,
&[Less, Equal, Greater].map(|o| holds(op, o)),
);
}
let numbers = number_comparison(column.clone(), op, value);
// A NaN row is less than any number if its sign bit is set, and greater if not.
with_nan(column, numbers, &[Less, Greater].map(|o| holds(op, o)))
}

/// Compares `column` with a number other than NaN.
fn number_comparison(column: Reference, op: PredicateOperator, value: f64) -> Predicate {
if value != 0.0 {
return Predicate::Binary(BinaryExpression::new(
op,
column,
Datum::double(value),
));
}
// A zero stands for both -0.0 and 0.0, which Iceberg orders -0.0 < 0.0.
match op {
PredicateOperator::Eq => zeros(column),
PredicateOperator::NotEq => column
.clone()
.less_than(Datum::double(-0.0))
.or(column.greater_than(Datum::double(0.0))),
PredicateOperator::LessThan => column.less_than(Datum::double(-0.0)),
PredicateOperator::LessThanOrEq => {
column.less_than_or_equal_to(Datum::double(0.0))
}
PredicateOperator::GreaterThan => column.greater_than(Datum::double(0.0)),
PredicateOperator::GreaterThanOrEq => {
column.greater_than_or_equal_to(Datum::double(-0.0))
}
_ => unreachable!("not a comparison: {op}"),
}
}

/// Converts `column IN (values)`, or `NOT IN` if `negated`, for float `values`:
/// a row matches if it equals any of them, as compared by [`float_comparison`].
fn float_in_list(column: Reference, values: &[f64], negated: bool) -> Converted {
// Zeros are matched by `zeros`, as in comparisons: Iceberg compares set members
// by its own order, so a set holding 0.0 alone would not match -0.0.
let numbers: Vec<Datum> = values
.iter()
.filter(|value| !value.is_nan() && **value != 0.0)
.map(|value| Datum::double(*value))
.collect();
let mut matches = if numbers.is_empty() {
Predicate::AlwaysFalse
} else {
column.clone().is_in(numbers)
};
if values.contains(&0.0) {
matches = matches.or(zeros(column.clone()));
}
// A NaN row never equals a number, and may equal a NaN in the list.
let nan_matches = [false, values.iter().any(|value| value.is_nan())];
if negated {
with_nan(column, matches.negate(), &nan_matches.map(|m| !m))
} else {
with_nan(column, matches, &nan_matches)
}
}

/// Matches -0.0 and 0.0.
fn zeros(column: Reference) -> Predicate {
column
.clone()
.greater_than_or_equal_to(Datum::double(-0.0))
.and(column.less_than_or_equal_to(Datum::double(0.0)))
}

/// Adds the NaN rows to the rows `numbers` matches, or excludes them.
/// `nan_matches` holds whether the filter matches a NaN row, for each way a NaN
/// row can compare with the literal. If it matches in some ways but not others,
/// the NaN rows are kept, and the result is only implied by the filter.
fn with_nan(column: Reference, numbers: Predicate, nan_matches: &[bool]) -> Converted {
if nan_matches.iter().all(|m| *m) {
Converted::Exact(numbers.or(column.is_nan()))
} else if nan_matches.iter().any(|m| *m) {
Converted::Implied(numbers.or(column.is_nan()))
} else {
Converted::Exact(numbers.and(column.is_not_nan()))
}
}

/// Whether `a op b` holds when `a.cmp(b)` is `ordering`.
fn holds(op: PredicateOperator, ordering: Ordering) -> bool {
match op {
PredicateOperator::Eq => ordering.is_eq(),
PredicateOperator::NotEq => ordering.is_ne(),
PredicateOperator::LessThan => ordering.is_lt(),
PredicateOperator::LessThanOrEq => ordering.is_le(),
PredicateOperator::GreaterThan => ordering.is_gt(),
PredicateOperator::GreaterThanOrEq => ordering.is_ge(),
_ => unreachable!("not a comparison: {op}"),
}
}

/// The values of `datums` if all of them are floats.
fn float_values(datums: &[Datum]) -> Option<Vec<f64>> {
datums
.iter()
.map(|datum| match datum.literal() {
PrimitiveLiteral::Double(value) => Some(value.0),
_ => None,
})
.collect()
}

fn column(expr: &Expr) -> Option<Reference> {
Expand Down Expand Up @@ -375,7 +527,8 @@ mod tests {
use datafusion::arrow::datatypes::{DataType, Field, Schema, TimeUnit};
use datafusion::common::DFSchema;
use datafusion::logical_expr::utils::split_conjunction;
use datafusion::prelude::{Expr, SessionContext};
use datafusion::logical_expr::{Operator, binary_expr};
use datafusion::prelude::{Expr, SessionContext, col, lit};
use iceberg::expr::{Predicate, Reference};
use iceberg::spec::Datum;
use parquet::arrow::PARQUET_FIELD_ID_META_KEY;
Expand Down Expand Up @@ -640,6 +793,93 @@ mod tests {
assert_eq!(predicate, expected_predicate);
}

#[test]
fn test_predicate_conversion_with_float_literals() {
let qux = || col("qux");
// Every comparison with a number, a zero, NaN and NaN with the sign bit
// set. They are named here, since a NaN literal displays without its sign.
let mut filters = Vec::new();
for (name, value) in [
("1.5", 1.5),
("0", 0.0),
("NaN", f64::NAN),
("-NaN", -f64::NAN),
] {
for op in [
Operator::Eq,
Operator::NotEq,
Operator::Lt,
Operator::LtEq,
Operator::Gt,
Operator::GtEq,
] {
let filter = binary_expr(qux(), op, lit(value));
filters.push((format!("qux {op} {name}"), filter));
}
}
filters.extend(
[
// -0.0 is the same zero, a REAL literal the same number, and a
// literal on the left the same comparison.
qux().eq(lit(-0.0)),
qux().gt(lit(1.5f32)),
lit(1.5).lt(qux()),
qux().in_list(vec![lit(1.5), lit(0.0), lit(f64::NAN)], false),
qux().in_list(vec![lit(1.5), lit(2.5)], true),
qux().in_list(vec![lit(1.5), lit(f64::NAN)], true),
// `NOT` negates an exact conversion only.
!qux().eq(lit(1.5)),
!qux().lt(lit(1.5)),
]
.map(|filter| (filter.to_string(), filter)),
);

let converted = filters
.into_iter()
.map(|(name, filter)| {
let predicate = convert_filters_to_predicate(&[filter])
.map_or("not pushed".to_string(), |p| p.to_string());
format!("{name} => {predicate}")
})
.collect::<Vec<_>>()
.join("\n");

insta::assert_snapshot!(converted, @"
qux = 1.5 => (qux = 1.5) AND (qux IS NOT NAN)
qux != 1.5 => (qux != 1.5) OR (qux IS NAN)
qux < 1.5 => (qux < 1.5) OR (qux IS NAN)
qux <= 1.5 => (qux <= 1.5) OR (qux IS NAN)
qux > 1.5 => (qux > 1.5) OR (qux IS NAN)
qux >= 1.5 => (qux >= 1.5) OR (qux IS NAN)
qux = 0 => ((qux >= -0) AND (qux <= 0)) AND (qux IS NOT NAN)
qux != 0 => ((qux < -0) OR (qux > 0)) OR (qux IS NAN)
qux < 0 => (qux < -0) OR (qux IS NAN)
qux <= 0 => (qux <= 0) OR (qux IS NAN)
qux > 0 => (qux > 0) OR (qux IS NAN)
qux >= 0 => (qux >= -0) OR (qux IS NAN)
qux = NaN => qux IS NAN
qux != NaN => TRUE
qux < NaN => TRUE
qux <= NaN => TRUE
qux > NaN => qux IS NAN
qux >= NaN => qux IS NAN
qux = -NaN => qux IS NAN
qux != -NaN => TRUE
qux < -NaN => qux IS NAN
qux <= -NaN => qux IS NAN
qux > -NaN => TRUE
qux >= -NaN => TRUE
qux = Float64(-0) => ((qux >= -0) AND (qux <= 0)) AND (qux IS NOT NAN)
qux > Float32(1.5) => (qux > 1.5) OR (qux IS NAN)
Float64(1.5) < qux => (qux > 1.5) OR (qux IS NAN)
qux IN ([Float64(1.5), Float64(0), Float64(NaN)]) => ((qux IN (1.5)) OR ((qux >= -0) AND (qux <= 0))) OR (qux IS NAN)
qux NOT IN ([Float64(1.5), Float64(2.5)]) => (qux NOT IN (1.5, 2.5)) OR (qux IS NAN)
qux NOT IN ([Float64(1.5), Float64(NaN)]) => (qux NOT IN (1.5)) OR (qux IS NAN)
NOT qux = Float64(1.5) => NOT ((qux = 1.5) AND (qux IS NOT NAN))
NOT qux < Float64(1.5) => not pushed
");
}

#[test]
fn test_predicate_conversion_with_cast() {
for sql in [
Expand Down
2 changes: 1 addition & 1 deletion crates/datafusion/tests/filter_pushdown.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ mod tests {
CoalescePartitionsExec
AggregateExec: mode=Partial, gby=[], aggr=[count(Int64(1))]
FilterExec: pickup_date@2 = 2024-01-10 AND payment_type@1 IN (SET) ([1, 2]) AND trip_distance@0 >= 2, projection=[]
DataSourceExec: format=iceberg, projection=[trip_distance, payment_type, pickup_date], provider=lazy, predicate=((pickup_date = 2024-01-10) AND (payment_type IN (1, 2))) AND (trip_distance >= 2)
DataSourceExec: format=iceberg, projection=[trip_distance, payment_type, pickup_date], provider=lazy, predicate=((pickup_date = 2024-01-10) AND (payment_type IN (1, 2))) AND ((trip_distance >= 2) OR (trip_distance IS NAN))
");
insta::assert_snapshot!(batches, @r"
+-------+
Expand Down
Loading