Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
f61c643
fix: keep Iceberg residual pushdown within Spark semantics
rich7420 Oct 21, 2026
cda4add
fix: push negated equality guarded by a null check on the same column
rich7420 Oct 22, 2026
05c5132
test: assert which negated equalities stay pushed to native Iceberg s…
rich7420 Oct 23, 2026
7f18a37
test: require Iceberg 1.9 for expired schema cleanup
rich7420 Oct 25, 2026
31bbcfc
Merge branch 'main' into fix/7136-iceberg-residual-semantics
rich7420 Oct 26, 2026
89b2afd
test: focus Iceberg residual correctness regressions
rich7420 Oct 27, 2026
e4a884d
Merge branch 'main' into fix/7136-iceberg-residual-semantics
rich7420 Oct 31, 2026
794df9a
Merge upstream/main into fix/7136-iceberg-residual-semantics
rich7420 Nov 7, 2026
4ea8723
Merge latest upstream/main into fix/7136-iceberg-residual-semantics
rich7420 Nov 7, 2026
e1afd07
fix: treat timestamp columns as promoted when Iceberg schema history …
rich7420 Nov 10, 2026
2f6f4a1
fix: do not push Iceberg range and IN residuals on tables with a name…
andygrove Oct 26, 2026
af2df23
docs: list equality under NOT among the promoted-column exclusions
rich7420 Nov 16, 2026
0936d46
Merge upstream/main into fix/7136-iceberg-residual-semantics
rich7420 Nov 16, 2026
a4c6f91
docs: note that the pinned iceberg-rust includes #3502
rich7420 Nov 16, 2026
fddc5bf
Merge remote-tracking branch 'apache/main' into HEAD
andygrove Nov 22, 2026
4403f9c
Merge upstream/main into fix/7136-iceberg-residual-semantics
rich7420 Nov 23, 2026
d5bf49e
test: count pushed Iceberg residuals across partition pools
rich7420 Nov 23, 2026
5d09d65
test: count Iceberg residuals across the per-partition pools
andygrove Nov 30, 2026
b4a5d60
test: share the snapshotTable import helper and cover decimal and tim…
andygrove Nov 30, 2026
610bd49
perf: collect NOT_NULL columns once per AND chain in Iceberg residuals
rich7420 Nov 30, 2026
aeeb1b0
Merge branch 'main' into fix/7136-iceberg-residual-semantics
andygrove Nov 30, 2026
5e26cd8
Merge branch 'pr-7156' into fix-7138-name-mapping
andygrove Nov 30, 2026
6f7677c
docs: name the iceberg-rust commits and the Arrow 60 bump that let th…
andygrove Nov 30, 2026
28006e6
fix: fall back to Spark for equality deletes keyed on a column that m…
andygrove Nov 30, 2026
78f78f8
perf: find promoted equality-delete keys by field id in one pass over…
andygrove Dec 1, 2026
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
29 changes: 29 additions & 0 deletions docs/source/user-guide/latest/iceberg.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,24 @@ results, but are not pushed into iceberg-rust, which binds accessors only for pr
These residuals provide no native row-group pruning, nor do conjunctions containing them;
safe partial pruning is tracked in [#5883](https://github.com/apache/datafusion-comet/issues/5883).

Some predicates are left to the filter above the scan because iceberg-rust would return
different rows than Spark:

- Range comparisons on `FLOAT` and `DOUBLE` columns, and comparisons with `0.0`, `-0.0` or NaN.
- `NOT` over equality on a nullable column, as in `NOT (id <=> 1)`, unless it is ANDed with an
`IS NOT NULL` check on that column, written in the query or inferred by Spark as for `b = false`.
`!=` reaches iceberg-rust as a separate comparison and is not affected.
- Comparisons other than `=`, and `=` under `NOT`, on a column whose type was promoted. This
applies to every `BIGINT`, `DOUBLE`, `DECIMAL` and `TIMESTAMP_NTZ` column when expiring
snapshots removed older schemas, and to every `INT`, `BIGINT`, `DOUBLE`, `DECIMAL` and
`TIMESTAMP_NTZ` column of a table with a `schema.name-mapping.default` property, which
`add_files`, `migrate` and `snapshot` set.

Iceberg still skips data files by their column bounds for these predicates, but the native scan
does not prune row groups for them or for conjunctions containing them. Restoring range pruning
on `FLOAT` and `DOUBLE` columns is tracked in
[#7588](https://github.com/apache/datafusion-comet/issues/7588).

**Partitioning:**

- Standard partitioning with partition pruning
Expand Down Expand Up @@ -255,6 +273,9 @@ The following scenarios will fall back to the JVM Iceberg reader:
- Encrypted tables with 192-bit data keys (no AES-192-GCM in the underlying crypto)
- Delete files in a format other than Parquet or Puffin (Avro or ORC positional/equality deletes)
- Equality deletes keyed on a field nested in a struct
- Equality deletes keyed on a column that the promoted-column exclusion under
[Supported features](#supported-features) covers, because iceberg-rust compares the delete value
with a file that stores a narrower type incorrectly
- Tables backed by Avro or ORC data files (only Parquet is accelerated)
- Queries that use `input_file_name()`, `input_file_block_start()` or `input_file_block_length()`
- Scans whose data or delete files span more than one S3 bucket (the native reader uses one
Expand Down Expand Up @@ -1000,6 +1021,14 @@ Which entries apply depends on which native paths are enabled:
returns a struct of NULL fields, and an empty list for a list of structs, where the native scan
returns the list with each element's fields NULL
([#6794](https://github.com/apache/datafusion-comet/issues/6794)).
- **Data files that store a narrower type than their column.** Files written before a type
promotion, such as `INT` to `BIGINT`, keep the older type, and files imported by `add_files`,
`migrate` or `snapshot` can store any narrower type. iceberg-rust compares such a file with a
filter literal incorrectly, so comparisons other than `=`, and `=` under `NOT`, pushed to the
native scan can drop matching rows. Comet avoids this for promotions that the schema history
records and for tables with a name mapping, which the import procedures set, but not for
promotions made before Iceberg 0.12 or for files imported into a table without a name mapping
([#7138](https://github.com/apache/datafusion-comet/issues/7138)).
Comment on lines +1024 to +1031

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Equality deletes go through the same comparison, and neither guard covers them. At the pin, iceberg-rust turns each delete row into col IS NULL OR col != v, binds it to the task schema (crates/iceberg/src/arrow/caching_delete_file_loader.rs:617-629, delete_filter.rs:231), and ANDs it into the same row filter (reader/pipeline.rs:478-544). There not_eq calls try_cast_literal (predicate_visitor.rs:520-533). Take an equality delete written after an INT to BIGINT promotion with a value above i32::MAX. When it applies to an older INT file, v becomes NULL and every non-NULL row of that file is dropped. A DOUBLE delete value such as 0.1 rounds to the FLOAT 0.1 and removes a row that Spark keeps. CometScanRule checks equality-delete keys only for nesting and type (CometScanRule.scala:1214-1257). Could this bullet list equality deletes keyed on such a column, or could CometScanRule fall back when a key is in promotedColumns? #7712 also lists this as not covered. I found this by reading the code and did not run it.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, I confirmed this against the code and chose the fallback. CometScanRule now declines the native scan when an equality-delete key is in the promoted-column set. That set covers the current, scan and historic schemas with the name-mapping widening, so a dropped key is covered too. The new test equality delete keyed on a promoted column falls back to Spark promotes INT to BIGINT and commits a delete of 3000000000. It matches Spark and fails with the fallback disabled. The fallback is listed under "Current limitations" in iceberg.md (28006e6).

- **`VERSION AS OF` reads of a column renamed after the snapshot.** The renamed column reads as
NULL, and two columns that swapped names return each other's values
([#6822](https://github.com/apache/datafusion-comet/issues/6822)).
Expand Down
56 changes: 40 additions & 16 deletions native/core/src/execution/planner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2774,21 +2774,7 @@ fn parse_file_scan_tasks_from_common(
.residual_pool
.get(idx as usize)
.and_then(iceberg_predicate_to_predicate)
.and_then(|pred| {
// The residual predicate only drives row-group pruning; the post-scan
// filter still enforces correctness. iceberg-rust cannot bind a datum
// whose type has no conversion to the column type, so on a bind failure
// we skip pushdown rather than fail the scan.
// rewrite_not first: iceberg-rust's scan evaluators require negation-normal
// form and reject a bare NOT (e.g. from a `NOT (a = b)` residual).
match pred.rewrite_not().bind(Arc::clone(&schema_ref), true) {
Ok(bound) => Some(bound),
Err(e) => {
log::warn!("Skipping Iceberg predicate pushdown; bind failed: {e}");
None
}
}
})
.and_then(|pred| bind_residual(pred, Arc::clone(&schema_ref)))
} else {
None
};
Expand Down Expand Up @@ -3159,6 +3145,24 @@ fn iceberg_predicate_to_predicate(
}
}

/// Binds a residual predicate to the file's schema. The residual prunes reads and filters rows; the
/// post-scan filter enforces any omitted predicates. iceberg-rust cannot bind a datum whose type
/// has no conversion to the column type, so on a bind failure we skip pushdown rather than fail
/// the scan. rewrite_not first: iceberg-rust's scan evaluators require negation-normal form and
/// reject a bare NOT (e.g. from a `NOT (a = b)` residual).
fn bind_residual(
pred: iceberg::expr::Predicate,
schema: Arc<iceberg::spec::Schema>,
) -> Option<iceberg::expr::BoundPredicate> {
match pred.rewrite_not().bind(schema, true) {
Ok(bound) => Some(bound),
Err(e) => {
log::warn!("Skipping Iceberg predicate pushdown; bind failed: {e}");
None
}
}
}

/// Combines the two children of a logical residual node (And/Or), returning `None` unless both
/// converted. A missing child is not expected: the Scala serde emits a logical node only when both
/// children convert, and Rust decodes every node it emits, so both sides always convert for a
Expand Down Expand Up @@ -3283,7 +3287,7 @@ mod tests {

use crate::execution::operators::ExecutionError;
use crate::execution::planner::{
convert_spark_types_to_arrow_schema, literal_to_array_ref,
bind_residual, convert_spark_types_to_arrow_schema, literal_to_array_ref,
parse_file_scan_tasks_from_common,
};
use crate::execution::shuffle::CometPartitioning;
Expand All @@ -3304,6 +3308,26 @@ mod tests {
};
use datafusion_comet_spark_expr::EvalMode;

#[test]
fn iceberg_residual_bind_failure_skips_pushdown() {
use iceberg::expr::Reference;
use iceberg::spec::{Datum, NestedField, PrimitiveType, Schema as IcebergSchema, Type};

let schema = Arc::new(
IcebergSchema::builder()
.with_fields(vec![Arc::new(NestedField::optional(
1,
"id",
Type::Primitive(PrimitiveType::Int),
))])
.build()
.unwrap(),
);
let id = Reference::new("id");
assert!(bind_residual(!id.clone().equal_to(Datum::int(1)), Arc::clone(&schema)).is_some());
assert!(bind_residual(id.equal_to(Datum::bool(true)), schema).is_none());
}

#[test]
fn scan_default_rejects_struct_expressions() {
let planner = PhysicalPlanner::new(Arc::new(SessionContext::new()), 0);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1230,6 +1230,80 @@ object IcebergReflection extends Logging {
}
}

/**
* Top-level column names of `schema` whose type differs in some schema of the table's history
* (`table.schemas()`), such as an int column promoted to long. Data files written before the
* promotion keep the older type, and iceberg-rust compares literals against it incorrectly: the
* page index skips every page for range and IN predicates, and the row filter casts the literal
* to the older type, so an out-of-range value becomes NULL (apache/iceberg-rust#3122).
*
* Expiring snapshots with `cleanExpiredMetadata` removes schemas that no retained snapshot
* uses, even though files written under them can remain. Iceberg numbers schemas consecutively
* from 0, so a gap means the history is incomplete, and every column of a type that a promotion
* can produce is returned: long, double, decimal, and, from format v3, timestamp and
* timestamp_ns, which a date can be promoted to. The history cannot reveal a file whose type
* differs without a recorded schema change, such as one imported by `add_files`, `migrate` or
* `snapshot`, or one promoted under metadata from before Iceberg 0.12, which kept only the
* current schema.
*
* Those imports set a name mapping, so a caller reading a table that has one passes
* `filesMayBeNarrower = true`. Every column of a type that a file can store in a narrower type
* is then returned, as for an incomplete history, and `int` joins the types above (Hive TINYINT
* and SMALLINT). Called at serialization time, so it throws on reflection failure.
*/
def promotedColumns(
table: Any,
schema: Any,
filesMayBeNarrower: Boolean = false): Set[String] = {
val ids = promotedFieldIds(table, Seq(schema), filesMayBeNarrower)
topLevelColumns(schema).filter(c => ids.contains(fieldIdOf(c))).map(fieldName).toSet
}

/**
* The field ids [[promotedColumns]] reports, for the top-level columns of `schemas` together
* with the table's history, computed in one pass over each schema. A field id belongs to one
* column for the life of the table, so a dropped column and a later one of the same name are
* different ids, and only the id whose type changed or may be narrower is returned.
*/
def promotedFieldIds(
table: Any,
schemas: Seq[Any],
filesMayBeNarrower: Boolean = false): Set[Int] = {
import scala.jdk.CollectionConverters._
val schemasById = getMethod(table.getClass, "schemas")
.invoke(table)
.asInstanceOf[java.util.Map[_, _]]
.asScala
val schemaIds = schemasById.keys.map(_.asInstanceOf[Integer].intValue).toSet
val historyComplete =
schemaIds.nonEmpty && schemaIds.min == 0 && schemaIds.max == schemaIds.size - 1
val assumeNarrower = filesMayBeNarrower || !historyComplete
val promotableTypes = Set("long", "double", "timestamp", "timestamp_ns") ++
(if (filesMayBeNarrower) Some("int") else None)
def promotable(tpe: String): Boolean =
tpe.startsWith("decimal(") || promotableTypes.contains(tpe)

val typesById = scala.collection.mutable.Map.empty[Int, Set[String]]
(schemasById.values.toSeq ++ schemas).foreach { schema =>
topLevelColumns(schema).foreach { column =>
val id = fieldIdOf(column)
typesById(id) = typesById.getOrElse(id, Set.empty[String]) + fieldTypeOf(column).toString
}
}
typesById.collect {
case (id, types) if types.size > 1 || (assumeNarrower && types.exists(promotable)) => id
}.toSet
}

private def topLevelColumns(schema: Any): Seq[Any] = {
import scala.jdk.CollectionConverters._
getMethod(schema.getClass, "columns")
.invoke(schema)
.asInstanceOf[java.util.List[_]]
.asScala
.toSeq
}

/**
* Validates partition column types for compatibility with iceberg-rust.
*
Expand Down
16 changes: 16 additions & 0 deletions spark/src/main/scala/org/apache/comet/rules/CometScanRule.scala
Original file line number Diff line number Diff line change
Expand Up @@ -1184,6 +1184,15 @@ case class CometScanRule(session: SparkSession)
val topLevelIds = (metadata.tableSchema +: historicSchemas)
.flatMap(IcebergReflection.buildFieldIdMapping(_).values)
.toSet
// iceberg-rust turns each equality-delete row into a filter on the key column and
// compares it with a file that still stores a narrower type incorrectly, so a key
// that may have been promoted drops rows Spark keeps (apache/iceberg-rust#3122).
// Keyed by field id, since a dropped key exists only in the history and a later
// column may reuse its name.
lazy val promotedKeyIds = IcebergReflection.promotedFieldIds(
metadata.table,
Seq(metadata.tableSchema, metadata.scanSchema),
filesMayBeNarrower = metadata.nameMapping.isDefined)
val contentFileClass =
IcebergReflection.loadClass(IcebergReflection.ClassNames.CONTENT_FILE)
val deleteFileClass =
Expand Down Expand Up @@ -1236,6 +1245,13 @@ case class CometScanRule(session: SparkSession)
s"Equality delete on nested field '$fieldName' (id $fid) is not yet " +
"supported by iceberg-rust, which resolves equality field ids " +
"among top-level columns only."
case Some((fieldName, _)) if promotedKeyIds.contains(fid) =>
hasUnsupportedDeletes = true
fallbackReasons +=
s"Equality delete on column '$fieldName', whose data files may store " +
"a narrower type than the column, is not supported by iceberg-rust, " +
"which would compare the delete value with the older type " +
"incorrectly and drop matching rows."
case Some((fieldName, fieldType)) =>
if (fieldType.contains("struct") || fieldType.equalsIgnoreCase(
"variant")) {
Expand Down
Loading
Loading