From f1d881cca7be1a89054aad7a1654229434bf98bc Mon Sep 17 00:00:00 2001 From: malon64 Date: Wed, 25 Nov 2026 23:48:59 +0100 Subject: [PATCH 1/6] 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/6] 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/6] 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( From fc49119e2611a421ae109e3be03983c22f3bba76 Mon Sep 17 00:00:00 2001 From: malon64 Date: Wed, 2 Dec 2026 20:28:43 +0000 Subject: [PATCH 4/6] Reject snapshots that would lower last-sequence-number A snapshot without a parent may carry an old sequence number, so a stale replace committed after writes to another branch made last-sequence-number go backwards. Java rejects this when building the metadata (indexAndValidateSnapshots); do the same when adding the snapshot. --- pyiceberg/table/update/__init__.py | 10 ++++++++++ tests/catalog/test_catalog_behaviors.py | 18 ++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/pyiceberg/table/update/__init__.py b/pyiceberg/table/update/__init__.py index 62d0bbd724..b652b81a80 100644 --- a/pyiceberg/table/update/__init__.py +++ b/pyiceberg/table/update/__init__.py @@ -465,6 +465,16 @@ def _(update: AddSnapshotUpdate, base_metadata: TableMetadata, context: _TableMe f"Cannot add snapshot with sequence number {update.snapshot.sequence_number} " f"older than last sequence number {base_metadata.last_sequence_number}" ) + elif ( + base_metadata.format_version >= 2 + and update.snapshot.sequence_number is not None + and any((s.sequence_number or 0) > update.snapshot.sequence_number for s in base_metadata.snapshots) + ): + # Like Java's indexAndValidateSnapshots: last-sequence-number must not go below an existing snapshot's + raise ValueError( + f"Cannot add snapshot with sequence number {update.snapshot.sequence_number} " + f"older than an existing snapshot's sequence number" + ) elif base_metadata.format_version >= 3 and update.snapshot.first_row_id is None: raise ValueError("Cannot add snapshot without first row id") elif ( diff --git a/tests/catalog/test_catalog_behaviors.py b/tests/catalog/test_catalog_behaviors.py index 00369675ca..f619f8b3cb 100644 --- a/tests/catalog/test_catalog_behaviors.py +++ b/tests/catalog/test_catalog_behaviors.py @@ -293,6 +293,24 @@ def test_replace_table_cleans_up_on_failed_commit(catalog: Catalog, random_table txn.commit_transaction() +def test_replace_table_fails_on_concurrent_commit_to_other_branch(catalog: Catalog, random_table_identifier: Identifier) -> None: + catalog.create_namespace(Catalog.namespace_from(random_table_identifier)) + df = pa.table({"foo": ["a"]}) + table = catalog.create_table(random_table_identifier, df.schema) + table.append(df) + table.manage_snapshots().create_branch(table.metadata.current_snapshot_id, "audit").commit() # type: ignore + + txn = catalog.replace_table_transaction(random_table_identifier, df.schema) + txn.append(df) + + # Two commits to another branch pass the main assertion, but the replace would make last-sequence-number go backwards + table.append(df, branch="audit") + table.append(df, branch="audit") + with pytest.raises(ValueError, match="older than an existing snapshot's sequence number"): + txn.commit_transaction() + assert catalog.load_table(random_table_identifier).metadata.last_sequence_number == 3 + + 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"]}) From 7a0a0067aefbfbe027bc69505b1577b0fd1e5689 Mon Sep 17 00:00:00 2001 From: malon64 Date: Thu, 3 Dec 2026 10:57:27 +0000 Subject: [PATCH 5/6] Fix concurrency and metadata edge cases in replace table - Reject a snapshot whose sequence number is below last-sequence-number with CommitFailedException, so expired snapshots are covered and the replace cleans up its files. - Assert every branch the replace writes to, not only main, so a concurrent commit to it fails instead of being dropped. - Write dynamic_partition_overwrite data with the transaction metadata, so it uses the new spec, schema and location. - Reject replacing any partitioned v1 table, also when upgrading: Java keeps the current v1 partition fields, which is not supported yet, and the v2 path could assign duplicate partition field IDs. --- pyiceberg/table/__init__.py | 18 +++---- pyiceberg/table/update/__init__.py | 9 ++-- tests/catalog/test_catalog_behaviors.py | 64 ++++++++++++++++++++----- 3 files changed, 66 insertions(+), 25 deletions(-) diff --git a/pyiceberg/table/__init__.py b/pyiceberg/table/__init__.py index b3d002c7ef..db5396b774 100644 --- a/pyiceberg/table/__init__.py +++ b/pyiceberg/table/__init__.py @@ -670,7 +670,7 @@ def dynamic_partition_overwrite( append_snapshot_commit_uuid = uuid.uuid4() data_files: list[DataFile] = list( _dataframe_to_data_files( - table_metadata=self._table.metadata, write_uuid=append_snapshot_commit_uuid, df=df, io=self._table.io + table_metadata=self.table_metadata, write_uuid=append_snapshot_commit_uuid, df=df, io=self._table.io ) ) @@ -1403,9 +1403,10 @@ def __init__( 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") + if base.format_version == 1 and not (base.spec().is_unpartitioned() and partition_spec.is_unpartitioned()): + # TODO: support Java's v1 path, which keeps the current partition fields (as void transforms if dropped), + # also when upgrading to v2 + raise ValueError("Replacing a partitioned v1 table is not supported, upgrade it to format version 2 first") schema.check_format_version_compatibility(format_version) _check_properties_format_version_compatibility(properties, format_version) @@ -1478,8 +1479,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. + Each branch written in the transaction is also asserted, so a concurrent commit to it fails the replace + instead of being dropped from the branch. Returns: The table with the updates applied. @@ -1500,8 +1501,9 @@ 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),) + for branch in {p._target_branch for p in self._snapshot_producers if p._target_branch is not None}: + ref = base.refs.get(branch) + requirements += (AssertRefSnapshotId(ref=branch, snapshot_id=ref.snapshot_id if ref else None),) try: try: self._table._do_commit(updates=self._updates, requirements=requirements) # pylint: disable=W0212 diff --git a/pyiceberg/table/update/__init__.py b/pyiceberg/table/update/__init__.py index b652b81a80..7d2708003a 100644 --- a/pyiceberg/table/update/__init__.py +++ b/pyiceberg/table/update/__init__.py @@ -468,12 +468,13 @@ def _(update: AddSnapshotUpdate, base_metadata: TableMetadata, context: _TableMe elif ( base_metadata.format_version >= 2 and update.snapshot.sequence_number is not None - and any((s.sequence_number or 0) > update.snapshot.sequence_number for s in base_metadata.snapshots) + and update.snapshot.sequence_number < base_metadata.last_sequence_number ): - # Like Java's indexAndValidateSnapshots: last-sequence-number must not go below an existing snapshot's - raise ValueError( + # A snapshot without a parent (e.g. from a replace) was built on stale metadata, and the spec requires + # last-sequence-number to only increase + raise CommitFailedException( f"Cannot add snapshot with sequence number {update.snapshot.sequence_number} " - f"older than an existing snapshot's sequence number" + f"older than last sequence number {base_metadata.last_sequence_number}" ) elif base_metadata.format_version >= 3 and update.snapshot.first_row_id is None: raise ValueError("Cannot add snapshot without first row id") diff --git a/tests/catalog/test_catalog_behaviors.py b/tests/catalog/test_catalog_behaviors.py index f619f8b3cb..2cf7daadc5 100644 --- a/tests/catalog/test_catalog_behaviors.py +++ b/tests/catalog/test_catalog_behaviors.py @@ -44,6 +44,7 @@ from pyiceberg.partitioning import UNPARTITIONED_PARTITION_SPEC, PartitionField, PartitionSpec from pyiceberg.schema import Schema from pyiceberg.table import Table, TableProperties +from pyiceberg.table.refs import MAIN_BRANCH from pyiceberg.table.snapshots import Operation from pyiceberg.table.sorting import NullOrder, SortDirection, SortField, SortOrder from pyiceberg.table.update import AddSchemaUpdate, SetCurrentSchemaUpdate @@ -278,22 +279,25 @@ def test_replace_table_cleans_up_on_failed_commit(catalog: Catalog, random_table catalog.create_namespace(Catalog.namespace_from(random_table_identifier)) df = pa.table({"foo": ["a", "b"]}) table = catalog.create_table(random_table_identifier, df.schema) + table.append(df) + table.manage_snapshots().create_branch(table.metadata.current_snapshot_id, "audit").commit() # type: ignore - 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 commit to a branch written by the replace fails it, instead of being dropped from the branch + for branch in [MAIN_BRANCH, "audit"]: + txn = catalog.replace_table_transaction(random_table_identifier, df.schema) + txn.append(df, branch=branch) + manifest_list = txn.table_metadata.snapshot_by_name(branch).manifest_list # type: ignore - # 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() + table.append(df, branch=branch) + 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() + with pytest.raises(RuntimeError, match="cannot be reused"): + txn.commit_transaction() -def test_replace_table_fails_on_concurrent_commit_to_other_branch(catalog: Catalog, random_table_identifier: Identifier) -> None: +def test_replace_table_fails_when_sequence_number_advanced(catalog: Catalog, random_table_identifier: Identifier) -> None: catalog.create_namespace(Catalog.namespace_from(random_table_identifier)) df = pa.table({"foo": ["a"]}) table = catalog.create_table(random_table_identifier, df.schema) @@ -302,15 +306,49 @@ def test_replace_table_fails_on_concurrent_commit_to_other_branch(catalog: Catal txn = catalog.replace_table_transaction(random_table_identifier, df.schema) txn.append(df) + manifest_list = txn.table_metadata.snapshot_by_name(MAIN_BRANCH).manifest_list # type: ignore - # Two commits to another branch pass the main assertion, but the replace would make last-sequence-number go backwards + # Commits to a branch the replace does not write, then expired, still advanced last-sequence-number table.append(df, branch="audit") table.append(df, branch="audit") - with pytest.raises(ValueError, match="older than an existing snapshot's sequence number"): + audit_snapshot_ids = [s.snapshot_id for s in table.snapshots() if s.snapshot_id != table.metadata.current_snapshot_id] + table.manage_snapshots().remove_branch("audit").commit() + table.maintenance.expire_snapshots().by_ids(audit_snapshot_ids).commit() + + with pytest.raises(CommitFailedException, match="older than last sequence number"): txn.commit_transaction() + assert not table.io.new_input(manifest_list).exists() assert catalog.load_table(random_table_identifier).metadata.last_sequence_number == 3 +@pytest.mark.filterwarnings("ignore:Delete operation did not match any records") +def test_replace_table_dynamic_partition_overwrite_uses_new_spec(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) + table.append(df) + spec = PartitionSpec(PartitionField(source_id=1, field_id=1000, transform=IdentityTransform(), name="foo")) + + with catalog.replace_table_transaction(random_table_identifier, table.schema(), partition_spec=spec) as txn: + txn.dynamic_partition_overwrite(df) + + replaced = catalog.load_table(random_table_identifier) + assert {task.file.spec_id for task in replaced.scan().plan_files()} == {replaced.spec().spec_id} + assert replaced.scan().to_arrow().sort_by("foo") == df + + +def test_replace_partitioned_v1_table_is_rejected(catalog: Catalog, random_table_identifier: Identifier) -> None: + catalog.create_namespace(Catalog.namespace_from(random_table_identifier)) + schema = Schema(NestedField(1, "foo", StringType())) + spec = PartitionSpec(PartitionField(source_id=1, field_id=1000, transform=IdentityTransform(), name="foo")) + catalog.create_table(random_table_identifier, schema, partition_spec=spec, properties={"format-version": "1"}) + + # Also when upgrading: Java keeps the current v1 partition fields, which is not supported yet + for properties in [{}, {TableProperties.FORMAT_VERSION: "2"}]: + with pytest.raises(ValueError, match="upgrade it to format version 2 first"): + catalog.replace_table_transaction(random_table_identifier, schema, partition_spec=spec, properties=properties) + + 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"]}) From 29400f2e65b4a98cd219d85aded0bd961504cf27 Mon Sep 17 00:00:00 2001 From: malon64 Date: Fri, 4 Dec 2026 10:35:18 +0000 Subject: [PATCH 6/6] Allow partitioning unpartitioned v1 tables on replace - Only reject replacing a v1 table whose current spec is partitioned. An unpartitioned v1 table has no fields to keep, so it can become partitioned when upgraded to v2. Like Java, v1 tables only reuse the partition field IDs of their current spec. - Raise CommitFailedException when a snapshot with a parent has a stale sequence number, like Java's RetryableValidationException. Plain transactions now retry instead of failing, and a replace writing to a branch cleans up its files. --- pyiceberg/table/__init__.py | 13 ++++++++----- pyiceberg/table/update/__init__.py | 3 ++- tests/catalog/test_catalog_behaviors.py | 26 ++++++++++++++++++++----- tests/table/test_commit_retry.py | 20 +++++++++++++++++++ tests/table/test_init.py | 2 +- 5 files changed, 52 insertions(+), 12 deletions(-) diff --git a/pyiceberg/table/__init__.py b/pyiceberg/table/__init__.py index db5396b774..404ccfa5c5 100644 --- a/pyiceberg/table/__init__.py +++ b/pyiceberg/table/__init__.py @@ -1403,10 +1403,11 @@ def __init__( 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 base.format_version == 1 and not (base.spec().is_unpartitioned() and partition_spec.is_unpartitioned()): - # TODO: support Java's v1 path, which keeps the current partition fields (as void transforms if dropped), - # also when upgrading to v2 + if base.format_version == 1 and not base.spec().is_unpartitioned(): + # TODO: support Java's v1 path, which keeps the current partition fields (as void transforms if dropped) raise ValueError("Replacing a partitioned v1 table is not supported, upgrade it to format version 2 first") + if format_version == 1 and not partition_spec.is_unpartitioned(): + raise ValueError("Partitioning a v1 table in a replace is not supported, set format-version to 2") schema.check_format_version_compatibility(format_version) _check_properties_format_version_compatibility(properties, format_version) @@ -1419,8 +1420,10 @@ def __init__( 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) + # Reuse partition field IDs by (source, transform), new fields get IDs above last_partition_id. Like Java, a v1 + # table only reuses the IDs of its current spec, since its historical specs can share IDs + reused_specs = base.partition_specs if base.format_version > 1 else [base.spec()] + existing_fields = sorted((f for s in reused_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( diff --git a/pyiceberg/table/update/__init__.py b/pyiceberg/table/update/__init__.py index 7d2708003a..ba22d462dd 100644 --- a/pyiceberg/table/update/__init__.py +++ b/pyiceberg/table/update/__init__.py @@ -461,7 +461,8 @@ def _(update: AddSnapshotUpdate, base_metadata: TableMetadata, context: _TableMe and update.snapshot.sequence_number <= base_metadata.last_sequence_number and update.snapshot.parent_snapshot_id is not None ): - raise ValueError( + # Retryable, like Java's RetryableValidationException: the snapshot was built on stale metadata + raise CommitFailedException( f"Cannot add snapshot with sequence number {update.snapshot.sequence_number} " f"older than last sequence number {base_metadata.last_sequence_number}" ) diff --git a/tests/catalog/test_catalog_behaviors.py b/tests/catalog/test_catalog_behaviors.py index 2cf7daadc5..485518f4f0 100644 --- a/tests/catalog/test_catalog_behaviors.py +++ b/tests/catalog/test_catalog_behaviors.py @@ -280,15 +280,17 @@ def test_replace_table_cleans_up_on_failed_commit(catalog: Catalog, random_table df = pa.table({"foo": ["a", "b"]}) table = catalog.create_table(random_table_identifier, df.schema) table.append(df) - table.manage_snapshots().create_branch(table.metadata.current_snapshot_id, "audit").commit() # type: ignore + snapshot_id = table.metadata.current_snapshot_id + table.manage_snapshots().create_branch(snapshot_id, "audit").create_branch(snapshot_id, "other").commit() # type: ignore - # A concurrent commit to a branch written by the replace fails it, instead of being dropped from the branch - for branch in [MAIN_BRANCH, "audit"]: + # A concurrent commit to a branch written by the replace fails it, instead of being dropped from the branch. + # A concurrent commit to another branch makes the sequence number of a snapshot with a parent stale. + for branch, concurrent_branch in [(MAIN_BRANCH, MAIN_BRANCH), ("audit", "audit"), ("audit", "other")]: txn = catalog.replace_table_transaction(random_table_identifier, df.schema) txn.append(df, branch=branch) manifest_list = txn.table_metadata.snapshot_by_name(branch).manifest_list # type: ignore - table.append(df, branch=branch) + table.append(df, branch=concurrent_branch) with pytest.raises(CommitFailedException): txn.commit_transaction() assert not table.io.new_input(manifest_list).exists() @@ -337,7 +339,7 @@ def test_replace_table_dynamic_partition_overwrite_uses_new_spec(catalog: Catalo assert replaced.scan().to_arrow().sort_by("foo") == df -def test_replace_partitioned_v1_table_is_rejected(catalog: Catalog, random_table_identifier: Identifier) -> None: +def test_replace_v1_table_partitioning(catalog: Catalog, random_table_identifier: Identifier) -> None: catalog.create_namespace(Catalog.namespace_from(random_table_identifier)) schema = Schema(NestedField(1, "foo", StringType())) spec = PartitionSpec(PartitionField(source_id=1, field_id=1000, transform=IdentityTransform(), name="foo")) @@ -348,6 +350,20 @@ def test_replace_partitioned_v1_table_is_rejected(catalog: Catalog, random_table with pytest.raises(ValueError, match="upgrade it to format version 2 first"): catalog.replace_table_transaction(random_table_identifier, schema, partition_spec=spec, properties=properties) + # An unpartitioned v1 table has nothing to keep, so it can become partitioned when upgraded to v2 + unpartitioned_identifier = (*random_table_identifier[:-1], f"{random_table_identifier[-1]}_unpartitioned") + catalog.create_table(unpartitioned_identifier, schema, properties={"format-version": "1"}) + with pytest.raises(ValueError, match="set format-version to 2"): + catalog.replace_table_transaction(unpartitioned_identifier, schema, partition_spec=spec) + with catalog.replace_table_transaction( + unpartitioned_identifier, schema, partition_spec=spec, properties={TableProperties.FORMAT_VERSION: "2"} + ) as txn: + txn.append(pa.table({"foo": ["a"]})) + replaced = catalog.load_table(unpartitioned_identifier) + assert replaced.format_version == 2 + assert [f.field_id for f in replaced.spec().fields] == [1000] + assert replaced.scan().to_arrow().num_rows == 1 + def test_replace_table_writes_to_new_location(catalog: Catalog, random_table_identifier: Identifier) -> None: catalog.create_namespace(Catalog.namespace_from(random_table_identifier)) diff --git a/tests/table/test_commit_retry.py b/tests/table/test_commit_retry.py index 22f743c1c8..8a3cc463c8 100644 --- a/tests/table/test_commit_retry.py +++ b/tests/table/test_commit_retry.py @@ -121,6 +121,26 @@ def test_concurrent_add_files_retry_rechecks_duplicate_paths(catalog: Catalog, t assert refreshed.scan().to_arrow()["x"].to_pylist() == [1, 2] +def test_branch_append_retries_when_another_branch_advances(catalog: Catalog) -> None: + import pyarrow as pa + + catalog.create_namespace("default") + df = pa.table({"x": pa.array([1], pa.int64())}) + tbl = catalog.create_table("default.branch_retry", schema=df.schema) + tbl.append(df) + snapshot_id = tbl.metadata.current_snapshot_id + tbl.manage_snapshots().create_branch(snapshot_id, "audit").create_branch(snapshot_id, "other").commit() # type: ignore + + # The concurrent commit makes the staged sequence number stale, which is retried like in Java + with tbl.transaction() as txn: + txn.append(df, branch="audit") + catalog.load_table("default.branch_retry").append(df, branch="other") + + refreshed = catalog.load_table("default.branch_retry") + assert refreshed.metadata.last_sequence_number == 3 + assert len(refreshed.scan(snapshot_id=refreshed.snapshot_by_name("audit").snapshot_id).to_arrow()) == 2 # type: ignore + + def test_no_retry_without_snapshot_producers(catalog: Catalog) -> None: """Verify that a transaction with no snapshot producers has an empty producer list.""" catalog.create_namespace("default") diff --git a/tests/table/test_init.py b/tests/table/test_init.py index 547ca94fc9..cc1ffd2721 100644 --- a/tests/table/test_init.py +++ b/tests/table/test_init.py @@ -2460,7 +2460,7 @@ def test_add_snapshot_update_fails_with_stale_sequence_number(table: Table) -> N ) with pytest.raises( - ValueError, + CommitFailedException, match=( f"Cannot add snapshot with sequence number {last_sequence_number} " f"older than last sequence number {last_sequence_number}"