Skip to content

Add atomic create or replace table - #4496

Open
malon64 wants to merge 6 commits into
apache:mainfrom
malon64:feat/create-or-replace-table
Open

malon64 wants to merge 6 commits into
apache:mainfrom
malon64:feat/create-or-replace-table

Conversation

@malon64

@malon64 malon64 commented Nov 25, 2026 •

Copy link
Copy Markdown

Closes #4485

Rationale for this change

Engines like Polars need to run CREATE OR REPLACE TABLE ... AS SELECT (e.g. for dbt) in a single commit, so readers never see an empty or half-written table.

This adds two methods to Catalog:

  • replace_table_transaction: replaces an existing table, raises NoSuchTableError if it doesn't exist
  • create_or_replace_table_transaction: creates the table, or replaces it if it exists

The replacement follows 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), identical schemas/specs/sort orders are reused, and properties are merged.

Differences from Java

  • Replacing a partitioned v1 table is rejected, also when upgrading to v2. Java keeps the current v1 partition fields (as void transforms when dropped), which isn't implemented yet; upgrade the table to v2 first.
  • Last assigned field and partition IDs are always asserted, and the current schema/spec/sort order is asserted when a new one is added, since PyIceberg catalogs keep the IDs assigned by the client.
  • Every branch the replace writes to is asserted (Java's forReplaceTable asserts none). Without it, a concurrent commit to that branch was dropped on v1, or rejected without cleaning up the written files on v2.
  • No retry on conflict: a concurrent change fails the replace with CommitFailedException and the written files are cleaned up.

Related fixes

  • AddSnapshotUpdate now rejects a snapshot whose sequence number is below last-sequence-number, with CommitFailedException. A snapshot without a parent built on stale metadata could make it go backwards. Java only checks retained snapshots; the spec says it must only increase. This touches shared metadata code, happy to split it out.
  • The snapshot producer builds its location provider from the transaction metadata, so a new location or write.metadata.path also applies to manifests.
  • dynamic_partition_overwrite writes with the transaction metadata instead of the committed one (pre-existing bug, visible when replacing the spec).

Follow-up: a table dropped during the commit reports CommitStateUnknownException instead of failing cleanly. Plain transactions behave the same, so I'll fix it separately.

Are these changes tested?

Yes, in tests/catalog/test_catalog_behaviors.py (memory and SQL catalogs) and tests/test_schema.py: create or replace, ID reuse, concurrent schema/sort order/branch commits, cleanup on failure, sequence numbers with snapshot expiration, new location, dynamic_partition_overwrite, format version checks. REST and Spark integration suites weren't run locally.

Are there any user-facing changes?

Yes: two new Catalog methods, documented in a new "Create or replace a table" section in mkdocs/docs/api.md.

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 apache#4485
@malon64
malon64 force-pushed the feat/create-or-replace-table branch from 7beaacf to f1d881c Compare November 25, 2026 23:06
@korsakowii

Copy link
Copy Markdown

I have some additional validation results for f1d881c using SQLite and the Apache REST fixture with local storage.

  • Aborting after writing and reading back two new Parquet files left the original table unchanged.
  • A rejected metadata pointer update in SQLite and an HTTP 409 following a concurrent schema change in REST preserved the last committed state.
  • Successful replacement published the new data while preserving the table UUID and access to historical snapshots.

All six checks passed across both catalogs.

Comment thread pyiceberg/catalog/__init__.py Resolved
Comment thread pyiceberg/table/__init__.py Resolved
Comment thread pyiceberg/table/__init__.py Resolved
Comment thread pyiceberg/table/__init__.py Resolved
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.
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.
@malon64

malon64 commented Nov 30, 2026

Copy link
Copy Markdown
Author

Anyone to approve this PR ? It is done now @oresttokovenko @korsakowii

@korsakowii

Copy link
Copy Markdown

Following up on my earlier validation, I tested the new snapshot guard on 8cb0db0e.

Concurrent appends to main work as expected, but I found an issue with writes to another branch.

On SQLite, two appends to an audit branch advanced the table sequence to 3 without changing main. The stale replacement then committed and lowered last-sequence-number back to 2.

The Java REST fixture rejected the same commit with HTTP 400.

Since sequence numbers are table-wide and monotonically increasing, should we also guard against sequence advancement on other branches?

Happy to share a reproducer.

@malon64

malon64 commented Dec 2, 2026 •

Copy link
Copy Markdown
Author

Thanks for catching this. Java rejects it because it checks that no snapshot has a sequence number above last-sequence-number when it builds the metadata (indexAndValidateSnapshots). I ported that check to the AddSnapshot validation, so commits on other branches are covered now, and added your scenario as a test. The main assertion stays so the common case still fails with a clean CommitFailedException. Since this touches the shared metadata code, happy to split it into its own PR if that's preferred.

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.
@korsakowii

Copy link
Copy Markdown

Thanks for the fix! I retested fc49119. The original scenario now passes, but two issues remain on SQLite:

  • After snapshot expiration, checking only retained snapshots still allows last-sequence-number to decrease from 3 to 2.
  • The new ValueError bypasses the existing CommitFailedException cleanup path, leaving staged manifests behind.

Could we check against the table’s last-sequence-number directly and handle cleanup for definitive commit failures?

- 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.
@malon64

malon64 commented Dec 3, 2026

Copy link
Copy Markdown
Author

Thanks for the retest. Both points were right: the check now compares against last-sequence-number and raises CommitFailedException, so expired snapshots are covered and the written files get cleaned up.

I also did a full pass on the PR to avoid more back and forth, and fixed a few more things:
• the replace now checks every branch it writes to, not just main;
• dynamic_partition_overwrite inside the transaction now uses the new spec/schema/location (it read the committed metadata, which predates this PR);
• a partitioned v1 table now has to be upgraded before a replace, since Java's v1 path keeps the old partition fields and that wasn't implemented.

Tests added for each. A dropped table during the commit still reports "commit state unknown"; that also affects plain transactions, so I'll do it in a follow-up as it is an existing behaviour.

@korsakowii

Copy link
Copy Markdown

Thanks for the fixes! Two follow-up observations on 7a0a006:

  • Sequence reuse: Local SQLite testing produced [1, 2, 2, 3] during a multi-branch replacement. Java intentionally allows parentless snapshots to reuse sequence numbers (#8390). Does the same rationale hold for multi-branch replacement?
  • Compatibility (lower priority): Replacing an unpartitioned v1 table with a partitioned v2 table now fails. Upgrading first still works. Was this restriction intentional?

Ref-conflict rejection, associated cleanup, and dynamic overwrite checks passed. REST/Java was not retested.

- 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.
@malon64

malon64 commented Dec 4, 2026

Copy link
Copy Markdown
Author

Thanks again for testing @korsakowii, fixed in 29400f2.

  1. The sequence number reuse is intended and matches Java. It only happens for the snapshot without a parent, i.e. the new main history the replace starts. As discussed in Fix REST catalogs behavior with v2 tables iceberg#8390 (fixed by Core: Fix REST catalog tests with default v2 tables iceberg#8469), that history has no existing files, so nothing in it is ordered against the other branch's snapshot with the same number. last-sequence-number still never goes down.

  2. Not intended, I made the check too broad. An unpartitioned v1 table has nothing to carry forward, so it can become partitioned again when upgraded to v2. For v1 tables, partition IDs are only reused from the current spec, like Java's reassignPartitionIds, which keeps the duplicate ID fix. Staying on v1 with a partitioned spec is still rejected.

While checking I found one more: the existing sequence check for snapshots with a parent raised ValueError, so a replace writing to a non-main branch left files behind when another branch moved, and plain transactions failed instead of retrying. It now raises CommitFailedException, which is what Java does (RetryableValidationException in TableMetadata.Builder.addSnapshot). This changes plain transactions too, happy to split it into its own PR if preferred.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature: Revive atomic REPLACE TABLE support in PyIceberg

3 participants