From ea61c07991646cf78350a4539dca372ee17e9343 Mon Sep 17 00:00:00 2001 From: rahulsmahadev Date: Fri, 20 Nov 2026 19:03:50 +0000 Subject: [PATCH 1/5] Find partition source columns the same way as the writer _determine_partitions read the partition source from the input by its full name in the table schema, split on dots, while the writer finds each column by following the table's struct path with the input's own names. A dotted struct name raised KeyError, and an input with field IDs from before a rename got its partition values from another column, so filtered scans missed rows. Follow the writer's path and names instead. Co-authored-by: Isaac --- pyiceberg/io/pyarrow.py | 54 +++++++++++--------- tests/catalog/test_catalog_behaviors.py | 66 +++++++++++++++++++++++++ tests/io/test_pyarrow.py | 26 ++++++++++ 3 files changed, 124 insertions(+), 22 deletions(-) diff --git a/pyiceberg/io/pyarrow.py b/pyiceberg/io/pyarrow.py index 20333882b5..1eae25fff9 100644 --- a/pyiceberg/io/pyarrow.py +++ b/pyiceberg/io/pyarrow.py @@ -3324,7 +3324,9 @@ def _dataframe_to_data_files( ), ) else: - partitions = _determine_partitions(spec=table_metadata.spec(), schema=table_metadata.schema(), arrow_table=df) + partitions = _determine_partitions( + spec=table_metadata.spec(), schema=table_metadata.schema(), arrow_table=df, input_schema=task_schema + ) yield from write_file( io=io, table_metadata=table_metadata, @@ -3348,9 +3350,14 @@ class _TablePartition: arrow_table_partition: pa.Table -def _determine_partitions(spec: PartitionSpec, schema: Schema, arrow_table: pa.Table) -> Iterable[_TablePartition]: +def _determine_partitions( + spec: PartitionSpec, schema: Schema, arrow_table: pa.Table, input_schema: Schema | None = None +) -> Iterable[_TablePartition]: """Based on the iceberg table partition spec, filter the arrow table into partitions with their keys. + The source columns are found by field ID in input_schema, the Iceberg schema of the arrow table (schema if not + given), whose names can differ from schema, e.g. when the arrow table has field IDs from before a rename. + Example: Input: An arrow table with partition key of ['n_legs', 'year'] and with data of @@ -3378,10 +3385,7 @@ def _determine_partitions(spec: PartitionSpec, schema: Schema, arrow_table: pa.T for partition, name in zip(spec.fields, partition_fields, strict=True): source_field = schema.find_field(partition.source_id) - full_field_name = schema.find_column_name(partition.source_id) - if full_field_name is None: - raise ValueError(f"Could not find column name for field ID: {partition.source_id}") - field_array = _get_field_from_arrow_table(arrow_table, full_field_name) + field_array = _get_field_from_arrow_table(arrow_table, schema, partition.source_id, input_schema) partition_array = partition.transform.pyarrow_transform(source_field.field_type)(field_array) # PyArrow has no group by or equality kernels for extension types such as arrow.uuid, so use their storage type if isinstance(partition_array.type, pa.BaseExtensionType): @@ -3427,30 +3431,36 @@ def _partition_value_filter(partition_field_name: str, value: Any) -> pc.Express return pc.field(partition_field_name) == value -def _get_field_from_arrow_table(arrow_table: pa.Table, field_path: str) -> pa.Array: - """Get a field from an Arrow table, supporting both literal field names and nested field paths. +def _get_field_from_arrow_table( + arrow_table: pa.Table, schema: Schema, field_id: int, input_schema: Schema | None = None +) -> pa.Array: + """Get a field from an Arrow table by its field ID, where the field can be nested in structs. - This function handles two cases: - 1. Literal field names that may contain dots (e.g., "some.id") - 2. Nested field paths using dot notation (e.g., "bar.baz" for nested access) + Follow the target schema's parent IDs and resolve each name in input_schema, matching the writer. + A name can contain dots (e.g., "some.id"), so a nested field's full name cannot be split into these names. Args: arrow_table: The Arrow table containing the field - field_path: Field name or dot-separated path + schema: The target Iceberg table schema + field_id: The ID of the field + input_schema: The Iceberg schema of the Arrow table, if different from schema Returns: The field as a PyArrow Array Raises: + ValueError: If a field ID on the path is missing from either schema KeyError: If the field path cannot be resolved """ - # Try exact column name match (handles field names containing literal dots) - if field_path in arrow_table.column_names: - return arrow_table[field_path] - - # If not found as exact name, treat as nested field path - path_parts = field_path.split(".") - # Get the struct column from the table (e.g., "bar" from "bar.baz") - field_array = arrow_table[path_parts[0]] - # Navigate into the struct using the remaining path parts - return pc.struct_field(field_array, path_parts[1:]) + source_schema = input_schema if input_schema is not None else schema + # Match ArrowAccessor: follow the target's parent IDs using each field's input name. + names = [source_schema.find_field(field_id).name] + parent_id = schema._lazy_id_to_parent.get(field_id) + while parent_id is not None: + names.append(source_schema.find_field(parent_id).name) + parent_id = schema._lazy_id_to_parent.get(parent_id) + + # Get the column from the table (e.g., "bar" for "bar.baz") and navigate into its structs + column_name, *nested_names = reversed(names) + field_array = arrow_table[column_name] + return pc.struct_field(field_array, nested_names) if nested_names else field_array diff --git a/tests/catalog/test_catalog_behaviors.py b/tests/catalog/test_catalog_behaviors.py index a5099e4e6b..6eaf7f1bfb 100644 --- a/tests/catalog/test_catalog_behaviors.py +++ b/tests/catalog/test_catalog_behaviors.py @@ -744,6 +744,72 @@ def test_table_properties_raise_for_none_value( # Append table +def test_append_to_identity_partitioned_table_with_dotted_names(catalog: Catalog) -> None: + catalog.create_namespace("default") + # The names from the top-level column down to the partition source, where a name can contain dots + paths = [("a.b",), ("bar", "baz"), ("foo", "bar", "baz"), ("a.b", "c"), ("a", "b.c"), ("root", "a.b", "c")] + for i, path in enumerate(paths): + column_type: pa.DataType = pa.string() + values: list[Any] = ["x", "y", None] + for name in reversed(path[1:]): + column_type = pa.struct([(name, column_type)]) + values = [{name: value} for value in values] + arrow_schema = pa.schema([("id", pa.int64()), (path[0], column_type)]) + df = pa.Table.from_pydict({"id": [1, 2, 3], path[0]: values}, schema=arrow_schema) + tbl = catalog.create_table(f"default.dotted_partition_source_{i}", schema=df.schema) + with tbl.update_spec() as update: + update.add_field(".".join(path), IdentityTransform(), "p") + + tbl.append(df) + + assert sorted(tbl.scan().to_arrow().to_pylist(), key=lambda row: row["id"]) == df.to_pylist(), path + assert {task.file.partition[0] for task in tbl.scan().plan_files()} == {"x", "y", None}, path + + +def test_append_with_field_ids_after_swapping_column_names(catalog: Catalog) -> None: + catalog.create_namespace("default") + struct_type = pa.struct([("c", pa.string())]) + # Each case swaps the names of the two columns after the Arrow table took its field IDs from the table schema + cases: list[tuple[pa.Schema, dict[str, Any], str, str]] = [ + (pa.schema([("a", pa.string()), ("b", pa.string())]), {"a": "x", "b": "y"}, "a", "b"), + (pa.schema([("left", struct_type), ("a.b", struct_type)]), {"left": {"c": "x"}, "a.b": {"c": "y"}}, "left.c", "a.b.c"), + ] + for i, (arrow_schema, row, source_name, renamed_source_name) in enumerate(cases): + tbl = catalog.create_table(f"default.swapped_names_{i}", schema=arrow_schema) + with tbl.update_spec() as spec_update: + spec_update.add_field(source_name, IdentityTransform(), "p") + df = pa.Table.from_pylist([row], schema=tbl.schema().as_arrow()) + first, second = arrow_schema.names + for old_name, new_name in [(first, "tmp"), (second, first), ("tmp", second)]: + with tbl.update_schema() as schema_update: + schema_update.rename_column(old_name, new_name) + + tbl.append(df) + + # The partition value comes from the column that the source field is written from + assert [task.file.partition[0] for task in tbl.scan().plan_files()] == ["x"], source_name + swapped_row = {first: row[second], second: row[first]} + assert tbl.scan(row_filter=f"{renamed_source_name} = 'x'").to_arrow().to_pylist() == [swapped_row], source_name + + +def test_partition_values_follow_writer_struct_path(catalog: Catalog) -> None: + catalog.create_namespace("default") + struct_type = pa.struct([("x", pa.string())]) + tbl = catalog.create_table("default.partition_input_parents", schema=pa.schema([("s", struct_type), ("t", struct_type)])) + with tbl.update_spec() as spec_update: + spec_update.add_field("s.x", IdentityTransform(), "p") + # Swap the struct types, so that each leaf field ID of the input is under the other parent + s_field, t_field = tbl.schema().as_arrow() + input_schema = pa.schema([s_field.with_type(t_field.type), t_field.with_type(s_field.type)]) + tbl.append(pa.Table.from_pylist([{"s": {"x": "X"}, "t": {"x": "Y"}}], schema=input_schema)) + + # The partition value and the filtered scan agree with the row that was written + written_rows = tbl.scan().to_arrow().to_pylist() + value = written_rows[0]["s"]["x"] + assert [task.file.partition[0] for task in tbl.scan().plan_files()] == [value] + assert tbl.scan(row_filter=f"s.x = '{value}'").to_arrow().to_pylist() == written_rows + + def test_append_table(catalog: Catalog, table_schema_simple: Schema, test_table_identifier: Identifier) -> None: namespace = Catalog.namespace_from(test_table_identifier) catalog.create_namespace(namespace) diff --git a/tests/io/test_pyarrow.py b/tests/io/test_pyarrow.py index 439405d121..18dad07f17 100644 --- a/tests/io/test_pyarrow.py +++ b/tests/io/test_pyarrow.py @@ -3436,6 +3436,32 @@ def test_partition_for_nested_field() -> None: assert partition_values == {486729, 486730} +def test_partition_for_nested_field_with_dotted_names() -> None: + # The full names a.b.c, d.e.f and g.h.i.j cannot be split on dots into the names of the nested fields + schema = Schema( + NestedField(1, "a.b", StructType(NestedField(2, "c", StringType()))), + NestedField(3, "d", StructType(NestedField(4, "e.f", StringType()))), + NestedField(5, "g", StructType(NestedField(6, "h.i", StructType(NestedField(7, "j", StringType()))))), + ) + spec = PartitionSpec( + PartitionField(source_id=2, field_id=1000, transform=IdentityTransform(), name="c"), + PartitionField(source_id=4, field_id=1001, transform=IdentityTransform(), name="e_f"), + PartitionField(source_id=7, field_id=1002, transform=IdentityTransform(), name="j"), + ) + rows = [ + {"a.b": {"c": "x"}, "d": {"e.f": "y"}, "g": {"h.i": {"j": "z"}}}, + {"a.b": {"c": "x"}, "d": {"e.f": None}, "g": None}, + ] + arrow_table = pa.Table.from_pylist(rows, schema=schema.as_arrow()) + + partitions = list(_determine_partitions(spec, schema, arrow_table)) + + assert {p.partition_key.partition: p.arrow_table_partition.to_pylist() for p in partitions} == { + Record("x", "y", "z"): [rows[0]], + Record("x", None, None): [rows[1]], + } + + def test_partition_for_deep_nested_field() -> None: schema = Schema( NestedField( From 0c164c1ee11eccf5cf616ec790311002acd3a45d Mon Sep 17 00:00:00 2001 From: rahulsmahadev Date: Mon, 30 Nov 2026 02:09:54 +0000 Subject: [PATCH 2/5] Partition on nulls when an optional source column is missing Appending input without an optional column that a partition field uses failed in _determine_partitions, although the schema check allows a missing optional column and the writer stores nulls for it. Use those nulls as the source values, so the rows go to the null partition. Co-authored-by: Isaac --- pyiceberg/io/pyarrow.py | 22 +++++++++++------ tests/catalog/test_catalog_behaviors.py | 33 +++++++++++++++++++++++++ tests/io/test_pyarrow.py | 13 ++++++++++ 3 files changed, 61 insertions(+), 7 deletions(-) diff --git a/pyiceberg/io/pyarrow.py b/pyiceberg/io/pyarrow.py index 1eae25fff9..3630fdfa33 100644 --- a/pyiceberg/io/pyarrow.py +++ b/pyiceberg/io/pyarrow.py @@ -3438,6 +3438,7 @@ def _get_field_from_arrow_table( Follow the target schema's parent IDs and resolve each name in input_schema, matching the writer. A name can contain dots (e.g., "some.id"), so a nested field's full name cannot be split into these names. + When an optional field on the path is missing from input_schema, return the nulls that the writer stores. Args: arrow_table: The Arrow table containing the field @@ -3449,18 +3450,25 @@ def _get_field_from_arrow_table( The field as a PyArrow Array Raises: - ValueError: If a field ID on the path is missing from either schema + ValueError: If a field ID on the path is missing from schema, or a required one from input_schema KeyError: If the field path cannot be resolved """ source_schema = input_schema if input_schema is not None else schema # Match ArrowAccessor: follow the target's parent IDs using each field's input name. - names = [source_schema.find_field(field_id).name] - parent_id = schema._lazy_id_to_parent.get(field_id) - while parent_id is not None: - names.append(source_schema.find_field(parent_id).name) - parent_id = schema._lazy_id_to_parent.get(parent_id) + field_ids = [field_id] + while (parent_id := schema._lazy_id_to_parent.get(field_ids[-1])) is not None: + field_ids.append(parent_id) + names: list[str] = [] + for current_id in reversed(field_ids): + if current_id not in source_schema._lazy_id_to_field and schema.find_field(current_id).optional: + # The writer stores nulls for a missing optional field and the fields nested in it + field_type = schema.find_field(field_id).field_type + # The truncate kernel has no large_binary support: https://github.com/apache/iceberg-rust/issues/3119 + arrow_type = pa.binary() if isinstance(field_type, BinaryType) else schema_to_pyarrow(field_type) + return pa.nulls(len(arrow_table), type=arrow_type) + names.append(source_schema.find_field(current_id).name) # Get the column from the table (e.g., "bar" for "bar.baz") and navigate into its structs - column_name, *nested_names = reversed(names) + column_name, *nested_names = names field_array = arrow_table[column_name] return pc.struct_field(field_array, nested_names) if nested_names else field_array diff --git a/tests/catalog/test_catalog_behaviors.py b/tests/catalog/test_catalog_behaviors.py index 6eaf7f1bfb..d9b5ce6383 100644 --- a/tests/catalog/test_catalog_behaviors.py +++ b/tests/catalog/test_catalog_behaviors.py @@ -810,6 +810,39 @@ def test_partition_values_follow_writer_struct_path(catalog: Catalog) -> None: assert tbl.scan(row_filter=f"s.x = '{value}'").to_arrow().to_pylist() == written_rows +def test_append_without_optional_partition_source_columns(catalog: Catalog) -> None: + catalog.create_namespace("default") + table_schema = pa.schema( + [ + ("id", pa.int64()), + ("region", pa.string()), + ("shipping", pa.struct([("country", pa.string()), ("zip", pa.string())])), + ("billing", pa.struct([("country", pa.string())])), + ] + ) + # The input has no region and billing columns, and its shipping struct has no country field + input_schema = pa.schema([("id", pa.int64()), ("shipping", pa.struct([("zip", pa.string())]))]) + df = pa.Table.from_pylist([{"id": 1, "shipping": {"zip": "1011"}}, {"id": 2, "shipping": None}], schema=input_schema) + expected = [ + {"id": 1, "region": None, "shipping": {"country": None, "zip": "1011"}, "billing": None}, + {"id": 2, "region": None, "shipping": None, "billing": None}, + ] + sources = ["region", "shipping.country", "billing.country"] + transforms: list[IdentityTransform[str] | BucketTransform[str]] = [IdentityTransform(), BucketTransform(4)] + cases = [(source_name, transform) for source_name in sources for transform in transforms] + for i, (source_name, transform) in enumerate(cases): + tbl = catalog.create_table(f"default.missing_partition_source_{i}", schema=table_schema) + with tbl.update_spec() as update: + update.add_field(source_name, transform, "p") + + tbl.append(df) + + # The writer stores nulls for the missing columns, so the rows are in the null partition + assert sorted(tbl.scan().to_arrow().to_pylist(), key=lambda row: row["id"]) == expected, (source_name, transform) + assert [task.file.partition[0] for task in tbl.scan().plan_files()] == [None], (source_name, transform) + assert tbl.scan(row_filter=f"{source_name} IS NULL").to_arrow().num_rows == 2, (source_name, transform) + + def test_append_table(catalog: Catalog, table_schema_simple: Schema, test_table_identifier: Identifier) -> None: namespace = Catalog.namespace_from(test_table_identifier) catalog.create_namespace(namespace) diff --git a/tests/io/test_pyarrow.py b/tests/io/test_pyarrow.py index 18dad07f17..62f9e539c3 100644 --- a/tests/io/test_pyarrow.py +++ b/tests/io/test_pyarrow.py @@ -3462,6 +3462,19 @@ def test_partition_for_nested_field_with_dotted_names() -> None: } +def test_append_without_optional_binary_partition_source(catalog: InMemoryCatalog) -> None: + catalog.create_namespace("default") + tbl = catalog.create_table("default.missing_binary", schema=pa.schema([("id", pa.int64()), ("data", pa.binary())])) + with tbl.update_spec() as update: + update.add_field("data", TruncateTransform(3), "p") + + tbl.append(pa.table({"id": [1]})) + + assert tbl.scan().to_arrow().to_pylist() == [{"id": 1, "data": None}] + assert [task.file.partition[0] for task in tbl.scan().plan_files()] == [None] + assert tbl.scan(row_filter="data IS NULL").to_arrow().num_rows == 1 + + def test_partition_for_deep_nested_field() -> None: schema = Schema( NestedField( From 974052763d7a1c9715a7e75a223ea949edf156df Mon Sep 17 00:00:00 2001 From: rahulsmahadev Date: Tue, 1 Dec 2026 07:40:46 +0000 Subject: [PATCH 3/5] Simplify the partition source lookup and drop the binary special case Take the names on the source's struct path by ID from the input schema, and return nulls of the writer's type for a missing field (the truncate large_binary gap is apache/iceberg-rust#3119). ArrowAccessor is not called directly: StructArray.field() ignores struct nulls, and its pa.Table branch combines chunks, which overflows for string sources over 2 GiB. Trim duplicate tests. Co-authored-by: Isaac --- pyiceberg/io/pyarrow.py | 34 ++++++--------------- tests/catalog/test_catalog_behaviors.py | 24 +++------------ tests/io/test_pyarrow.py | 39 ------------------------- 3 files changed, 13 insertions(+), 84 deletions(-) diff --git a/pyiceberg/io/pyarrow.py b/pyiceberg/io/pyarrow.py index b9439ebfd4..7608daaf80 100644 --- a/pyiceberg/io/pyarrow.py +++ b/pyiceberg/io/pyarrow.py @@ -3598,41 +3598,25 @@ def _partition_value_filter(partition_field_name: str, value: Any) -> pc.Express def _get_field_from_arrow_table( arrow_table: pa.Table, schema: Schema, field_id: int, input_schema: Schema | None = None ) -> pa.Array: - """Get a field from an Arrow table by its field ID, where the field can be nested in structs. + """Get a field, which can be nested in structs, from an Arrow table the way the writer does. - Follow the target schema's parent IDs and resolve each name in input_schema, matching the writer. - A name can contain dots (e.g., "some.id"), so a nested field's full name cannot be split into these names. - When an optional field on the path is missing from input_schema, return the nulls that the writer stores. + Like ArrowAccessor in the writer, follow the field's struct path in schema and take each field on it by the name + that its ID has in input_schema, which can differ from schema and contain dots. Args: arrow_table: The Arrow table containing the field - schema: The target Iceberg table schema + schema: The Iceberg table schema field_id: The ID of the field input_schema: The Iceberg schema of the Arrow table, if different from schema Returns: - The field as a PyArrow Array - - Raises: - ValueError: If a field ID on the path is missing from schema, or a required one from input_schema - KeyError: If the field path cannot be resolved + The field as a PyArrow Array, or the nulls that the writer stores when a field on its path is missing """ source_schema = input_schema if input_schema is not None else schema - # Match ArrowAccessor: follow the target's parent IDs using each field's input name. field_ids = [field_id] while (parent_id := schema._lazy_id_to_parent.get(field_ids[-1])) is not None: field_ids.append(parent_id) - names: list[str] = [] - for current_id in reversed(field_ids): - if current_id not in source_schema._lazy_id_to_field and schema.find_field(current_id).optional: - # The writer stores nulls for a missing optional field and the fields nested in it - field_type = schema.find_field(field_id).field_type - # The truncate kernel has no large_binary support: https://github.com/apache/iceberg-rust/issues/3119 - arrow_type = pa.binary() if isinstance(field_type, BinaryType) else schema_to_pyarrow(field_type) - return pa.nulls(len(arrow_table), type=arrow_type) - names.append(source_schema.find_field(current_id).name) - - # Get the column from the table (e.g., "bar" for "bar.baz") and navigate into its structs - column_name, *nested_names = names - field_array = arrow_table[column_name] - return pc.struct_field(field_array, nested_names) if nested_names else field_array + if any(current_id not in source_schema._lazy_id_to_field for current_id in field_ids): + return pa.nulls(len(arrow_table), type=schema_to_pyarrow(schema.find_type(field_id))) + column_name, *nested_names = [source_schema.find_field(current_id).name for current_id in reversed(field_ids)] + return pc.struct_field(arrow_table[column_name], nested_names) if nested_names else arrow_table[column_name] diff --git a/tests/catalog/test_catalog_behaviors.py b/tests/catalog/test_catalog_behaviors.py index f8ee83ee92..bd1c4830e8 100644 --- a/tests/catalog/test_catalog_behaviors.py +++ b/tests/catalog/test_catalog_behaviors.py @@ -784,15 +784,17 @@ def test_remove_properties_already_removed_by_concurrent_commit( def test_append_to_identity_partitioned_table_with_dotted_names(catalog: Catalog) -> None: catalog.create_namespace("default") # The names from the top-level column down to the partition source, where a name can contain dots - paths = [("a.b",), ("bar", "baz"), ("foo", "bar", "baz"), ("a.b", "c"), ("a", "b.c"), ("root", "a.b", "c")] + paths = [("a.b", "c"), ("a", "b.c"), ("root", "a.b", "c")] for i, path in enumerate(paths): column_type: pa.DataType = pa.string() values: list[Any] = ["x", "y", None] for name in reversed(path[1:]): column_type = pa.struct([(name, column_type)]) values = [{name: value} for value in values] + # The fields of a null struct are stored as nulls, so the last row is in the null partition too + values.append(None) arrow_schema = pa.schema([("id", pa.int64()), (path[0], column_type)]) - df = pa.Table.from_pydict({"id": [1, 2, 3], path[0]: values}, schema=arrow_schema) + df = pa.Table.from_pydict({"id": [1, 2, 3, 4], path[0]: values}, schema=arrow_schema) tbl = catalog.create_table(f"default.dotted_partition_source_{i}", schema=df.schema) with tbl.update_spec() as update: update.add_field(".".join(path), IdentityTransform(), "p") @@ -829,24 +831,6 @@ def test_append_with_field_ids_after_swapping_column_names(catalog: Catalog) -> assert tbl.scan(row_filter=f"{renamed_source_name} = 'x'").to_arrow().to_pylist() == [swapped_row], source_name -def test_partition_values_follow_writer_struct_path(catalog: Catalog) -> None: - catalog.create_namespace("default") - struct_type = pa.struct([("x", pa.string())]) - tbl = catalog.create_table("default.partition_input_parents", schema=pa.schema([("s", struct_type), ("t", struct_type)])) - with tbl.update_spec() as spec_update: - spec_update.add_field("s.x", IdentityTransform(), "p") - # Swap the struct types, so that each leaf field ID of the input is under the other parent - s_field, t_field = tbl.schema().as_arrow() - input_schema = pa.schema([s_field.with_type(t_field.type), t_field.with_type(s_field.type)]) - tbl.append(pa.Table.from_pylist([{"s": {"x": "X"}, "t": {"x": "Y"}}], schema=input_schema)) - - # The partition value and the filtered scan agree with the row that was written - written_rows = tbl.scan().to_arrow().to_pylist() - value = written_rows[0]["s"]["x"] - assert [task.file.partition[0] for task in tbl.scan().plan_files()] == [value] - assert tbl.scan(row_filter=f"s.x = '{value}'").to_arrow().to_pylist() == written_rows - - def test_append_without_optional_partition_source_columns(catalog: Catalog) -> None: catalog.create_namespace("default") table_schema = pa.schema( diff --git a/tests/io/test_pyarrow.py b/tests/io/test_pyarrow.py index 6f7026b543..1605dd3b67 100644 --- a/tests/io/test_pyarrow.py +++ b/tests/io/test_pyarrow.py @@ -3667,45 +3667,6 @@ def test_partition_for_nested_field() -> None: assert partition_values == {486729, 486730} -def test_partition_for_nested_field_with_dotted_names() -> None: - # The full names a.b.c, d.e.f and g.h.i.j cannot be split on dots into the names of the nested fields - schema = Schema( - NestedField(1, "a.b", StructType(NestedField(2, "c", StringType()))), - NestedField(3, "d", StructType(NestedField(4, "e.f", StringType()))), - NestedField(5, "g", StructType(NestedField(6, "h.i", StructType(NestedField(7, "j", StringType()))))), - ) - spec = PartitionSpec( - PartitionField(source_id=2, field_id=1000, transform=IdentityTransform(), name="c"), - PartitionField(source_id=4, field_id=1001, transform=IdentityTransform(), name="e_f"), - PartitionField(source_id=7, field_id=1002, transform=IdentityTransform(), name="j"), - ) - rows = [ - {"a.b": {"c": "x"}, "d": {"e.f": "y"}, "g": {"h.i": {"j": "z"}}}, - {"a.b": {"c": "x"}, "d": {"e.f": None}, "g": None}, - ] - arrow_table = pa.Table.from_pylist(rows, schema=schema.as_arrow()) - - partitions = list(_determine_partitions(spec, schema, arrow_table)) - - assert {p.partition_key.partition: p.arrow_table_partition.to_pylist() for p in partitions} == { - Record("x", "y", "z"): [rows[0]], - Record("x", None, None): [rows[1]], - } - - -def test_append_without_optional_binary_partition_source(catalog: InMemoryCatalog) -> None: - catalog.create_namespace("default") - tbl = catalog.create_table("default.missing_binary", schema=pa.schema([("id", pa.int64()), ("data", pa.binary())])) - with tbl.update_spec() as update: - update.add_field("data", TruncateTransform(3), "p") - - tbl.append(pa.table({"id": [1]})) - - assert tbl.scan().to_arrow().to_pylist() == [{"id": 1, "data": None}] - assert [task.file.partition[0] for task in tbl.scan().plan_files()] == [None] - assert tbl.scan(row_filter="data IS NULL").to_arrow().num_rows == 1 - - def test_partition_for_deep_nested_field() -> None: schema = Schema( NestedField( From ea1cc8e702214cc3bf32b3fc76e65c39aef53579 Mon Sep 17 00:00:00 2001 From: rahulsmahadev Date: Tue, 1 Dec 2026 22:51:25 +0000 Subject: [PATCH 4/5] Compute partition values from the writer's projection Partition values must come from the values write_file stores. Instead of re-deriving its field resolution by hand, project the partition sources per batch with _to_requested_schema, as write_file does (field IDs of the input schema, nulls for missing optional fields, the same casts), and read each source by position with Schema.accessor_for_field. This also fixes ns timestamps and times with the downcast option (#4479) and s/ms timestamp and narrow-int inputs (#4421); the three tests of #4479 move here. Co-authored-by: Isaac --- pyiceberg/io/pyarrow.py | 62 +++++++++++++++++++++----------------- tests/io/test_pyarrow.py | 65 +++++++++++++++++++++++++++++++++++++++- 2 files changed, 98 insertions(+), 29 deletions(-) diff --git a/pyiceberg/io/pyarrow.py b/pyiceberg/io/pyarrow.py index 7608daaf80..cfcf5722e5 100644 --- a/pyiceberg/io/pyarrow.py +++ b/pyiceberg/io/pyarrow.py @@ -141,6 +141,7 @@ ) from pyiceberg.partitioning import PartitionFieldValue, PartitionKey, PartitionSpec from pyiceberg.schema import ( + Accessor, PartnerAccessor, PreOrderSchemaVisitor, Schema, @@ -3494,7 +3495,11 @@ def _dataframe_to_data_files( ) else: partitions = _determine_partitions( - spec=table_metadata.spec(), schema=table_metadata.schema(), arrow_table=df, input_schema=task_schema + spec=table_metadata.spec(), + schema=table_metadata.schema(), + arrow_table=df, + input_schema=task_schema, + downcast_ns_timestamp_to_us=downcast_ns_timestamp_to_us, ) yield from write_file( io=io, @@ -3520,12 +3525,16 @@ class _TablePartition: def _determine_partitions( - spec: PartitionSpec, schema: Schema, arrow_table: pa.Table, input_schema: Schema | None = None + spec: PartitionSpec, + schema: Schema, + arrow_table: pa.Table, + input_schema: Schema | None = None, + downcast_ns_timestamp_to_us: bool = False, ) -> Iterable[_TablePartition]: """Based on the iceberg table partition spec, filter the arrow table into partitions with their keys. - The source columns are found by field ID in input_schema, the Iceberg schema of the arrow table (schema if not - given), whose names can differ from schema, e.g. when the arrow table has field IDs from before a rename. + The source columns are projected the way write_file does, by field ID in input_schema (the Iceberg schema of the + arrow table, schema if not given), so the partition values are computed from the values that are written. Example: Input: @@ -3547,9 +3556,19 @@ def _determine_partitions( name = f"_{name}" partition_fields.append(name) + source_schema = prune_columns(schema, {field.source_id for field in spec.fields}, select_full_types=False) + input_schema = input_schema if input_schema is not None else schema + source_batches = [ + _to_requested_schema(source_schema, input_schema, batch, downcast_ns_timestamp_to_us) + for batch in arrow_table.to_batches() + ] + if not source_batches: + return + sources = pa.Table.from_batches(source_batches) + for partition, name in zip(spec.fields, partition_fields, strict=True): source_field = schema.find_field(partition.source_id) - field_array = _get_field_from_arrow_table(arrow_table, schema, partition.source_id, input_schema) + field_array = _get_field_from_arrow_table(sources, source_schema, partition.source_id) partition_array = partition.transform.pyarrow_transform(source_field.field_type)(field_array) # PyArrow has no group by or equality kernels for extension types such as arrow.uuid, so use their storage type if isinstance(partition_array.type, pa.BaseExtensionType): @@ -3595,28 +3614,15 @@ def _partition_value_filter(partition_field_name: str, value: Any) -> pc.Express return pc.field(partition_field_name) == value -def _get_field_from_arrow_table( - arrow_table: pa.Table, schema: Schema, field_id: int, input_schema: Schema | None = None -) -> pa.Array: - """Get a field, which can be nested in structs, from an Arrow table the way the writer does. +def _get_field_from_arrow_table(arrow_table: pa.Table, schema: Schema, field_id: int) -> pa.Array: + """Get a field, which can be nested in structs, from an Arrow table that has the layout of schema. - Like ArrowAccessor in the writer, follow the field's struct path in schema and take each field on it by the name - that its ID has in input_schema, which can differ from schema and contain dots. - - Args: - arrow_table: The Arrow table containing the field - schema: The Iceberg table schema - field_id: The ID of the field - input_schema: The Iceberg schema of the Arrow table, if different from schema - - Returns: - The field as a PyArrow Array, or the nulls that the writer stores when a field on its path is missing + The field is found by position, like Java's Accessors, so the names on its path can contain dots. """ - source_schema = input_schema if input_schema is not None else schema - field_ids = [field_id] - while (parent_id := schema._lazy_id_to_parent.get(field_ids[-1])) is not None: - field_ids.append(parent_id) - if any(current_id not in source_schema._lazy_id_to_field for current_id in field_ids): - return pa.nulls(len(arrow_table), type=schema_to_pyarrow(schema.find_type(field_id))) - column_name, *nested_names = [source_schema.find_field(current_id).name for current_id in reversed(field_ids)] - return pc.struct_field(arrow_table[column_name], nested_names) if nested_names else arrow_table[column_name] + positions: list[int] = [] + accessor: Accessor | None = schema.accessor_for_field(field_id) + while accessor is not None: + positions.append(accessor.position) + accessor = accessor.inner + column, *nested = positions + return pc.struct_field(arrow_table.column(column), nested) if nested else arrow_table.column(column) diff --git a/tests/io/test_pyarrow.py b/tests/io/test_pyarrow.py index 1605dd3b67..759fa9e8f4 100644 --- a/tests/io/test_pyarrow.py +++ b/tests/io/test_pyarrow.py @@ -131,7 +131,15 @@ from pyiceberg.table.metadata_columns import LAST_UPDATED_SEQUENCE_NUMBER, ROW_ID from pyiceberg.table.name_mapping import create_mapping_from_schema from pyiceberg.table.puffin import MAGIC_BYTES, PuffinFile -from pyiceberg.transforms import BucketTransform, HourTransform, IdentityTransform, Transform, TruncateTransform, YearTransform +from pyiceberg.transforms import ( + BucketTransform, + DayTransform, + HourTransform, + IdentityTransform, + Transform, + TruncateTransform, + YearTransform, +) from pyiceberg.typedef import UTF8, Properties, Record, TableVersion from pyiceberg.types import ( BinaryType, @@ -4492,6 +4500,61 @@ def test__to_requested_schema_timestamps_without_downcast_raises_exception( assert "Unsupported schema projection from timestamp[ns] to timestamp[us]" in str(exc_info.value) +def test_append_partitioned_ns_timestamp_downcast(monkeypatch: pytest.MonkeyPatch, catalog: InMemoryCatalog) -> None: + monkeypatch.setenv("PYICEBERG_DOWNCAST_NS_TIMESTAMP_TO_US_ON_WRITE", "True") + catalog.create_namespace("default") + # Stored as [1, 1, 0, 3600000000, null] us: 1000 and 1500 ns share 1 us, and -1 ns becomes 0 us + values = [1000, 1500, -1, 3600000000000, None] + cases: list[tuple[Transform[Any, Any], PrimitiveType, str | None, dict[Any, int]]] = [ + (IdentityTransform(), TimestampType(), None, {1: 2, 0: 1, 3600000000: 1, None: 1}), + (HourTransform(), TimestampType(), None, {0: 3, 1: 1, None: 1}), + (DayTransform(), TimestamptzType(), "UTC", {0: 4, None: 1}), + ] + for transform, ts_type, tz, expected in cases: + table = catalog.create_table( + f"default.ns_downcast_{transform}", + schema=Schema(NestedField(1, "id", LongType(), required=False), NestedField(2, "ts", ts_type, required=False)), + partition_spec=PartitionSpec(PartitionField(2, 1000, transform, name="ts_part")), + ) + table.append(pa.table({"id": pa.array(range(5), pa.int64()), "ts": pa.array(values, pa.timestamp("ns", tz=tz))})) + + rows = table.scan().to_arrow().sort_by("id") + assert rows.column("id").to_pylist() == [0, 1, 2, 3, 4], transform + assert rows.column("ts").cast(pa.int64()).to_pylist() == [1, 1, 0, 3600000000, None], transform + assert {task.file.partition[0]: task.file.record_count for task in table.scan().plan_files()} == expected, transform + + +def test_append_partitioned_ns_time_downcast(monkeypatch: pytest.MonkeyPatch, catalog: InMemoryCatalog) -> None: + monkeypatch.setenv("PYICEBERG_DOWNCAST_NS_TIMESTAMP_TO_US_ON_WRITE", "True") + catalog.create_namespace("default") + table = catalog.create_table( + "default.ns_time_downcast", + schema=Schema(NestedField(1, "id", LongType(), required=False), NestedField(2, "t", TimeType(), required=False)), + partition_spec=PartitionSpec(PartitionField(2, 1000, IdentityTransform(), name="t_part")), + ) + # Stored as [1, 1, 3600000001, null] us: 1000 and 1500 ns share 1 us, and 3600000001500 ns is alone in its us + values = [1000, 1500, 3600000001500, None] + table.append(pa.table({"id": pa.array(range(4), pa.int64()), "t": pa.array(values, pa.time64("ns"))})) + + rows = table.scan().to_arrow().sort_by("id") + assert rows.column("id").to_pylist() == [0, 1, 2, 3] + assert rows.column("t").cast(pa.int64()).to_pylist() == [1, 1, 3600000001, None] + partitions = {task.file.partition[0]: task.file.record_count for task in table.scan().plan_files()} + assert partitions == {1: 2, 3600000001: 1, None: 1} + + +def test_determine_partitions_native_ns_timestamp_is_not_downcast() -> None: + # v3 nanosecond sources keep their precision, so day(-1 ns) stays -1 even with the downcast flag on + for source_type, tz in [(TimestampNanoType(), None), (TimestamptzNanoType(), "UTC")]: + schema = Schema(NestedField(1, "id", LongType(), required=False), NestedField(2, "ts", source_type, required=False)) + spec = PartitionSpec(PartitionField(2, 1000, DayTransform(), name="ts_day")) + arrow_table = pa.table({"id": pa.array([0, 1], pa.int64()), "ts": pa.array([-1, None], pa.timestamp("ns", tz=tz))}) + result = _determine_partitions(spec, schema, arrow_table, downcast_ns_timestamp_to_us=True) + assert { + p.partition_key.partition[0]: p.arrow_table_partition.column("ts").cast(pa.int64()).to_pylist() for p in result + } == {-1: [-1], None: [None]}, source_type + + def test__to_requested_schema_time_ns_downcast() -> None: """Test that a time64[ns] column is downcast to time64[us] on write when the flag is set.""" requested_schema = Schema(NestedField(1, "time_field", TimeType(), required=False)) From 9c491e28e9ae52886c48e02c1f99c5070cd4a39f Mon Sep 17 00:00:00 2001 From: rahulsmahadev Date: Wed, 2 Dec 2026 01:23:52 +0000 Subject: [PATCH 5/5] Test an identity partition on a float16 input The writer widens float16 to the column's float type, and the partition values now come from that projection, so the append no longer raises ArrowNotImplementedError. Co-authored-by: Isaac --- tests/io/test_pyarrow.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/tests/io/test_pyarrow.py b/tests/io/test_pyarrow.py index 759fa9e8f4..b585ab943e 100644 --- a/tests/io/test_pyarrow.py +++ b/tests/io/test_pyarrow.py @@ -4543,6 +4543,19 @@ def test_append_partitioned_ns_time_downcast(monkeypatch: pytest.MonkeyPatch, ca assert partitions == {1: 2, 3600000001: 1, None: 1} +def test_append_partitioned_float16_is_widened(catalog: InMemoryCatalog) -> None: + catalog.create_namespace("default") + table = catalog.create_table( + "default.float16_partition", + schema=Schema(NestedField(1, "id", LongType(), required=False), NestedField(2, "v", FloatType(), required=False)), + partition_spec=PartitionSpec(PartitionField(2, 1000, IdentityTransform(), name="v_part")), + ) + table.append(pa.table({"id": pa.array([0, 1, 2], pa.int64()), "v": pa.array([1.5, 0.25, 1.5], pa.float16())})) + + assert table.scan().to_arrow().sort_by("id").column("v").to_pylist() == [1.5, 0.25, 1.5] + assert {task.file.partition[0]: task.file.record_count for task in table.scan().plan_files()} == {1.5: 2, 0.25: 1} + + def test_determine_partitions_native_ns_timestamp_is_not_downcast() -> None: # v3 nanosecond sources keep their precision, so day(-1 ns) stays -1 even with the downcast flag on for source_type, tz in [(TimestampNanoType(), None), (TimestamptzNanoType(), "UTC")]: