From 89102cd2cf3cea1c044fa1f4d3b11a278c4c8d1d Mon Sep 17 00:00:00 2001 From: rahulsmahadev Date: Tue, 24 Nov 2026 17:48:31 +0000 Subject: [PATCH 1/2] Apply initial defaults under present struct parents A field added under an optional struct with an initial default was folded to that default for the whole file, so rows whose struct is NULL matched as if the field were present. Such predicates now read the field as NULL under a NULL ancestor struct, and a NOT over them (or over != and NOT IN) is pushed into its complement. Arrow paths are built from field IDs, so a struct whose name contains a dot resolves after a rename. Co-authored-by: Isaac --- pyiceberg/expressions/visitors.py | 109 +++++++++++++++-- pyiceberg/io/pyarrow.py | 36 ++++-- tests/expressions/test_visitors.py | 16 +++ tests/io/test_pyarrow.py | 187 +++++++++++++++++++++++++++++ 4 files changed, 328 insertions(+), 20 deletions(-) diff --git a/pyiceberg/expressions/visitors.py b/pyiceberg/expressions/visitors.py index 7504548507..0bd088e909 100644 --- a/pyiceberg/expressions/visitors.py +++ b/pyiceberg/expressions/visitors.py @@ -862,6 +862,22 @@ def inclusive_projection( return InclusiveProjection(schema, spec, case_sensitive).project +# These predicates use Arrow's NULL behavior. != and NOT IN retain the existing default-value result (see #4276). +_NULL_STRICT_PREDICATES = ( + BoundEqualTo, + BoundIn, + BoundLessThan, + BoundLessThanOrEqual, + BoundGreaterThan, + BoundGreaterThanOrEqual, + BoundIsNull, + BoundNotNull, +) + +# A NOT over these predicates is pushed into their complements, so NOT (c != 5) is handled as c = 5 +_NESTED_NOT_PREDICATES = (*_NULL_STRICT_PREDICATES, BoundNotEqualTo, BoundNotIn) + + class _ColumnNameTranslator(BooleanExpressionVisitor[BooleanExpression]): """Converts the column names with the ones in the actual file. @@ -869,6 +885,7 @@ class _ColumnNameTranslator(BooleanExpressionVisitor[BooleanExpression]): file_schema (Schema): The schema of the file. case_sensitive (bool): Whether to consider case when binding a reference to a field in a schema, defaults to True. projected_field_values (Dict[int, Any]): Values for projected fields not present in the data file. + table_schema (Schema | None): The table schema, used to find the struct ancestors of a missing field. Raises: TypeError: In the case of an UnboundPredicate. @@ -878,11 +895,19 @@ class _ColumnNameTranslator(BooleanExpressionVisitor[BooleanExpression]): file_schema: Schema case_sensitive: bool projected_field_values: dict[int, Any] + table_schema: Schema | None - def __init__(self, file_schema: Schema, case_sensitive: bool, projected_field_values: dict[int, Any] = EMPTY_DICT) -> None: + def __init__( + self, + file_schema: Schema, + case_sensitive: bool, + projected_field_values: dict[int, Any] = EMPTY_DICT, + table_schema: Schema | None = None, + ) -> None: self.file_schema = file_schema self.case_sensitive = case_sensitive self.projected_field_values = projected_field_values + self.table_schema = table_schema def visit_true(self) -> BooleanExpression: return AlwaysTrue() @@ -926,11 +951,16 @@ def visit_bound_predicate(self, predicate: BoundPredicate) -> BooleanExpression: field_value = ( self.projected_field_values[field_id] if field.field_id in self.projected_field_values else field.initial_default ) - return ( - AlwaysTrue() - if expression_evaluator(Schema(field), pred, case_sensitive=self.case_sensitive)(Record(field_value)) - else AlwaysFalse() - ) + evaluate = expression_evaluator(Schema(field), pred, case_sensitive=self.case_sensitive) + matches_value = evaluate(Record(field_value)) + if self.table_schema is None or not isinstance(predicate, _NULL_STRICT_PREDICATES): + return AlwaysTrue() if matches_value else AlwaysFalse() + # A row whose optional ancestor struct is NULL reads the field as NULL, so it matches like a NULL value + matches_null = evaluate(Record(None)) + if matches_value == matches_null: + return AlwaysTrue() if matches_value else AlwaysFalse() + present = self._ancestors_present(self.table_schema, field.field_id) + return present if matches_value else Not(present) if isinstance(predicate, BoundUnaryPredicate): return predicate.as_unbound(file_column_name) @@ -941,11 +971,74 @@ def visit_bound_predicate(self, predicate: BoundPredicate) -> BooleanExpression: else: raise ValueError(f"Unsupported predicate: {predicate}") + def _ancestors_present(self, table_schema: Schema, field_id: int) -> BooleanExpression: + """Return the rows in which every optional struct around a missing field is present.""" + present: BooleanExpression = AlwaysTrue() + for parent_id in _ancestor_ids(table_schema, field_id): + parent = table_schema.find_field(parent_id) + if not parent.required: + parent_name = self.file_schema.find_column_name(parent_id) + if parent_name is None: + # The struct is missing from the file too, so its value is the same in every row + if self.projected_field_values.get(parent_id, parent.initial_default) is None: + return AlwaysFalse() + else: + present = And(present, NotNull(parent_name)) + return present + + +def _ancestor_ids(schema: Schema, field_id: int) -> list[int]: + """Return the IDs of the parents of a field, from the nearest one outwards.""" + ancestor_ids: list[int] = [] + parent_id = schema._lazy_id_to_parent.get(field_id) + while parent_id is not None: + ancestor_ids.append(parent_id) + parent_id = schema._lazy_id_to_parent.get(parent_id) + return ancestor_ids + + +def _is_missing_nested_field(predicate: BoundPredicate, file_schema: Schema, table_schema: Schema) -> bool: + """Return whether the predicate reads a field that is missing from the file, under an optional struct.""" + field_id = predicate.term.ref().field.field_id + return file_schema.find_column_name(field_id) is None and any( + not table_schema.find_field(parent_id).required for parent_id in _ancestor_ids(table_schema, field_id) + ) + + +def _rewrite_nested_not( + expr: BooleanExpression, file_schema: Schema, table_schema: Schema, negated: bool = False +) -> BooleanExpression: + """Push NOT down to the predicates, and complement those on a missing nested field. + + A row whose optional struct is NULL reads such a field as NULL. NOT (c < 4) must not match that row, as c >= 4 + does not. Other negations are kept, so their results stay the same as on main. + """ + if isinstance(expr, Not): + return _rewrite_nested_not(expr.child, file_schema, table_schema, not negated) + if isinstance(expr, (And, Or)): + # De Morgan's laws: NOT (A AND B) is NOT A OR NOT B, and NOT (A OR B) is NOT A AND NOT B + left = _rewrite_nested_not(expr.left, file_schema, table_schema, negated) + right = _rewrite_nested_not(expr.right, file_schema, table_schema, negated) + if isinstance(expr, And) != negated: + return And(left, right) + return Or(left, right) + if not negated: + return expr + if isinstance(expr, _NESTED_NOT_PREDICATES) and _is_missing_nested_field(expr, file_schema, table_schema): + return ~expr + return Not(child=expr) + def translate_column_names( - expr: BooleanExpression, file_schema: Schema, case_sensitive: bool = True, projected_field_values: dict[int, Any] = EMPTY_DICT + expr: BooleanExpression, + file_schema: Schema, + case_sensitive: bool = True, + projected_field_values: dict[int, Any] = EMPTY_DICT, + table_schema: Schema | None = None, ) -> BooleanExpression: - return visit(expr, _ColumnNameTranslator(file_schema, case_sensitive, projected_field_values)) + if table_schema is not None: + expr = _rewrite_nested_not(expr, file_schema, table_schema) + return visit(expr, _ColumnNameTranslator(file_schema, case_sensitive, projected_field_values, table_schema)) class _ExpressionFieldIDs(BooleanExpressionVisitor[set[int]]): diff --git a/pyiceberg/io/pyarrow.py b/pyiceberg/io/pyarrow.py index d0b7031c3f..f94e9000dd 100644 --- a/pyiceberg/io/pyarrow.py +++ b/pyiceberg/io/pyarrow.py @@ -946,17 +946,19 @@ def _get_field_name(self, term: BoundTerm) -> str | tuple[str, ...]: For nested struct fields, returns a tuple of field names (e.g., ("mazeMetadata", "run_id")). For top-level fields, returns just the field name as a string. + The path is built from the field IDs, because a struct name can contain a dot (e.g., "old.pt"). PyArrow requires nested field references as tuples, not dotted strings. """ if self._schema is not None: - # Use the schema to get the full dotted path for nested fields - full_name = self._schema.find_column_name(term.ref().field.field_id) - if full_name is not None: - # If the field name contains dots, it's a nested field - # Convert "parent.child" to ("parent", "child") for PyArrow - if "." in full_name: - return tuple(full_name.split(".")) - return full_name + field_id = term.ref().field.field_id + if self._schema.find_column_name(field_id) is not None: + # Walk up the struct ancestors by field ID, instead of splitting the dotted full name + names = [self._schema.find_field(field_id).name] + parent_id = self._schema._lazy_id_to_parent.get(field_id) + while parent_id is not None: + names.insert(0, self._schema.find_field(parent_id).name) + parent_id = self._schema._lazy_id_to_parent.get(parent_id) + return tuple(names) if len(names) > 1 else names[0] # Fallback to just the field name if schema is not available return term.ref().field.name @@ -1871,10 +1873,12 @@ def _task_to_record_batches( pyarrow_filter = None if bound_row_filter is not AlwaysTrue(): translated_row_filter = translate_column_names( - bound_row_filter, file_schema, case_sensitive=case_sensitive, projected_field_values=projected_missing_fields + bound_row_filter, + file_schema, + case_sensitive=case_sensitive, + projected_field_values=projected_missing_fields, + table_schema=table_schema, ) - # Rewrite NOT into the complementary predicates, as the manifest and metrics evaluators do, so a row - # matches the same predicate that decided whether its file was read bound_file_filter = rewrite_not(bind(file_schema, translated_row_filter, case_sensitive=case_sensitive)) pyarrow_filter = expression_to_pyarrow(bound_file_filter, file_schema) @@ -2056,6 +2060,14 @@ def __init__( # Register extension types before inspecting any data file schemas. self._arrow_schema = schema_to_pyarrow(projected_schema, include_field_ids=False) self._bound_row_filter = bind(table_metadata.schema(), row_filter, case_sensitive=case_sensitive) + # A filter on a nested field also reads its struct ancestors, which are NULL where the field reads as NULL + schema = table_metadata.schema() + self._filter_ancestor_field_ids: set[int] = set() + for field_id in extract_field_ids(self._bound_row_filter): + parent_id = schema._lazy_id_to_parent.get(field_id) + while parent_id is not None and isinstance(schema.find_type(parent_id), StructType): + self._filter_ancestor_field_ids.add(parent_id) + parent_id = schema._lazy_id_to_parent.get(parent_id) self._case_sensitive = case_sensitive self._limit = limit self._downcast_ns_timestamp_to_us = Config().get_bool(DOWNCAST_NS_TIMESTAMP_TO_US_ON_WRITE) @@ -2065,7 +2077,7 @@ def __init__( def _projected_field_ids(self) -> set[int]: """Set of field IDs that should be projected from the data files.""" schema = self._table_metadata.schema() - filter_field_ids = extract_field_ids(self._bound_row_filter) + filter_field_ids = extract_field_ids(self._bound_row_filter) | self._filter_ancestor_field_ids # A list or map cannot be projected by its own ID, so a filter on one reads its nested fields instead nested_field_ids = prune_columns( schema, {id for id in filter_field_ids if isinstance(schema.find_type(id), (MapType, ListType))} diff --git a/tests/expressions/test_visitors.py b/tests/expressions/test_visitors.py index 2bc77d50e9..de5d7c2860 100644 --- a/tests/expressions/test_visitors.py +++ b/tests/expressions/test_visitors.py @@ -1770,6 +1770,22 @@ def test_translate_column_names_different_column_names() -> None: assert translated_expr.literal == literal("test_value") +def test_translate_column_names_not_on_missing_top_level_column_keeps_its_result() -> None: + """NOT over a predicate on a missing top-level column keeps the result of its default-value constant.""" + table_schema = Schema( + NestedField(field_id=1, name="id", field_type=IntegerType(), required=False), + NestedField(field_id=2, name="d", field_type=IntegerType(), required=False), + schema_id=1, + ) + file_schema = Schema(NestedField(field_id=1, name="id", field_type=IntegerType(), required=False), schema_id=1) + for unbound_expr, expected in [ + (Not(LessThan("d", 4)), AlwaysTrue()), + (Not(IsNull("d")), AlwaysFalse()), + ]: + bound_expr = visit(unbound_expr, visitor=BindVisitor(schema=table_schema, case_sensitive=True)) + assert translate_column_names(bound_expr, file_schema, case_sensitive=True) == expected, unbound_expr + + def test_translate_column_names_missing_column() -> None: """Test translate_column_names when column is missing from file schema (such as in schema evolution).""" # Original schema diff --git a/tests/io/test_pyarrow.py b/tests/io/test_pyarrow.py index e1e99be4c7..3f7f32ee0c 100644 --- a/tests/io/test_pyarrow.py +++ b/tests/io/test_pyarrow.py @@ -75,6 +75,7 @@ Or, ) from pyiceberg.expressions.literals import literal +from pyiceberg.expressions.parser import parse from pyiceberg.io import ADLS_ACCOUNT_NAME, S3_RETRY_STRATEGY_IMPL, S3_SSL_CA_CERT, InputStream, OutputStream, load_file_io from pyiceberg.io.pyarrow import ( ICEBERG_SCHEMA, @@ -1143,6 +1144,7 @@ def _write_table_to_data_file(filepath: str, schema: pa.Schema, table: pa.Table) partition={}, record_count=len(table), file_size_in_bytes=22, # This is not relevant for now + spec_id=0, ) @@ -1611,6 +1613,191 @@ def test_identity_transform_column_projection_with_falsy_value( ) +def _v3_table_metadata(tmpdir: str, table_schema: Schema) -> TableMetadataV3: + return TableMetadataV3( + location=str(tmpdir), + last_column_id=table_schema.highest_field_id, + schemas=[table_schema], + partition_specs=[PartitionSpec()], + next_row_id=0, + ) + + +def _write_deletion_vector(tmpdir: str, data_file: DataFile, positions: list[int]) -> DataFile: + dv_blob = _deletion_vector_blob(_deletion_vector_bitmap_payload(positions)) + dv_path = f"{tmpdir}/deletes.bin" + with open(dv_path, "wb") as f: + f.write(dv_blob) + return DataFile.from_args( + _table_format_version=3, + content=DataFileContent.POSITION_DELETES, + file_path=dv_path, + file_format=FileFormat.PUFFIN, + record_count=len(positions), + referenced_data_file=data_file.file_path, + content_offset=0, + content_size_in_bytes=len(dv_blob), + ) + + +def _scan_ids(table_metadata: TableMetadataV3, data_file: DataFile, row_filter: str, delete_files: set[DataFile]) -> list[int]: + # Only id is projected, so a filter on another field reads that field for the filter alone + projected_schema = Schema(NestedField(1, "id", LongType(), required=False)) + task = FileScanTask(data_file=data_file, delete_files=delete_files) + return ArrowScan(table_metadata, PyArrowFileIO(), projected_schema, parse(row_filter)).to_table([task])["id"].to_pylist() + + +def test_missing_nested_field_under_null_struct_reads_as_null(tmpdir: str) -> None: + """A field added under optional structs is NULL in the rows where a struct is NULL, with or without deletes.""" + table_schema = Schema( + NestedField(1, "id", LongType(), required=False), + NestedField( + 2, + "pt", + StructType( + NestedField(3, "a", IntegerType(), required=False), + NestedField(4, "c", IntegerType(), required=False, initial_default=5), + NestedField( + 5, + "inner", + StructType( + NestedField(6, "z", IntegerType(), required=False), + NestedField(7, "c2", IntegerType(), required=False, initial_default=5), + ), + required=False, + ), + NestedField( + 8, + "req", + StructType( + NestedField(9, "w", IntegerType(), required=False), + NestedField(10, "c3", IntegerType(), required=False, initial_default=5), + ), + required=True, + ), + NestedField(11, "n", IntegerType(), required=False), + ), + required=False, + ), + ) + # The file has pt.a, pt.inner.z and pt.req.w only. Row 2 has no pt, so its defaulted fields and pt.n are NULL. + # Row 3 has no inner, so its pt.inner.c2 is NULL. + arrow_schema = schema_to_pyarrow(table_schema.select("id", "pt.a", "pt.inner.z", "pt.req.w")) + arrow_table = pa.table( + { + "id": [1, 2, 3], + "pt": [{"a": 1, "inner": {"z": 1}, "req": {"w": 1}}, None, {"a": 2, "inner": None, "req": {"w": 2}}], + }, + schema=arrow_schema, + ) + data_file = _write_table_to_data_file(f"{tmpdir}/nested_default.parquet", arrow_schema, arrow_table) + table_metadata = _v3_table_metadata(tmpdir, table_schema) + dv = _write_deletion_vector(tmpdir, data_file, [0]) + + for row_filter, rows in [ + ("pt.c = 5", [1, 3]), + ("pt.c IN (4, 5)", [1, 3]), + ("pt.c = 5 OR pt.c = 6", [1, 3]), + ("pt.c > 4", [1, 3]), + ("pt.c < 6", [1, 3]), + ("pt.c <= 5", [1, 3]), + ("pt.c >= 5", [1, 3]), + ("pt.c IS NULL", [2]), + ("NOT (pt.c IS NULL)", [1, 3]), + ("NOT (pt.c > 4)", []), + ("NOT (pt.c < 4)", [1, 3]), + ("NOT (pt.c > 4 AND id = 2)", [1, 3]), + ("NOT (pt.c < 4 OR id = 1)", [3]), + ("NOT (pt.c != 5)", [1, 3]), + ("NOT (pt.c NOT IN (4, 5))", [1, 3]), + ("pt.inner.c2 = 5", [1]), + ("pt.inner.c2 IS NULL", [2, 3]), + ("pt.req.c3 = 5", [1, 3]), + ("NOT (pt.req.c3 < 4)", [1, 3]), + ("pt.n IS NULL", [1, 2, 3]), + ("NOT (pt.n < 4)", []), + ]: + assert _scan_ids(table_metadata, data_file, row_filter, set()) == rows, row_filter + # The deletion vector removes row 1, so the filter runs after the deletes and reads the struct ancestors + assert _scan_ids(table_metadata, data_file, row_filter, {dv}) == [row for row in rows if row != 1], row_filter + + +def test_missing_nested_field_under_renamed_null_struct(tmpdir: str) -> None: + """A struct renamed from old.pt to new.pt is matched by field ID, so its NULL row reads the added field as NULL.""" + table_schema = Schema( + NestedField(1, "id", LongType(), required=False), + NestedField( + 2, + "new.pt", + StructType( + NestedField(3, "a", IntegerType(), required=False), + NestedField(4, "c", IntegerType(), required=False, initial_default=5), + ), + required=False, + ), + ) + arrow_schema = pa.schema( + [ + pa.field("id", pa.int64(), metadata={PYARROW_PARQUET_FIELD_ID_KEY: "1"}), + pa.field( + "old.pt", + pa.struct([pa.field("a", pa.int32(), metadata={PYARROW_PARQUET_FIELD_ID_KEY: "3"})]), + metadata={PYARROW_PARQUET_FIELD_ID_KEY: "2"}, + ), + ] + ) + arrow_table = pa.table({"id": [1, 2, 3], "old.pt": [{"a": 1}, None, {"a": 2}]}, schema=arrow_schema) + data_file = _write_table_to_data_file(f"{tmpdir}/renamed_nested_default.parquet", arrow_schema, arrow_table) + table_metadata = _v3_table_metadata(tmpdir, table_schema) + dv = _write_deletion_vector(tmpdir, data_file, [0]) + + for row_filter, rows in [ + ("new.pt.c = 5", [1, 3]), + ("new.pt.c IS NULL", [2]), + ]: + assert _scan_ids(table_metadata, data_file, row_filter, set()) == rows, row_filter + assert _scan_ids(table_metadata, data_file, row_filter, {dv}) == [row for row in rows if row != 1], row_filter + + +def test_missing_fields_absent_from_file_read_as_null(tmpdir: str) -> None: + """A struct the file lacks is NULL in every row. NOT keeps its result on a top-level or a required-struct field.""" + table_schema = Schema( + NestedField(1, "id", LongType(), required=False), + NestedField(2, "d", IntegerType(), required=False), + NestedField(3, "pt", StructType(NestedField(4, "c", IntegerType(), required=False, initial_default=5)), required=False), + NestedField( + 5, + "rq", + StructType(NestedField(6, "x", IntegerType(), required=False), NestedField(7, "c2", IntegerType(), required=False)), + required=True, + ), + ) + arrow_schema = pa.schema( + [ + pa.field("id", pa.int64(), metadata={PYARROW_PARQUET_FIELD_ID_KEY: "1"}), + pa.field( + "rq", + pa.struct([pa.field("x", pa.int32(), metadata={PYARROW_PARQUET_FIELD_ID_KEY: "6"})]), + metadata={PYARROW_PARQUET_FIELD_ID_KEY: "5"}, + ), + ] + ) + arrow_table = pa.table({"id": [1, 2, 3], "rq": [{"x": 1}, {"x": 1}, {"x": 1}]}, schema=arrow_schema) + data_file = _write_table_to_data_file(f"{tmpdir}/no_pt.parquet", arrow_schema, arrow_table) + table_metadata = _v3_table_metadata(tmpdir, table_schema) + + for row_filter, rows in [ + ("pt.c = 5", []), + ("pt.c IS NULL", [1, 2, 3]), + ("NOT (pt.c > 4)", []), + ("NOT (d > 4)", [1, 2, 3]), + ("NOT (d IS NULL)", []), + # A required struct is never NULL, so NOT keeps its result on a field under it + ("NOT (rq.c2 > 4)", [1, 2, 3]), + ]: + assert _scan_ids(table_metadata, data_file, row_filter, set()) == rows, row_filter + + def test_identity_transform_column_projection_uuid(tmp_path: str, catalog: InMemoryCatalog) -> None: """A filter on a uuid identity partition column matches the files that do not contain the column.""" schema = Schema( From 0dabae8beb7d848e3cc460b95df3a624504e88bc Mon Sep 17 00:00:00 2001 From: rahulsmahadev Date: Wed, 25 Nov 2026 13:34:42 +0000 Subject: [PATCH 2/2] Honor NULL ancestors for NOT IN, STARTS WITH and IS NAN too The expression evaluator and Arrow agree on NULL for these predicates, as for = and IN, so a row under a NULL struct no longer matches the default. NOT over NOT STARTS WITH and NOT NAN is pushed into STARTS WITH and IS NAN. Drop the test cases that asserted main's results for top-level and required-only NOT, which a file storing the NULLs and Java do not return, and the visitor test that did not reach the new code. Restore the comment on the rewrite_not line. Co-authored-by: Isaac --- pyiceberg/expressions/visitors.py | 16 +++++++++------ pyiceberg/io/pyarrow.py | 3 ++- tests/expressions/test_visitors.py | 16 --------------- tests/io/test_pyarrow.py | 31 ++++++++++-------------------- 4 files changed, 22 insertions(+), 44 deletions(-) diff --git a/pyiceberg/expressions/visitors.py b/pyiceberg/expressions/visitors.py index 0bd088e909..f323104c19 100644 --- a/pyiceberg/expressions/visitors.py +++ b/pyiceberg/expressions/visitors.py @@ -862,20 +862,24 @@ def inclusive_projection( return InclusiveProjection(schema, spec, case_sensitive).project -# These predicates use Arrow's NULL behavior. != and NOT IN retain the existing default-value result (see #4276). -_NULL_STRICT_PREDICATES = ( +# For these predicates the expression evaluator and Arrow give the same result for a NULL value. For !=, NOT STARTS WITH +# and NOT NAN the evaluator matches NULL and Arrow does not, so those keep the default-value result. +_NULL_CONSISTENT_PREDICATES = ( BoundEqualTo, BoundIn, + BoundNotIn, BoundLessThan, BoundLessThanOrEqual, BoundGreaterThan, BoundGreaterThanOrEqual, BoundIsNull, BoundNotNull, + BoundStartsWith, + BoundIsNaN, ) # A NOT over these predicates is pushed into their complements, so NOT (c != 5) is handled as c = 5 -_NESTED_NOT_PREDICATES = (*_NULL_STRICT_PREDICATES, BoundNotEqualTo, BoundNotIn) +_NESTED_NOT_PREDICATES = (*_NULL_CONSISTENT_PREDICATES, BoundNotEqualTo, BoundNotStartsWith, BoundNotNaN) class _ColumnNameTranslator(BooleanExpressionVisitor[BooleanExpression]): @@ -953,7 +957,7 @@ def visit_bound_predicate(self, predicate: BoundPredicate) -> BooleanExpression: ) evaluate = expression_evaluator(Schema(field), pred, case_sensitive=self.case_sensitive) matches_value = evaluate(Record(field_value)) - if self.table_schema is None or not isinstance(predicate, _NULL_STRICT_PREDICATES): + if self.table_schema is None or not isinstance(predicate, _NULL_CONSISTENT_PREDICATES): return AlwaysTrue() if matches_value else AlwaysFalse() # A row whose optional ancestor struct is NULL reads the field as NULL, so it matches like a NULL value matches_null = evaluate(Record(None)) @@ -980,7 +984,7 @@ def _ancestors_present(self, table_schema: Schema, field_id: int) -> BooleanExpr parent_name = self.file_schema.find_column_name(parent_id) if parent_name is None: # The struct is missing from the file too, so its value is the same in every row - if self.projected_field_values.get(parent_id, parent.initial_default) is None: + if parent.initial_default is None: return AlwaysFalse() else: present = And(present, NotNull(parent_name)) @@ -1011,7 +1015,7 @@ def _rewrite_nested_not( """Push NOT down to the predicates, and complement those on a missing nested field. A row whose optional struct is NULL reads such a field as NULL. NOT (c < 4) must not match that row, as c >= 4 - does not. Other negations are kept, so their results stay the same as on main. + does not. Other negations are left in place. """ if isinstance(expr, Not): return _rewrite_nested_not(expr.child, file_schema, table_schema, not negated) diff --git a/pyiceberg/io/pyarrow.py b/pyiceberg/io/pyarrow.py index f94e9000dd..f3ea9b7aaa 100644 --- a/pyiceberg/io/pyarrow.py +++ b/pyiceberg/io/pyarrow.py @@ -952,7 +952,6 @@ def _get_field_name(self, term: BoundTerm) -> str | tuple[str, ...]: if self._schema is not None: field_id = term.ref().field.field_id if self._schema.find_column_name(field_id) is not None: - # Walk up the struct ancestors by field ID, instead of splitting the dotted full name names = [self._schema.find_field(field_id).name] parent_id = self._schema._lazy_id_to_parent.get(field_id) while parent_id is not None: @@ -1879,6 +1878,8 @@ def _task_to_record_batches( projected_field_values=projected_missing_fields, table_schema=table_schema, ) + # Rewrite NOT into the complementary predicates, as the manifest and metrics evaluators do, so a row + # matches the same predicate that decided whether its file was read bound_file_filter = rewrite_not(bind(file_schema, translated_row_filter, case_sensitive=case_sensitive)) pyarrow_filter = expression_to_pyarrow(bound_file_filter, file_schema) diff --git a/tests/expressions/test_visitors.py b/tests/expressions/test_visitors.py index de5d7c2860..2bc77d50e9 100644 --- a/tests/expressions/test_visitors.py +++ b/tests/expressions/test_visitors.py @@ -1770,22 +1770,6 @@ def test_translate_column_names_different_column_names() -> None: assert translated_expr.literal == literal("test_value") -def test_translate_column_names_not_on_missing_top_level_column_keeps_its_result() -> None: - """NOT over a predicate on a missing top-level column keeps the result of its default-value constant.""" - table_schema = Schema( - NestedField(field_id=1, name="id", field_type=IntegerType(), required=False), - NestedField(field_id=2, name="d", field_type=IntegerType(), required=False), - schema_id=1, - ) - file_schema = Schema(NestedField(field_id=1, name="id", field_type=IntegerType(), required=False), schema_id=1) - for unbound_expr, expected in [ - (Not(LessThan("d", 4)), AlwaysTrue()), - (Not(IsNull("d")), AlwaysFalse()), - ]: - bound_expr = visit(unbound_expr, visitor=BindVisitor(schema=table_schema, case_sensitive=True)) - assert translate_column_names(bound_expr, file_schema, case_sensitive=True) == expected, unbound_expr - - def test_translate_column_names_missing_column() -> None: """Test translate_column_names when column is missing from file schema (such as in schema evolution).""" # Original schema diff --git a/tests/io/test_pyarrow.py b/tests/io/test_pyarrow.py index 3f7f32ee0c..3fecdfd9fa 100644 --- a/tests/io/test_pyarrow.py +++ b/tests/io/test_pyarrow.py @@ -1676,6 +1676,8 @@ def test_missing_nested_field_under_null_struct_reads_as_null(tmpdir: str) -> No required=True, ), NestedField(11, "n", IntegerType(), required=False), + NestedField(12, "s", StringType(), required=False, initial_default="abc"), + NestedField(13, "fn", DoubleType(), required=False, initial_default=float("nan")), ), required=False, ), @@ -1710,6 +1712,11 @@ def test_missing_nested_field_under_null_struct_reads_as_null(tmpdir: str) -> No ("NOT (pt.c < 4 OR id = 1)", [3]), ("NOT (pt.c != 5)", [1, 3]), ("NOT (pt.c NOT IN (4, 5))", [1, 3]), + ("pt.c NOT IN (4, 5)", [2]), + ("NOT (pt.c IN (4, 5))", [2]), + ("pt.s LIKE 'ab%'", [1, 3]), + ("NOT (pt.s NOT LIKE 'ab%')", [1, 3]), + ("pt.fn IS NAN", [1, 3]), ("pt.inner.c2 = 5", [1]), ("pt.inner.c2 IS NULL", [2, 3]), ("pt.req.c3 = 5", [1, 3]), @@ -1760,29 +1767,14 @@ def test_missing_nested_field_under_renamed_null_struct(tmpdir: str) -> None: def test_missing_fields_absent_from_file_read_as_null(tmpdir: str) -> None: - """A struct the file lacks is NULL in every row. NOT keeps its result on a top-level or a required-struct field.""" + """A struct the file lacks is NULL in every row, so a field under it reads as NULL despite its default.""" table_schema = Schema( NestedField(1, "id", LongType(), required=False), NestedField(2, "d", IntegerType(), required=False), NestedField(3, "pt", StructType(NestedField(4, "c", IntegerType(), required=False, initial_default=5)), required=False), - NestedField( - 5, - "rq", - StructType(NestedField(6, "x", IntegerType(), required=False), NestedField(7, "c2", IntegerType(), required=False)), - required=True, - ), - ) - arrow_schema = pa.schema( - [ - pa.field("id", pa.int64(), metadata={PYARROW_PARQUET_FIELD_ID_KEY: "1"}), - pa.field( - "rq", - pa.struct([pa.field("x", pa.int32(), metadata={PYARROW_PARQUET_FIELD_ID_KEY: "6"})]), - metadata={PYARROW_PARQUET_FIELD_ID_KEY: "5"}, - ), - ] ) - arrow_table = pa.table({"id": [1, 2, 3], "rq": [{"x": 1}, {"x": 1}, {"x": 1}]}, schema=arrow_schema) + arrow_schema = pa.schema([pa.field("id", pa.int64(), metadata={PYARROW_PARQUET_FIELD_ID_KEY: "1"})]) + arrow_table = pa.table({"id": [1, 2, 3]}, schema=arrow_schema) data_file = _write_table_to_data_file(f"{tmpdir}/no_pt.parquet", arrow_schema, arrow_table) table_metadata = _v3_table_metadata(tmpdir, table_schema) @@ -1790,10 +1782,7 @@ def test_missing_fields_absent_from_file_read_as_null(tmpdir: str) -> None: ("pt.c = 5", []), ("pt.c IS NULL", [1, 2, 3]), ("NOT (pt.c > 4)", []), - ("NOT (d > 4)", [1, 2, 3]), ("NOT (d IS NULL)", []), - # A required struct is never NULL, so NOT keeps its result on a field under it - ("NOT (rq.c2 > 4)", [1, 2, 3]), ]: assert _scan_ids(table_metadata, data_file, row_filter, set()) == rows, row_filter