Fokko commented on code in PR #4346:
URL: https://github.com/apache/iceberg-python/pull/4346#discussion_r4700337981


##########
pyiceberg/io/pyarrow.py:
##########
@@ -1748,6 +1759,32 @@ def _get_column_projection_values(
     return projected_missing_fields
 
 
+def _has_nan_sensitive_predicate(expr: BooleanExpression) -> bool:
+    """Return whether a predicate in the expression can match NaN values that 
pyarrow may prune away.
+
+    Parquet statistics exclude NaN, so a row group whose non-NaN values are 
all equal reports min == max.
+    pyarrow then prunes it for predicates that the NaN values satisfy: IsNaN, 
NotEqualTo and NotIn on a
+    float or double column.
+
+    The expression must be bound and already rewritten by `rewrite_not`, 
because `Not` nodes are not inspected.
+    """
+    if isinstance(expr, (And, Or)):
+        return _has_nan_sensitive_predicate(expr.left) or 
_has_nan_sensitive_predicate(expr.right)
+    return isinstance(expr, (BoundIsNaN, BoundNotEqualTo, BoundNotIn)) and 
isinstance(
+        expr.term.ref().field.field_type, (FloatType, DoubleType)
+    )
+
+
+def _nan_safe_conjuncts(expr: BooleanExpression) -> BooleanExpression:

Review Comment:
   Correcting my earlier comment: OR branches do not keep their conjuncts. A 
NaN-sensitive leaf anywhere under an `Or` drops the whole top-level conjunct, 
so `(x is nan and id = 7) or id = 8` pushes down nothing. Java evaluates per 
leaf (`ROWS_MIGHT_MATCH` for the NaN-sensitive leaf), so it still skips row 
groups where `id` cannot be 7 or 8.
   
   What do you think of recursing into `Or` as well and replacing only the 
sensitive leaves with `AlwaysTrue()`? After `rewrite_not` the tree only has 
`And`/`Or`, so the result is always implied by the original filter and is safe 
to push down. The example above then pushes `id = 7 or id = 8`. I tried this 
locally and the existing tests pass.
   
   ```python
   def _nan_safe_filter(expr: BooleanExpression) -> BooleanExpression:
       if isinstance(expr, And):
           return And(_nan_safe_filter(expr.left), _nan_safe_filter(expr.right))
       if isinstance(expr, Or):
           return Or(_nan_safe_filter(expr.left), _nan_safe_filter(expr.right))
       return AlwaysTrue() if _has_nan_sensitive_predicate(expr) else expr
   ```



##########
tests/io/test_pyarrow.py:
##########
@@ -4587,6 +4592,64 @@ def 
test_task_to_record_batches_filter_after_positional_deletes_empty_result(tmp
     assert result_batches == []
 
 
+def 
test_task_to_record_batches_keeps_nan_rows_for_nan_sensitive_filters(tmpdir: 
str) -> None:
+    """Regression test: pyarrow must not prune a row group that holds NaN rows 
matching the filter.
+
+    Parquet statistics exclude NaN, so the row group [NaN, 5.0, 5.0] reports 
min == max == 5.0.
+    pyarrow prunes such a row group for IsNaN, NotEqualTo and NotIn, which 
drops the NaN row.
+    NotNaN is a control.
+    """
+    from pyiceberg.expressions.visitors import bind
+
+    for arrow_type, iceberg_type in [(pa.float32(), FloatType()), 
(pa.float64(), DoubleType())]:
+        arrow_schema = pa.schema(
+            (
+                pa.field("id", pa.int32(), nullable=True, 
metadata={PYARROW_PARQUET_FIELD_ID_KEY: "1"}),
+                pa.field("x", arrow_type, nullable=True, 
metadata={PYARROW_PARQUET_FIELD_ID_KEY: "2"}),
+            )
+        )
+        arrow_table = pa.table(
+            {"id": pa.array([0, 1, 2], type=pa.int32()), "x": 
pa.array([float("nan"), 5.0, 5.0], type=arrow_type)},
+            schema=arrow_schema,
+        )
+        data_file = _write_table_to_data_file(
+            f"{tmpdir}/nan_row_group_equal_bounds_{iceberg_type}.parquet", 
arrow_schema, arrow_table
+        )
+
+        table_schema = Schema(
+            NestedField(1, "id", IntegerType(), required=False),
+            NestedField(2, "x", iceberg_type, required=False),
+        )
+        projected_schema = Schema(NestedField(1, "id", IntegerType(), 
required=False))
+
+        cases: list[tuple[BooleanExpression, list[int]]] = [
+            (IsNaN("x"), [0]),
+            (NotEqualTo("x", 5.0), [0]),
+            (NotIn("x", {5.0, 6.0}), [0]),
+            (And(IsNaN("x"), EqualTo("id", 0)), [0]),
+            (Or(IsNaN("x"), EqualTo("id", 2)), [0, 2]),

Review Comment:
   This case passes without the fix: `id = 2` is inside the row group's `id` 
range, so Arrow never prunes the row group. Using an `id` outside the range 
makes it fail before and pass after:
   
   ```suggestion
               (Or(IsNaN("x"), EqualTo("id", 7)), [0]),
   ```
   
   Separately, nothing asserts that the NaN-safe conjuncts are still pushed 
down. If `_nan_safe_conjuncts` regressed to always returning `AlwaysTrue()`, 
every test here would still pass. Could we add a direct test on the helper, for 
example that `And(IsNaN("x"), EqualTo("id", 0))` yields `id = 0`?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to