From 28fbbaba4195d7043baf88cd7d759d55b7693448 Mon Sep 17 00:00:00 2001 From: rahulsmahadev Date: Tue, 1 Dec 2026 17:59:39 +0000 Subject: [PATCH 1/5] Map add_files columns without field IDs by the table's name mapping add_files matched columns without field IDs against a mapping built from the table's current names, so a file that still used a renamed column's old name was rejected, although the table's name mapping keeps that name and the scan reads the file through it. add_files now uses the table's name mapping; writes keep matching the current names. Co-authored-by: Isaac --- pyiceberg/io/pyarrow.py | 10 +++++-- tests/io/test_pyarrow.py | 63 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+), 2 deletions(-) diff --git a/pyiceberg/io/pyarrow.py b/pyiceberg/io/pyarrow.py index 397160ab81..0a2a06f143 100644 --- a/pyiceberg/io/pyarrow.py +++ b/pyiceberg/io/pyarrow.py @@ -3284,11 +3284,13 @@ def _check_pyarrow_schema_compatible( provided_schema: pa.Schema, downcast_ns_timestamp_to_us: bool = False, format_version: TableVersion = TableProperties.DEFAULT_FORMAT_VERSION, + name_mapping: NameMapping | None = None, ) -> Schema: """ Check if the `requested_schema` is compatible with `provided_schema`. Two schemas are considered compatible when they are equal in terms of the Iceberg Schema type. + Columns without field IDs get them from `name_mapping`, which defaults to the names of `requested_schema`. Returns: The Iceberg schema of `provided_schema`, with the field IDs of its columns. @@ -3296,7 +3298,8 @@ def _check_pyarrow_schema_compatible( Raises: ValueError: If the schemas are not compatible. """ - name_mapping = requested_schema.name_mapping + if name_mapping is None: + name_mapping = requested_schema.name_mapping try: provided_schema = pyarrow_to_schema( @@ -3332,7 +3335,10 @@ def parquet_file_to_data_file(io: FileIO, table_metadata: TableMetadata, file_pa arrow_schema = parquet_metadata.schema.to_arrow_schema() schema = table_metadata.schema() - file_schema = _check_pyarrow_schema_compatible(schema, arrow_schema, format_version=table_metadata.format_version) + # Like the scan, use the table's name mapping, which keeps the old names of renamed columns. + file_schema = _check_pyarrow_schema_compatible( + schema, arrow_schema, format_version=table_metadata.format_version, name_mapping=table_metadata.name_mapping() + ) stats_columns = compute_statistics_plan(schema, table_metadata.properties) parquet_column_mapping = _file_parquet_path_to_id_mapping(parquet_metadata, file_schema) diff --git a/tests/io/test_pyarrow.py b/tests/io/test_pyarrow.py index 1605dd3b67..77fde5d9c3 100644 --- a/tests/io/test_pyarrow.py +++ b/tests/io/test_pyarrow.py @@ -3462,6 +3462,27 @@ def test_schema_downcast(table_schema_simple: Schema) -> None: pytest.fail("Unexpected Exception raised when calling `_check_pyarrow_schema_compatible`") +def test_schema_compatible_with_name_mapping(table_schema_simple: Schema) -> None: + # The table renamed "foo" (field ID 1) to "qux", and the columns have no field IDs. + renamed_schema = Schema(NestedField(1, "qux", StringType(), required=False), *table_schema_simple.fields[1:]) + other_schema = pa.schema( + ( + pa.field("foo", pa.string(), nullable=True), + pa.field("bar", pa.int32(), nullable=False), + pa.field("baz", pa.bool_(), nullable=True), + ) + ) + + file_schema = _check_pyarrow_schema_compatible( + renamed_schema, other_schema, name_mapping=create_mapping_from_schema(table_schema_simple) + ) + assert file_schema.find_field("foo").field_id == 1 + + # Without a name mapping, the columns are matched by the names of the requested schema. + with pytest.raises(ValueError, match="PyArrow table contains more columns: foo"): + _check_pyarrow_schema_compatible(renamed_schema, other_schema) + + def test_add_files_matches_columns_by_field_id(catalog: InMemoryCatalog, tmp_path: str) -> None: # Each file is valid for its table, but its column paths differ from the table's names. nested_schema = Schema( @@ -3547,6 +3568,48 @@ def test_add_files_matches_columns_by_field_id(catalog: InMemoryCatalog, tmp_pat assert dict(table.inspect.files().to_pylist()[0]["value_counts"]) == value_counts +def test_add_files_matches_columns_by_table_name_mapping(catalog: InMemoryCatalog, tmp_path: str) -> None: + # The files have no field IDs. The first add_files stores the table's name mapping, and the renames + # keep the old names in it, so a file that still uses them is matched the way the scan reads it. + catalog.create_namespace("default") + identifier = "default.add_files_table_name_mapping" + catalog.create_table( + identifier, + schema=Schema( + NestedField(1, "id", LongType(), required=False), + NestedField(2, "name", StringType(), required=False), + NestedField(3, "address", StructType(NestedField(4, "zip", LongType(), required=False)), required=False), + ), + ) + file_schema = pa.schema( + [pa.field("id", pa.int64()), pa.field("name", pa.string()), pa.field("address", pa.struct([pa.field("zip", pa.int64())]))] + ) + file_locs = [] + for row_id, name, zip_code in [(1, "a", 98101), (2, "b", 10001), (3, "c", 94105)]: + file_loc = f"{tmp_path}/{row_id}.parquet" + pq.write_table(pa.table({"id": [row_id], "name": [name], "address": [{"zip": zip_code}]}, schema=file_schema), file_loc) + file_locs.append(file_loc) + + catalog.load_table(identifier).add_files(file_locs[:1]) + with catalog.load_table(identifier).update_schema() as update: + update.rename_column("name", "full_name") + update.rename_column("address.zip", "postal_code") + catalog.load_table(identifier).add_files(file_locs[1:2]) + + table = catalog.load_table(identifier) + assert sorted(table.scan().to_arrow().to_pylist(), key=lambda row: row["id"]) == [ + {"id": 1, "full_name": "a", "address": {"postal_code": 98101}}, + {"id": 2, "full_name": "b", "address": {"postal_code": 10001}}, + ] + assert [dict(file["value_counts"]) for file in table.inspect.files().to_pylist()] == [{1: 1, 2: 1, 4: 1}] * 2 + + # The mapping keeps the names of a dropped column too, but they no longer match a column of the table. + with table.update_schema() as update: + update.delete_column("full_name") + with pytest.raises(ValueError, match="PyArrow table contains more columns: name"): + catalog.load_table(identifier).add_files(file_locs[2:]) + + def test_add_files_with_field_ids_swapped_relative_to_names(catalog: InMemoryCatalog, tmp_path: str) -> None: # The file's "a" is field ID 2 and its "b" is field ID 1, the reverse of the table, as after renames. # Its bounds have to be recorded by field ID, or both filters below prune the file. From 554afee63821cda08e9cad22c811c566bfcad067 Mon Sep 17 00:00:00 2001 From: rahulsmahadev Date: Tue, 1 Dec 2026 19:57:41 +0000 Subject: [PATCH 2/5] Reject add_files columns that resolve to the same field ID With the table's name mapping, a file with both the old and the new name of a renamed column resolved both to one field ID: the scan read one of them and the value counts added up. add_files now rejects such files, and files with a field ID twice, as Java's import does, and documents its ValueError. Co-authored-by: Isaac --- pyiceberg/io/pyarrow.py | 11 ++++++++++- pyiceberg/table/__init__.py | 3 +++ tests/io/test_pyarrow.py | 21 +++++++++++++++++++++ 3 files changed, 34 insertions(+), 1 deletion(-) diff --git a/pyiceberg/io/pyarrow.py b/pyiceberg/io/pyarrow.py index 0a2a06f143..5a08880483 100644 --- a/pyiceberg/io/pyarrow.py +++ b/pyiceberg/io/pyarrow.py @@ -147,6 +147,7 @@ SchemaVisitorPerPrimitiveType, SchemaWithPartnerVisitor, _check_schema_compatible, + _IndexByName, build_position_accessors, pre_order_visit, promote, @@ -3290,7 +3291,8 @@ def _check_pyarrow_schema_compatible( Check if the `requested_schema` is compatible with `provided_schema`. Two schemas are considered compatible when they are equal in terms of the Iceberg Schema type. - Columns without field IDs get them from `name_mapping`, which defaults to the names of `requested_schema`. + If `provided_schema` lacks field IDs, its columns get them from `name_mapping`, which defaults to the names of + `requested_schema`. Returns: The Iceberg schema of `provided_schema`, with the field IDs of its columns. @@ -3339,6 +3341,13 @@ def parquet_file_to_data_file(io: FileIO, table_metadata: TableMetadata, file_pa file_schema = _check_pyarrow_schema_compatible( schema, arrow_schema, format_version=table_metadata.format_version, name_mapping=table_metadata.name_mapping() ) + # Two columns can resolve to one field ID, for example the old and the new name of a renamed column. + names_by_id: dict[int, list[str]] = {} + for name, field_id in visit(file_schema, _IndexByName()).items(): + names_by_id.setdefault(field_id, []).append(name) + for field_id, names in sorted(names_by_id.items()): + if len(names) > 1: + raise ValueError(f"Multiple file columns resolve to field ID {field_id}: {', '.join(sorted(names))}") stats_columns = compute_statistics_plan(schema, table_metadata.properties) parquet_column_mapping = _file_parquet_path_to_id_mapping(parquet_metadata, file_schema) diff --git a/pyiceberg/table/__init__.py b/pyiceberg/table/__init__.py index 28a76fc3bb..aff339a5ea 100644 --- a/pyiceberg/table/__init__.py +++ b/pyiceberg/table/__init__.py @@ -1097,6 +1097,8 @@ def add_files( FileNotFoundError: If the file does not exist. ValueError: Raises a ValueError given file_paths contains duplicate files ValueError: Raises a ValueError given file_paths already referenced by table + ValueError: Raises a ValueError given a file whose columns cannot be resolved unambiguously or are incompatible + with the table schema ValidationException: Raises a ValidationException if a file becomes referenced during a commit retry """ if len(file_paths) != len(set(file_paths)): @@ -1972,6 +1974,7 @@ def add_files( Raises: FileNotFoundError: If the file does not exist. + ValueError: If the columns of a file cannot be resolved unambiguously or are incompatible with the table schema. """ with self.transaction() as tx: tx.add_files( diff --git a/tests/io/test_pyarrow.py b/tests/io/test_pyarrow.py index 77fde5d9c3..498eb4bc38 100644 --- a/tests/io/test_pyarrow.py +++ b/tests/io/test_pyarrow.py @@ -3479,6 +3479,8 @@ def test_schema_compatible_with_name_mapping(table_schema_simple: Schema) -> Non assert file_schema.find_field("foo").field_id == 1 # Without a name mapping, the columns are matched by the names of the requested schema. + file_schema = _check_pyarrow_schema_compatible(renamed_schema, other_schema.set(0, pa.field("qux", pa.string()))) + assert file_schema.find_field("qux").field_id == 1 with pytest.raises(ValueError, match="PyArrow table contains more columns: foo"): _check_pyarrow_schema_compatible(renamed_schema, other_schema) @@ -3603,6 +3605,25 @@ def test_add_files_matches_columns_by_table_name_mapping(catalog: InMemoryCatalo ] assert [dict(file["value_counts"]) for file in table.inspect.files().to_pylist()] == [{1: 1, 2: 1, 4: 1}] * 2 + # Both the old and the new name of a column in one file, in either order, resolve to one field ID, like a field ID + # that a file has twice. Such files are rejected. + old_name, new_name = pa.field("name", pa.string()), pa.field("full_name", pa.string()) + both_zips = pa.field("address", pa.struct([pa.field("zip", pa.int64()), pa.field("postal_code", pa.int64())])) + id_2 = {"PARQUET:field_id": "2"} + for i, (columns, error) in enumerate( + [ + ([old_name, new_name], "2: full_name, name"), + ([new_name, old_name], "2: full_name, name"), + ([both_zips], "4: address.postal_code, address.zip"), + ([old_name.with_metadata(id_2), new_name.with_metadata(id_2)], "2: full_name, name"), + ] + ): + file_loc = f"{tmp_path}/duplicate_{i}.parquet" + pq.write_table(pa.Table.from_pylist([{}], schema=pa.schema(columns)), file_loc) + with pytest.raises(ValueError, match=f"Multiple file columns resolve to field ID {error}"): + catalog.load_table(identifier).add_files([file_loc]) + assert catalog.load_table(identifier).current_snapshot() == table.current_snapshot() + # The mapping keeps the names of a dropped column too, but they no longer match a column of the table. with table.update_schema() as update: update.delete_column("full_name") From a6a91c105971356dfae0a6376b69b9af5951b751 Mon Sep 17 00:00:00 2001 From: rahulsmahadev Date: Tue, 1 Dec 2026 20:53:08 +0000 Subject: [PATCH 3/5] Test add_files with a list of structs and an incomplete name mapping The duplicate check must not take the short names of a list of structs for a second column, and a file with a current column that the stored name mapping lacks must be rejected without changing the table. Co-authored-by: Isaac --- tests/io/test_pyarrow.py | 34 +++++++++++++++++++++++----------- 1 file changed, 23 insertions(+), 11 deletions(-) diff --git a/tests/io/test_pyarrow.py b/tests/io/test_pyarrow.py index 498eb4bc38..a680bd2a17 100644 --- a/tests/io/test_pyarrow.py +++ b/tests/io/test_pyarrow.py @@ -3573,6 +3573,7 @@ def test_add_files_matches_columns_by_field_id(catalog: InMemoryCatalog, tmp_pat def test_add_files_matches_columns_by_table_name_mapping(catalog: InMemoryCatalog, tmp_path: str) -> None: # The files have no field IDs. The first add_files stores the table's name mapping, and the renames # keep the old names in it, so a file that still uses them is matched the way the scan reads it. + # The short names of the list of structs, like address.zip, must not count as a second column. catalog.create_namespace("default") identifier = "default.add_files_table_name_mapping" catalog.create_table( @@ -3580,41 +3581,39 @@ def test_add_files_matches_columns_by_table_name_mapping(catalog: InMemoryCatalo schema=Schema( NestedField(1, "id", LongType(), required=False), NestedField(2, "name", StringType(), required=False), - NestedField(3, "address", StructType(NestedField(4, "zip", LongType(), required=False)), required=False), + NestedField(3, "address", ListType(4, StructType(NestedField(5, "zip", LongType())), element_required=False)), ), ) - file_schema = pa.schema( - [pa.field("id", pa.int64()), pa.field("name", pa.string()), pa.field("address", pa.struct([pa.field("zip", pa.int64())]))] - ) + file_schema = pa.schema([("id", pa.int64()), ("name", pa.string()), ("address", pa.list_(pa.struct([("zip", pa.int64())])))]) file_locs = [] for row_id, name, zip_code in [(1, "a", 98101), (2, "b", 10001), (3, "c", 94105)]: file_loc = f"{tmp_path}/{row_id}.parquet" - pq.write_table(pa.table({"id": [row_id], "name": [name], "address": [{"zip": zip_code}]}, schema=file_schema), file_loc) + pq.write_table(pa.table({"id": [row_id], "name": [name], "address": [[{"zip": zip_code}]]}, schema=file_schema), file_loc) file_locs.append(file_loc) catalog.load_table(identifier).add_files(file_locs[:1]) with catalog.load_table(identifier).update_schema() as update: update.rename_column("name", "full_name") - update.rename_column("address.zip", "postal_code") + update.rename_column("address.element.zip", "postal_code") catalog.load_table(identifier).add_files(file_locs[1:2]) table = catalog.load_table(identifier) assert sorted(table.scan().to_arrow().to_pylist(), key=lambda row: row["id"]) == [ - {"id": 1, "full_name": "a", "address": {"postal_code": 98101}}, - {"id": 2, "full_name": "b", "address": {"postal_code": 10001}}, + {"id": 1, "full_name": "a", "address": [{"postal_code": 98101}]}, + {"id": 2, "full_name": "b", "address": [{"postal_code": 10001}]}, ] - assert [dict(file["value_counts"]) for file in table.inspect.files().to_pylist()] == [{1: 1, 2: 1, 4: 1}] * 2 + assert [dict(file["value_counts"]) for file in table.inspect.files().to_pylist()] == [{1: 1, 2: 1, 5: 1}] * 2 # Both the old and the new name of a column in one file, in either order, resolve to one field ID, like a field ID # that a file has twice. Such files are rejected. old_name, new_name = pa.field("name", pa.string()), pa.field("full_name", pa.string()) - both_zips = pa.field("address", pa.struct([pa.field("zip", pa.int64()), pa.field("postal_code", pa.int64())])) + both_zips = pa.field("address", pa.list_(pa.struct([("zip", pa.int64()), ("postal_code", pa.int64())]))) id_2 = {"PARQUET:field_id": "2"} for i, (columns, error) in enumerate( [ ([old_name, new_name], "2: full_name, name"), ([new_name, old_name], "2: full_name, name"), - ([both_zips], "4: address.postal_code, address.zip"), + ([both_zips], "5: address.element.postal_code, address.element.zip"), ([old_name.with_metadata(id_2), new_name.with_metadata(id_2)], "2: full_name, name"), ] ): @@ -3630,6 +3629,19 @@ def test_add_files_matches_columns_by_table_name_mapping(catalog: InMemoryCatalo with pytest.raises(ValueError, match="PyArrow table contains more columns: name"): catalog.load_table(identifier).add_files(file_locs[2:]) + # A stored mapping that lacks a column of the table cannot resolve that column, so the file is rejected. + incomplete = catalog.create_table( + "default.add_files_incomplete_name_mapping", + schema=Schema(NestedField(1, "id", LongType(), required=False), NestedField(2, "name", StringType(), required=False)), + properties={TableProperties.DEFAULT_NAME_MAPPING: '[{"field-id": 1, "names": ["id"]}]'}, + ) + file_loc = f"{tmp_path}/incomplete.parquet" + pq.write_table(pa.table({"id": [1], "name": ["a"]}), file_loc) + metadata = incomplete.metadata + with pytest.raises(ValueError): + incomplete.add_files([file_loc]) + assert catalog.load_table("default.add_files_incomplete_name_mapping").metadata == metadata + def test_add_files_with_field_ids_swapped_relative_to_names(catalog: InMemoryCatalog, tmp_path: str) -> None: # The file's "a" is field ID 2 and its "b" is field ID 1, the reverse of the table, as after renames. From 01f4b49fae9977873ea11fadbb45a3249d129881 Mon Sep 17 00:00:00 2001 From: rahulsmahadev Date: Thu, 3 Dec 2026 19:04:12 +0000 Subject: [PATCH 4/5] Retrigger CI Co-authored-by: Isaac From 522ab521158e8d92dcc32fa7456b6602096f2ec3 Mon Sep 17 00:00:00 2001 From: rahulsmahadev Date: Thu, 3 Dec 2026 20:26:39 +0000 Subject: [PATCH 5/5] Retrigger CI Co-authored-by: Isaac