diff --git a/pyiceberg/expressions/visitors.py b/pyiceberg/expressions/visitors.py index 7504548507..f323104c19 100644 --- a/pyiceberg/expressions/visitors.py +++ b/pyiceberg/expressions/visitors.py @@ -862,6 +862,26 @@ def inclusive_projection( return InclusiveProjection(schema, spec, case_sensitive).project +# 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_CONSISTENT_PREDICATES, BoundNotEqualTo, BoundNotStartsWith, BoundNotNaN) + + class _ColumnNameTranslator(BooleanExpressionVisitor[BooleanExpression]): """Converts the column names with the ones in the actual file. @@ -869,6 +889,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 +899,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 +955,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_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)) + 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 +975,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 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 left in place. + """ + 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..f3ea9b7aaa 100644 --- a/pyiceberg/io/pyarrow.py +++ b/pyiceberg/io/pyarrow.py @@ -946,17 +946,18 @@ 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: + 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,7 +1872,11 @@ 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 @@ -2056,6 +2061,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 +2078,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/io/test_pyarrow.py b/tests/io/test_pyarrow.py index e1e99be4c7..3fecdfd9fa 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,180 @@ 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), + NestedField(12, "s", StringType(), required=False, initial_default="abc"), + NestedField(13, "fn", DoubleType(), required=False, initial_default=float("nan")), + ), + 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.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]), + ("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, 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), + ) + 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) + + for row_filter, rows in [ + ("pt.c = 5", []), + ("pt.c IS NULL", [1, 2, 3]), + ("NOT (pt.c > 4)", []), + ("NOT (d IS NULL)", []), + ]: + 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(