From f1d881cca7be1a89054aad7a1654229434bf98bc Mon Sep 17 00:00:00 2001 From: malon64 Date: Wed, 25 Nov 2026 23:48:59 +0100 Subject: [PATCH 1/3] Add atomic create or replace table Add replace_table_transaction, create_or_replace_table_transaction and create_or_replace_table to Catalog, so engines like Polars can run CREATE OR REPLACE TABLE AS SELECT (e.g. for dbt) in a single commit. Mirrors Java's TableMetadata.buildReplacement: the table keeps its UUID and history, main is removed, field ids are reused by name, partition field ids by (source, transform), and properties are merged. The commit asserts only the table UUID and last assigned ids, like UpdateRequirements.forReplaceTable. Closes #4485 --- mkdocs/docs/api.md | 11 ++ pyiceberg/catalog/__init__.py | 88 +++++++++++++++ pyiceberg/schema.py | 23 ++++ pyiceberg/table/__init__.py | 141 +++++++++++++++++++++++- tests/catalog/test_catalog_behaviors.py | 84 ++++++++++++++ tests/test_schema.py | 24 ++++ 6 files changed, 368 insertions(+), 3 deletions(-) diff --git a/mkdocs/docs/api.md b/mkdocs/docs/api.md index f823a2fc60..634335a633 100644 --- a/mkdocs/docs/api.md +++ b/mkdocs/docs/api.md @@ -185,6 +185,17 @@ with catalog.create_table_transaction(identifier="docs_example.bids", schema=sch txn.set_properties(test_a="test_aa", test_b="test_b", test_c="test_c") ``` +## Create or replace a table + +`create_or_replace_table_transaction` creates the table, or atomically replaces it when it already exists (`CREATE OR REPLACE TABLE ... AS SELECT`). The new schema, partition spec, sort order and data become visible in a single commit, so readers never see an empty or half-written table: + +```python +with catalog.create_or_replace_table_transaction(identifier="docs_example.bids", schema=df.schema) as txn: + txn.append(df) +``` + +A replaced table keeps its UUID and snapshot history, field IDs are reused for columns with the same name, and the given properties are merged into the existing ones. Use `create_or_replace_table` to replace only the definition, or `replace_table_transaction` to fail with `NoSuchTableError` when the table does not exist. + ## Register a table To register a table using existing metadata: diff --git a/pyiceberg/catalog/__init__.py b/pyiceberg/catalog/__init__.py index 1c063cb526..ab9c0e0603 100644 --- a/pyiceberg/catalog/__init__.py +++ b/pyiceberg/catalog/__init__.py @@ -49,6 +49,7 @@ DOWNCAST_NS_TIMESTAMP_TO_US_ON_WRITE, CommitTableResponse, CreateTableTransaction, + ReplaceTableTransaction, StagedTable, Table, TableProperties, @@ -493,6 +494,93 @@ def create_table_if_not_exists( except TableAlreadyExistsError: return self.load_table(identifier) + def replace_table_transaction( + self, + identifier: str | Identifier, + schema: Schema | pa.Schema, + location: str | None = None, + partition_spec: PartitionSpec = UNPARTITIONED_PARTITION_SPEC, + sort_order: SortOrder = UNSORTED_SORT_ORDER, + properties: Properties = EMPTY_DICT, + ) -> ReplaceTableTransaction: + """Create a ReplaceTableTransaction that atomically replaces an existing table. + + The table keeps its UUID and history, but the main branch is removed until new data is + written in the transaction. Field IDs are reused by name, and the given properties are + merged into the existing ones. + + Args: + identifier (str | Identifier): Table identifier. + schema (Schema): Table's new schema. + location (str | None): New location for the table. Defaults to the current location. + partition_spec (PartitionSpec): New PartitionSpec for the table. + sort_order (SortOrder): New SortOrder for the table. + properties (Properties): Table properties to set on the table. + + Returns: + ReplaceTableTransaction: the transaction to stage changes in and commit. + + Raises: + NoSuchTableError: If a table with the name does not exist. + """ + table = self.load_table(identifier) + format_version = int(properties.get(TableProperties.FORMAT_VERSION, table.metadata.format_version)) + iceberg_schema = self._convert_schema_if_needed(schema, format_version) # type: ignore + return ReplaceTableTransaction(table, iceberg_schema, location, partition_spec, sort_order, properties) + + def create_or_replace_table_transaction( + self, + identifier: str | Identifier, + schema: Schema | pa.Schema, + location: str | None = None, + partition_spec: PartitionSpec = UNPARTITIONED_PARTITION_SPEC, + sort_order: SortOrder = UNSORTED_SORT_ORDER, + properties: Properties = EMPTY_DICT, + ) -> CreateTableTransaction | ReplaceTableTransaction: + """Create a transaction that creates the table, or atomically replaces it if it already exists. + + Args: + identifier (str | Identifier): Table identifier. + schema (Schema): Table's schema. + location (str | None): Location for the table. Optional Argument. + partition_spec (PartitionSpec): PartitionSpec for the table. + sort_order (SortOrder): SortOrder for the table. + properties (Properties): Table properties that can be a string based dictionary. + + Returns: + CreateTableTransaction | ReplaceTableTransaction: the transaction to stage changes in and commit. + """ + try: + return self.replace_table_transaction(identifier, schema, location, partition_spec, sort_order, properties) + except NoSuchTableError: + return self.create_table_transaction(identifier, schema, location, partition_spec, sort_order, properties) + + def create_or_replace_table( + self, + identifier: str | Identifier, + schema: Schema | pa.Schema, + location: str | None = None, + partition_spec: PartitionSpec = UNPARTITIONED_PARTITION_SPEC, + sort_order: SortOrder = UNSORTED_SORT_ORDER, + properties: Properties = EMPTY_DICT, + ) -> Table: + """Create a table, or atomically replace it if it already exists. + + Args: + identifier (str | Identifier): Table identifier. + schema (Schema): Table's schema. + location (str | None): Location for the table. Optional Argument. + partition_spec (PartitionSpec): PartitionSpec for the table. + sort_order (SortOrder): SortOrder for the table. + properties (Properties): Table properties that can be a string based dictionary. + + Returns: + Table: the created or replaced table instance. + """ + return self.create_or_replace_table_transaction( + identifier, schema, location, partition_spec, sort_order, properties + ).commit_transaction() + @abstractmethod def load_table(self, identifier: str | Identifier) -> Table: """Load the table's metadata and returns the table instance. diff --git a/pyiceberg/schema.py b/pyiceberg/schema.py index aa4e7493d5..538dfd1428 100644 --- a/pyiceberg/schema.py +++ b/pyiceberg/schema.py @@ -1342,6 +1342,13 @@ def assign_fresh_schema_ids(schema_or_type: Schema | IcebergType, next_id: Calla return pre_order_visit(schema_or_type, _SetFreshIDs(next_id_func=next_id)) +def assign_fresh_schema_ids_for_replace(schema: Schema, base_schema: Schema, last_column_id: int) -> Schema: + """Assign fresh IDs, reusing the base schema's ID for fields with the same name, like Java's TypeUtil.assignFreshIds.""" + # Make the IDs unique first: schemas converted from PyArrow have -1 for every field + schema = assign_fresh_schema_ids(schema) + return pre_order_visit(schema, _SetFreshIDsReusingBase(schema, base_schema, last_column_id)) + + class _SetFreshIDs(PreOrderSchemaVisitor[IcebergType]): """Traverses the schema and assigns monotonically increasing ids.""" @@ -1404,6 +1411,22 @@ def primitive(self, primitive: PrimitiveType) -> PrimitiveType: return primitive +class _SetFreshIDsReusingBase(_SetFreshIDs): + """Reuses the base schema's ID for fields with the same name and assigns new IDs above last_column_id otherwise.""" + + def __init__(self, schema: Schema, base_schema: Schema, last_column_id: int) -> None: + counter = itertools.count(last_column_id + 1) + super().__init__(lambda: next(counter)) + self._names = index_name_by_id(schema) + self._base_ids = index_by_name(base_schema) + + def _get_and_increment(self, current_id: int) -> int: + name = self._names[current_id] + new_id = self._base_ids[name] if name in self._base_ids else self.next_id_func() + self.old_id_to_new_id[current_id] = new_id + return new_id + + # Implementation copied from Apache Iceberg repo. def make_compatible_name(name: str) -> str: """Make a field name compatible with Avro specification. diff --git a/pyiceberg/table/__init__.py b/pyiceberg/table/__init__.py index a8fcdb16e6..7d8774cb8e 100644 --- a/pyiceberg/table/__init__.py +++ b/pyiceberg/table/__init__.py @@ -56,8 +56,15 @@ ManifestEntryStatus, ManifestFile, ) -from pyiceberg.partitioning import PARTITION_FIELD_ID_START, UNPARTITIONED_PARTITION_SPEC, PartitionKey, PartitionSpec -from pyiceberg.schema import Schema +from pyiceberg.partitioning import ( + PARTITION_FIELD_ID_START, + UNPARTITIONED_PARTITION_SPEC, + PartitionField, + PartitionKey, + PartitionSpec, + assign_fresh_partition_spec_ids, +) +from pyiceberg.schema import Schema, assign_fresh_schema_ids_for_replace from pyiceberg.table.delete_file_index import DeleteFileIndex from pyiceberg.table.inspect import InspectTable from pyiceberg.table.labels import Labels @@ -75,17 +82,23 @@ is_ancestor_of, is_parent_ancestor_of, ) -from pyiceberg.table.sorting import UNSORTED_SORT_ORDER, SortOrder +from pyiceberg.table.sorting import UNSORTED_SORT_ORDER, SortOrder, assign_fresh_sort_order_ids from pyiceberg.table.update import ( AddPartitionSpecUpdate, AddSchemaUpdate, AddSnapshotUpdate, AddSortOrderUpdate, AssertCreate, + AssertCurrentSchemaId, + AssertDefaultSortOrderId, + AssertDefaultSpecId, + AssertLastAssignedFieldId, + AssertLastAssignedPartitionId, AssertRefSnapshotId, AssertTableUUID, AssignUUIDUpdate, RemovePropertiesUpdate, + RemoveSnapshotRefUpdate, SetCurrentSchemaUpdate, SetDefaultSortOrderUpdate, SetDefaultSpecUpdate, @@ -1361,6 +1374,128 @@ def commit_transaction(self) -> Table: return self._table +class ReplaceTableTransaction(Transaction): + """A transaction that atomically replaces the definition and data of an existing table. + + Mirrors Java's TableMetadata.buildReplacement: the UUID, snapshots and history are kept, the main + branch is removed, field IDs are reused by name, and properties are merged into the existing ones. + """ + + def __init__( + self, + table: Table, + schema: Schema, + location: str | None = None, + partition_spec: PartitionSpec = UNPARTITIONED_PARTITION_SPEC, + sort_order: SortOrder = UNSORTED_SORT_ORDER, + properties: Properties = EMPTY_DICT, + ): + super().__init__(table, autocommit=False) + base = table.metadata + properties = dict(properties) + format_version = int(properties.pop(TableProperties.FORMAT_VERSION, base.format_version)) + if format_version < base.format_version: + raise ValueError(f"Cannot downgrade v{base.format_version} table to v{format_version}") + if format_version == 1 and not (base.spec().is_unpartitioned() and partition_spec.is_unpartitioned()): + # TODO: support Java's carry-forward of the current v1 partition fields as void transforms + raise ValueError("Replacing a partitioned v1 table is not supported, set format-version to 2 or higher") + schema.check_format_version_compatibility(format_version) + + fresh_schema = assign_fresh_schema_ids_for_replace(schema, base.schema(), base.last_column_id) + fresh_spec = assign_fresh_partition_spec_ids(partition_spec, schema, fresh_schema) + fresh_sort_order = assign_fresh_sort_order_ids(sort_order, schema, fresh_schema) + + if format_version > base.format_version: + self._updates += (UpgradeFormatVersionUpdate(format_version=format_version),) + if MAIN_BRANCH in base.refs: + self._updates += (RemoveSnapshotRefUpdate(ref_name=MAIN_BRANCH),) + + # Reuse partition field IDs by (source, transform) across all specs, new fields get IDs above last_partition_id + existing_fields = sorted((f for s in base.partition_specs for f in s.fields), key=lambda f: f.field_id) + field_ids = {(f.source_id, str(f.transform)): f.field_id for f in existing_fields} # highest ID wins, like Java + next_field_id = itertools.count((base.last_partition_id or PARTITION_FIELD_ID_START - 1) + 1) + fresh_spec = PartitionSpec( + *[ + PartitionField( + source_id=f.source_id, + field_id=field_ids.get((f.source_id, str(f.transform))) or next(next_field_id), + transform=f.transform, + name=f.name, + ) + for f in fresh_spec.fields + ] + ) + + # Reuse an existing schema, spec or sort order when identical, otherwise add it and make it the default + if (schema_id := next((s.schema_id for s in base.schemas if s == fresh_schema), None)) is not None: + self._updates += (SetCurrentSchemaUpdate(schema_id=schema_id),) + else: + new_schema_id = max(s.schema_id for s in base.schemas) + 1 + self._updates += ( + AddSchemaUpdate(schema_=fresh_schema.model_copy(update={"schema_id": new_schema_id})), + SetCurrentSchemaUpdate(schema_id=-1), + ) + + if (spec_id := next((s.spec_id for s in base.partition_specs if s.fields == fresh_spec.fields), None)) is not None: + self._updates += (SetDefaultSpecUpdate(spec_id=spec_id),) + else: + new_spec_id = max(s.spec_id for s in base.partition_specs) + 1 + self._updates += ( + AddPartitionSpecUpdate(spec=PartitionSpec(*fresh_spec.fields, spec_id=new_spec_id)), + SetDefaultSpecUpdate(spec_id=-1), + ) + + if (order_id := next((o.order_id for o in base.sort_orders if o.fields == fresh_sort_order.fields), None)) is not None: + self._updates += (SetDefaultSortOrderUpdate(sort_order_id=order_id),) + elif fresh_sort_order.is_unsorted: + # The unsorted order always has ID 0 + self._updates += (AddSortOrderUpdate(sort_order=UNSORTED_SORT_ORDER), SetDefaultSortOrderUpdate(sort_order_id=0)) + else: + new_order_id = max(o.order_id for o in base.sort_orders) + 1 + self._updates += ( + AddSortOrderUpdate(sort_order=SortOrder(*fresh_sort_order.fields, order_id=new_order_id)), + SetDefaultSortOrderUpdate(sort_order_id=-1), + ) + + if location and location.rstrip("/") != base.location: + self._updates += (SetLocationUpdate(location=location.rstrip("/")),) + if properties: + self._updates += (SetPropertiesUpdate(updates=properties),) + + def commit_transaction(self) -> Table: + """Commit the replacement to the catalog. + + Like Java's UpdateRequirements.forReplaceTable, the main branch and current IDs are overwritten + regardless of concurrent changes; only the table identity and ID assignment are asserted. + + Unlike Java, the current schema, spec or sort order is also asserted when a new one is added: the + catalogs in PyIceberg keep the IDs assigned by the client, so a concurrent addition would reuse the ID. + + Returns: + The table with the updates applied. + """ + if len(self._updates) > 0: + base = self._table.metadata + requirements: tuple[TableRequirement, ...] = ( + AssertTableUUID(uuid=base.table_uuid), + AssertLastAssignedFieldId(last_assigned_field_id=base.last_column_id), + AssertLastAssignedPartitionId(last_assigned_partition_id=base.last_partition_id), + ) + update_types = {type(update) for update in self._updates} + if AddSchemaUpdate in update_types: + requirements += (AssertCurrentSchemaId(current_schema_id=base.current_schema_id),) + if AddPartitionSpecUpdate in update_types: + requirements += (AssertDefaultSpecId(default_spec_id=base.default_spec_id),) + if AddSortOrderUpdate in update_types: + requirements += (AssertDefaultSortOrderId(default_sort_order_id=base.default_sort_order_id),) + self._table._do_commit(updates=self._updates, requirements=requirements) # pylint: disable=W0212 + + self._updates = () + self._requirements = () + + return self._table + + class Namespace(IcebergRootModel[list[str]]): """Reference to one or more levels of a namespace.""" diff --git a/tests/catalog/test_catalog_behaviors.py b/tests/catalog/test_catalog_behaviors.py index cface2e0d0..e51e460066 100644 --- a/tests/catalog/test_catalog_behaviors.py +++ b/tests/catalog/test_catalog_behaviors.py @@ -188,6 +188,90 @@ def test_create_table_transaction(catalog: Catalog, format_version: int) -> None assert len(tbl.scan().to_arrow()) == 6 +def test_create_or_replace_table(catalog: Catalog, random_table_identifier: Identifier) -> None: + catalog.create_namespace(Catalog.namespace_from(random_table_identifier)) + df = pa.table({"foo": ["a", "b"], "bar": pa.array([1, 2], pa.int32())}) + + # Creates the table when it does not exist + table = catalog.create_or_replace_table(random_table_identifier, df.schema, properties={"keep": "me"}) + table.append(df) + old_snapshot_id = table.metadata.current_snapshot_id + + new_df = pa.table({"bar": pa.array([3], pa.int32()), "baz": [True]}) + with catalog.create_or_replace_table_transaction(random_table_identifier, new_df.schema, properties={"new": "prop"}) as txn: + txn.append(new_df) + + replaced = catalog.load_table(random_table_identifier) + assert replaced.metadata.table_uuid == table.metadata.table_uuid + # bar keeps its field ID, baz gets a new one above last-column-id + assert [(f.name, f.field_id) for f in replaced.schema().fields] == [("bar", 2), ("baz", 3)] + assert replaced.properties["keep"] == "me" and replaced.properties["new"] == "prop" + # History is kept, but the new snapshot starts a fresh lineage with only the new data + assert old_snapshot_id in [s.snapshot_id for s in replaced.snapshots()] + assert replaced.current_snapshot().parent_snapshot_id is None # type: ignore + assert replaced.scan().to_arrow() == new_df + + +def test_replace_table_reuses_partition_spec_and_schema(catalog: Catalog, test_table_identifier: Identifier) -> None: + catalog.create_namespace(Catalog.namespace_from(test_table_identifier)) + schema = Schema(NestedField(1, "foo", StringType()), NestedField(2, "bar", IntegerType())) + spec = PartitionSpec(PartitionField(source_id=2, field_id=1000, transform=IdentityTransform(), name="bar")) + catalog.create_table(test_table_identifier, schema, partition_spec=spec) + + unpartitioned = catalog.create_or_replace_table(test_table_identifier, schema) + assert unpartitioned.spec().is_unpartitioned() + assert unpartitioned.current_snapshot() is None + + replaced = catalog.create_or_replace_table(test_table_identifier, schema, partition_spec=spec) + assert replaced.metadata.default_spec_id == 0 + assert replaced.spec().fields[0].field_id == 1000 + assert len(replaced.metadata.schemas) == 1 + + +def test_replace_table_transaction_raises_when_table_does_not_exist( + catalog: Catalog, test_table_identifier: Identifier, table_schema_simple: Schema +) -> None: + with pytest.raises(NoSuchTableError): + catalog.replace_table_transaction(test_table_identifier, table_schema_simple) + + +def test_replace_table_fails_when_table_is_recreated( + catalog: Catalog, test_table_identifier: Identifier, table_schema_simple: Schema +) -> None: + catalog.create_namespace(Catalog.namespace_from(test_table_identifier)) + catalog.create_table(test_table_identifier, table_schema_simple) + txn = catalog.replace_table_transaction(test_table_identifier, table_schema_simple) + + catalog.drop_table(test_table_identifier) + catalog.create_table(test_table_identifier, table_schema_simple) + + with pytest.raises(CommitFailedException): + txn.commit_transaction() + + +def test_replace_table_fails_on_concurrent_schema_or_sort_order_change( + catalog: Catalog, test_table_identifier: Identifier, table_schema_simple: Schema +) -> None: + catalog.create_namespace(Catalog.namespace_from(test_table_identifier)) + table = catalog.create_table(test_table_identifier, table_schema_simple) + new_schema = Schema(NestedField(1, "foo", StringType()), NestedField(2, "qux", IntegerType())) + + # A concurrent change that adds no column IDs would otherwise reuse the ID of the schema added by the replace + txn = catalog.replace_table_transaction(test_table_identifier, new_schema) + table.update_schema().rename_column("baz", "renamed").commit() + with pytest.raises(CommitFailedException): + txn.commit_transaction() + + txn = catalog.replace_table_transaction(test_table_identifier, table.schema(), sort_order=SortOrder(SortField(source_id=1))) + table.update_sort_order().desc("foo", IdentityTransform()).commit() + with pytest.raises(CommitFailedException): + txn.commit_transaction() + + loaded = catalog.load_table(test_table_identifier) + assert loaded.schema() == table.schema() + assert len(loaded.metadata.schemas) == 2 + + def test_create_table_default_sort_order( catalog: Catalog, table_schema_nested: Schema, test_table_identifier: Identifier ) -> None: diff --git a/tests/test_schema.py b/tests/test_schema.py index 9f16282999..185f792ff6 100644 --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -26,6 +26,7 @@ Accessor, Schema, _check_schema_compatible, + assign_fresh_schema_ids_for_replace, build_position_accessors, index_by_id, index_by_name, @@ -1972,3 +1973,26 @@ def test_check_schema_compatible_optional_map_field_present() -> None: ) # Should not raise - schemas match _check_schema_compatible(requested_schema, provided_schema) + + +def test_assign_fresh_schema_ids_for_replace_reuses_ids_by_name() -> None: + base = Schema( + NestedField(1, "id", LongType(), required=True), + NestedField(2, "tags", ListType(3, StringType())), + NestedField(4, "dropped", StringType()), + identifier_field_ids=[1], + ) + # IDs of the new schema are ignored, like the -1 IDs of schemas converted from PyArrow + new = Schema( + NestedField(-1, "added", StringType()), + NestedField(-1, "tags", ListType(-1, StringType())), + NestedField(-1, "id", LongType(), required=True), + ) + + fresh = assign_fresh_schema_ids_for_replace(new, base, last_column_id=4) + + assert fresh == Schema( + NestedField(5, "added", StringType()), + NestedField(2, "tags", ListType(3, StringType())), + NestedField(1, "id", LongType(), required=True), + ) From 4a75542849524daf5e284d648dfa9af9cd3720fd Mon Sep 17 00:00:00 2001 From: malon64 Date: Sat, 28 Nov 2026 18:56:05 +0000 Subject: [PATCH 2/3] Address review comments on replace table Drop create_or_replace_table, the transaction already covers it. Clean up written files and refuse reuse when a replace commit fails, like Transaction.commit_transaction. Build the snapshot producer's location provider from the transaction metadata, so a new location or write.metadata.path applies to manifests too. Validate the target format version and properties up front. --- mkdocs/docs/api.md | 2 +- pyiceberg/catalog/__init__.py | 26 ------------ pyiceberg/table/__init__.py | 27 +++++++++++- pyiceberg/table/update/snapshot.py | 9 +++- tests/catalog/test_catalog_behaviors.py | 55 +++++++++++++++++++++++-- 5 files changed, 85 insertions(+), 34 deletions(-) diff --git a/mkdocs/docs/api.md b/mkdocs/docs/api.md index 634335a633..65d59ee307 100644 --- a/mkdocs/docs/api.md +++ b/mkdocs/docs/api.md @@ -194,7 +194,7 @@ with catalog.create_or_replace_table_transaction(identifier="docs_example.bids", txn.append(df) ``` -A replaced table keeps its UUID and snapshot history, field IDs are reused for columns with the same name, and the given properties are merged into the existing ones. Use `create_or_replace_table` to replace only the definition, or `replace_table_transaction` to fail with `NoSuchTableError` when the table does not exist. +A replaced table keeps its UUID and snapshot history, field IDs are reused for columns with the same name, and the given properties are merged into the existing ones. Use `replace_table_transaction` to fail with `NoSuchTableError` when the table does not exist. ## Register a table diff --git a/pyiceberg/catalog/__init__.py b/pyiceberg/catalog/__init__.py index ab9c0e0603..0484a18e2f 100644 --- a/pyiceberg/catalog/__init__.py +++ b/pyiceberg/catalog/__init__.py @@ -555,32 +555,6 @@ def create_or_replace_table_transaction( except NoSuchTableError: return self.create_table_transaction(identifier, schema, location, partition_spec, sort_order, properties) - def create_or_replace_table( - self, - identifier: str | Identifier, - schema: Schema | pa.Schema, - location: str | None = None, - partition_spec: PartitionSpec = UNPARTITIONED_PARTITION_SPEC, - sort_order: SortOrder = UNSORTED_SORT_ORDER, - properties: Properties = EMPTY_DICT, - ) -> Table: - """Create a table, or atomically replace it if it already exists. - - Args: - identifier (str | Identifier): Table identifier. - schema (Schema): Table's schema. - location (str | None): Location for the table. Optional Argument. - partition_spec (PartitionSpec): PartitionSpec for the table. - sort_order (SortOrder): SortOrder for the table. - properties (Properties): Table properties that can be a string based dictionary. - - Returns: - Table: the created or replaced table instance. - """ - return self.create_or_replace_table_transaction( - identifier, schema, location, partition_spec, sort_order, properties - ).commit_transaction() - @abstractmethod def load_table(self, identifier: str | Identifier) -> Table: """Load the table's metadata and returns the table instance. diff --git a/pyiceberg/table/__init__.py b/pyiceberg/table/__init__.py index 7d8774cb8e..3beb5312f9 100644 --- a/pyiceberg/table/__init__.py +++ b/pyiceberg/table/__init__.py @@ -70,7 +70,12 @@ from pyiceberg.table.labels import Labels from pyiceberg.table.locations import LocationProvider, load_location_provider from pyiceberg.table.maintenance import MaintenanceTable -from pyiceberg.table.metadata import INITIAL_SEQUENCE_NUMBER, TableMetadata +from pyiceberg.table.metadata import ( + INITIAL_SEQUENCE_NUMBER, + SUPPORTED_TABLE_FORMAT_VERSION, + TableMetadata, + _check_properties_format_version_compatibility, +) from pyiceberg.table.metadata_columns import project_schema, split_selected_fields from pyiceberg.table.name_mapping import NameMapping from pyiceberg.table.refs import MAIN_BRANCH, SnapshotRef @@ -1396,10 +1401,13 @@ def __init__( format_version = int(properties.pop(TableProperties.FORMAT_VERSION, base.format_version)) if format_version < base.format_version: raise ValueError(f"Cannot downgrade v{base.format_version} table to v{format_version}") + if format_version > base.format_version and format_version > SUPPORTED_TABLE_FORMAT_VERSION: + raise ValueError(f"Unsupported table format version: {format_version}") if format_version == 1 and not (base.spec().is_unpartitioned() and partition_spec.is_unpartitioned()): # TODO: support Java's carry-forward of the current v1 partition fields as void transforms raise ValueError("Replacing a partitioned v1 table is not supported, set format-version to 2 or higher") schema.check_format_version_compatibility(format_version) + _check_properties_format_version_compatibility(properties, format_version) fresh_schema = assign_fresh_schema_ids_for_replace(schema, base.schema(), base.last_column_id) fresh_spec = assign_fresh_partition_spec_ids(partition_spec, schema, fresh_schema) @@ -1474,6 +1482,8 @@ def commit_transaction(self) -> Table: Returns: The table with the updates applied. """ + if self._failed: + raise RuntimeError("This transaction failed to commit and cannot be reused; create a new transaction.") if len(self._updates) > 0: base = self._table.metadata requirements: tuple[TableRequirement, ...] = ( @@ -1488,7 +1498,20 @@ def commit_transaction(self) -> Table: requirements += (AssertDefaultSpecId(default_spec_id=base.default_spec_id),) if AddSortOrderUpdate in update_types: requirements += (AssertDefaultSortOrderId(default_sort_order_id=base.default_sort_order_id),) - self._table._do_commit(updates=self._updates, requirements=requirements) # pylint: disable=W0212 + try: + try: + self._table._do_commit(updates=self._updates, requirements=requirements) # pylint: disable=W0212 + except CommitFailedException: + # Same as Transaction.commit_transaction: only delete the written files when the commit did not land + if not (self._snapshot_producers and self._attempt_landed()): + for producer in self._snapshot_producers: + producer._clean_all_uncommitted() + raise + except Exception: + self._failed = True + raise + + self._snapshot_producers = [] self._updates = () self._requirements = () diff --git a/pyiceberg/table/update/snapshot.py b/pyiceberg/table/update/snapshot.py index 7a37b76287..171d9cc38f 100644 --- a/pyiceberg/table/update/snapshot.py +++ b/pyiceberg/table/update/snapshot.py @@ -57,6 +57,7 @@ ) from pyiceberg.partitioning import PartitionSpec from pyiceberg.schema import Schema +from pyiceberg.table.locations import load_location_provider from pyiceberg.table.refs import MAIN_BRANCH, SnapshotRef, SnapshotRefType from pyiceberg.table.snapshots import ( Operation, @@ -344,7 +345,9 @@ def _commit(self) -> UpdatesAndRequirements: attempt=0, commit_uuid=self.commit_uuid, ) - location_provider = self._transaction._table.location_provider() + location_provider = load_location_provider( + self._transaction.table_metadata.location, self._transaction.table_metadata.properties + ) manifest_list_file_path = location_provider.new_metadata_location(file_name) self._written_manifest_lists.append(manifest_list_file_path) @@ -422,7 +425,9 @@ def new_manifest_writer(self, spec: PartitionSpec) -> ManifestWriter: ) def new_manifest_output(self) -> OutputFile: - location_provider = self._transaction._table.location_provider() + location_provider = load_location_provider( + self._transaction.table_metadata.location, self._transaction.table_metadata.properties + ) file_name = _new_manifest_file_name(num=next(self._manifest_num_counter), commit_uuid=self.commit_uuid) file_path = location_provider.new_metadata_location(file_name) self._written_manifests.append(file_path) diff --git a/tests/catalog/test_catalog_behaviors.py b/tests/catalog/test_catalog_behaviors.py index e51e460066..f5ade0798e 100644 --- a/tests/catalog/test_catalog_behaviors.py +++ b/tests/catalog/test_catalog_behaviors.py @@ -193,7 +193,9 @@ def test_create_or_replace_table(catalog: Catalog, random_table_identifier: Iden df = pa.table({"foo": ["a", "b"], "bar": pa.array([1, 2], pa.int32())}) # Creates the table when it does not exist - table = catalog.create_or_replace_table(random_table_identifier, df.schema, properties={"keep": "me"}) + table = catalog.create_or_replace_table_transaction( + random_table_identifier, df.schema, properties={"keep": "me"} + ).commit_transaction() table.append(df) old_snapshot_id = table.metadata.current_snapshot_id @@ -218,11 +220,11 @@ def test_replace_table_reuses_partition_spec_and_schema(catalog: Catalog, test_t spec = PartitionSpec(PartitionField(source_id=2, field_id=1000, transform=IdentityTransform(), name="bar")) catalog.create_table(test_table_identifier, schema, partition_spec=spec) - unpartitioned = catalog.create_or_replace_table(test_table_identifier, schema) + unpartitioned = catalog.replace_table_transaction(test_table_identifier, schema).commit_transaction() assert unpartitioned.spec().is_unpartitioned() assert unpartitioned.current_snapshot() is None - replaced = catalog.create_or_replace_table(test_table_identifier, schema, partition_spec=spec) + replaced = catalog.replace_table_transaction(test_table_identifier, schema, partition_spec=spec).commit_transaction() assert replaced.metadata.default_spec_id == 0 assert replaced.spec().fields[0].field_id == 1000 assert len(replaced.metadata.schemas) == 1 @@ -272,6 +274,53 @@ def test_replace_table_fails_on_concurrent_schema_or_sort_order_change( assert len(loaded.metadata.schemas) == 2 +def test_replace_table_cleans_up_on_failed_commit(catalog: Catalog, random_table_identifier: Identifier) -> None: + catalog.create_namespace(Catalog.namespace_from(random_table_identifier)) + df = pa.table({"foo": ["a", "b"]}) + table = catalog.create_table(random_table_identifier, df.schema) + + txn = catalog.replace_table_transaction(random_table_identifier, df.schema) + txn.append(df) + manifest_list = txn.table_metadata.snapshot_by_name("main").manifest_list # type: ignore + + # A concurrent column addition fails the last-assigned field ID requirement + table.update_schema().add_column("bar", StringType()).commit() + with pytest.raises(CommitFailedException): + txn.commit_transaction() + assert not table.io.new_input(manifest_list).exists() + + with pytest.raises(RuntimeError, match="cannot be reused"): + txn.commit_transaction() + + +def test_replace_table_writes_to_new_location(catalog: Catalog, random_table_identifier: Identifier) -> None: + catalog.create_namespace(Catalog.namespace_from(random_table_identifier)) + df = pa.table({"foo": ["a", "b"]}) + table = catalog.create_table(random_table_identifier, df.schema) + new_location = f"{table.location()}_replaced" + + with catalog.replace_table_transaction(random_table_identifier, df.schema, location=new_location) as txn: + txn.append(df) + + replaced = catalog.load_table(random_table_identifier) + snapshot = replaced.current_snapshot() + assert snapshot is not None + assert snapshot.manifest_list.startswith(new_location) + assert all(m.manifest_path.startswith(new_location) for m in snapshot.manifests(replaced.io)) + assert all(task.file.file_path.startswith(new_location) for task in replaced.scan().plan_files()) + + +def test_replace_table_rejects_invalid_format_version( + catalog: Catalog, test_table_identifier: Identifier, table_schema_simple: Schema +) -> None: + catalog.create_namespace(Catalog.namespace_from(test_table_identifier)) + catalog.create_table(test_table_identifier, table_schema_simple) + + for properties in [{TableProperties.FORMAT_VERSION: "99"}, {TableProperties.ENCRYPTION_KEY_ID: "key"}]: + with pytest.raises(ValueError): + catalog.replace_table_transaction(test_table_identifier, table_schema_simple, properties=properties) + + def test_create_table_default_sort_order( catalog: Catalog, table_schema_nested: Schema, test_table_identifier: Identifier ) -> None: From 8cb0db0e8f6bdc4eaa540e32cf6d888bd4b3cac6 Mon Sep 17 00:00:00 2001 From: malon64 Date: Sat, 28 Nov 2026 20:56:12 +0000 Subject: [PATCH 3/3] Assert main on replace when writing data The replaced main has no parent, so a snapshot built from a stale base is accepted with an old sequence number and a concurrent commit makes last-sequence-number go backwards. Fail the replace instead. Also run the new replace tests with a single identifier fixture. --- pyiceberg/table/__init__.py | 4 ++ tests/catalog/test_catalog_behaviors.py | 50 ++++++++++++------------- 2 files changed, 29 insertions(+), 25 deletions(-) diff --git a/pyiceberg/table/__init__.py b/pyiceberg/table/__init__.py index 3beb5312f9..b3d002c7ef 100644 --- a/pyiceberg/table/__init__.py +++ b/pyiceberg/table/__init__.py @@ -1478,6 +1478,8 @@ def commit_transaction(self) -> Table: Unlike Java, the current schema, spec or sort order is also asserted when a new one is added: the catalogs in PyIceberg keep the IDs assigned by the client, so a concurrent addition would reuse the ID. + When data is written, main is also asserted: the new snapshot has no parent, so a concurrent commit + would otherwise make the table's last sequence number go backwards. Returns: The table with the updates applied. @@ -1498,6 +1500,8 @@ def commit_transaction(self) -> Table: requirements += (AssertDefaultSpecId(default_spec_id=base.default_spec_id),) if AddSortOrderUpdate in update_types: requirements += (AssertDefaultSortOrderId(default_sort_order_id=base.default_sort_order_id),) + if self._snapshot_producers: + requirements += (AssertRefSnapshotId(ref=MAIN_BRANCH, snapshot_id=base.current_snapshot_id),) try: try: self._table._do_commit(updates=self._updates, requirements=requirements) # pylint: disable=W0212 diff --git a/tests/catalog/test_catalog_behaviors.py b/tests/catalog/test_catalog_behaviors.py index f5ade0798e..00369675ca 100644 --- a/tests/catalog/test_catalog_behaviors.py +++ b/tests/catalog/test_catalog_behaviors.py @@ -214,62 +214,62 @@ def test_create_or_replace_table(catalog: Catalog, random_table_identifier: Iden assert replaced.scan().to_arrow() == new_df -def test_replace_table_reuses_partition_spec_and_schema(catalog: Catalog, test_table_identifier: Identifier) -> None: - catalog.create_namespace(Catalog.namespace_from(test_table_identifier)) +def test_replace_table_reuses_partition_spec_and_schema(catalog: Catalog, random_table_identifier: Identifier) -> None: + catalog.create_namespace(Catalog.namespace_from(random_table_identifier)) schema = Schema(NestedField(1, "foo", StringType()), NestedField(2, "bar", IntegerType())) spec = PartitionSpec(PartitionField(source_id=2, field_id=1000, transform=IdentityTransform(), name="bar")) - catalog.create_table(test_table_identifier, schema, partition_spec=spec) + catalog.create_table(random_table_identifier, schema, partition_spec=spec) - unpartitioned = catalog.replace_table_transaction(test_table_identifier, schema).commit_transaction() + unpartitioned = catalog.replace_table_transaction(random_table_identifier, schema).commit_transaction() assert unpartitioned.spec().is_unpartitioned() assert unpartitioned.current_snapshot() is None - replaced = catalog.replace_table_transaction(test_table_identifier, schema, partition_spec=spec).commit_transaction() + replaced = catalog.replace_table_transaction(random_table_identifier, schema, partition_spec=spec).commit_transaction() assert replaced.metadata.default_spec_id == 0 assert replaced.spec().fields[0].field_id == 1000 assert len(replaced.metadata.schemas) == 1 def test_replace_table_transaction_raises_when_table_does_not_exist( - catalog: Catalog, test_table_identifier: Identifier, table_schema_simple: Schema + catalog: Catalog, random_table_identifier: Identifier, table_schema_simple: Schema ) -> None: with pytest.raises(NoSuchTableError): - catalog.replace_table_transaction(test_table_identifier, table_schema_simple) + catalog.replace_table_transaction(random_table_identifier, table_schema_simple) def test_replace_table_fails_when_table_is_recreated( - catalog: Catalog, test_table_identifier: Identifier, table_schema_simple: Schema + catalog: Catalog, random_table_identifier: Identifier, table_schema_simple: Schema ) -> None: - catalog.create_namespace(Catalog.namespace_from(test_table_identifier)) - catalog.create_table(test_table_identifier, table_schema_simple) - txn = catalog.replace_table_transaction(test_table_identifier, table_schema_simple) + catalog.create_namespace(Catalog.namespace_from(random_table_identifier)) + catalog.create_table(random_table_identifier, table_schema_simple) + txn = catalog.replace_table_transaction(random_table_identifier, table_schema_simple) - catalog.drop_table(test_table_identifier) - catalog.create_table(test_table_identifier, table_schema_simple) + catalog.drop_table(random_table_identifier) + catalog.create_table(random_table_identifier, table_schema_simple) with pytest.raises(CommitFailedException): txn.commit_transaction() def test_replace_table_fails_on_concurrent_schema_or_sort_order_change( - catalog: Catalog, test_table_identifier: Identifier, table_schema_simple: Schema + catalog: Catalog, random_table_identifier: Identifier, table_schema_simple: Schema ) -> None: - catalog.create_namespace(Catalog.namespace_from(test_table_identifier)) - table = catalog.create_table(test_table_identifier, table_schema_simple) + catalog.create_namespace(Catalog.namespace_from(random_table_identifier)) + table = catalog.create_table(random_table_identifier, table_schema_simple) new_schema = Schema(NestedField(1, "foo", StringType()), NestedField(2, "qux", IntegerType())) # A concurrent change that adds no column IDs would otherwise reuse the ID of the schema added by the replace - txn = catalog.replace_table_transaction(test_table_identifier, new_schema) + txn = catalog.replace_table_transaction(random_table_identifier, new_schema) table.update_schema().rename_column("baz", "renamed").commit() with pytest.raises(CommitFailedException): txn.commit_transaction() - txn = catalog.replace_table_transaction(test_table_identifier, table.schema(), sort_order=SortOrder(SortField(source_id=1))) + txn = catalog.replace_table_transaction(random_table_identifier, table.schema(), sort_order=SortOrder(SortField(source_id=1))) table.update_sort_order().desc("foo", IdentityTransform()).commit() with pytest.raises(CommitFailedException): txn.commit_transaction() - loaded = catalog.load_table(test_table_identifier) + loaded = catalog.load_table(random_table_identifier) assert loaded.schema() == table.schema() assert len(loaded.metadata.schemas) == 2 @@ -283,8 +283,8 @@ def test_replace_table_cleans_up_on_failed_commit(catalog: Catalog, random_table txn.append(df) manifest_list = txn.table_metadata.snapshot_by_name("main").manifest_list # type: ignore - # A concurrent column addition fails the last-assigned field ID requirement - table.update_schema().add_column("bar", StringType()).commit() + # A concurrent append moves main, which would otherwise make the sequence numbers go backwards + table.append(df) with pytest.raises(CommitFailedException): txn.commit_transaction() assert not table.io.new_input(manifest_list).exists() @@ -311,14 +311,14 @@ def test_replace_table_writes_to_new_location(catalog: Catalog, random_table_ide def test_replace_table_rejects_invalid_format_version( - catalog: Catalog, test_table_identifier: Identifier, table_schema_simple: Schema + catalog: Catalog, random_table_identifier: Identifier, table_schema_simple: Schema ) -> None: - catalog.create_namespace(Catalog.namespace_from(test_table_identifier)) - catalog.create_table(test_table_identifier, table_schema_simple) + catalog.create_namespace(Catalog.namespace_from(random_table_identifier)) + catalog.create_table(random_table_identifier, table_schema_simple) for properties in [{TableProperties.FORMAT_VERSION: "99"}, {TableProperties.ENCRYPTION_KEY_ID: "key"}]: with pytest.raises(ValueError): - catalog.replace_table_transaction(test_table_identifier, table_schema_simple, properties=properties) + catalog.replace_table_transaction(random_table_identifier, table_schema_simple, properties=properties) def test_create_table_default_sort_order(