Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 68 additions & 3 deletions pyiceberg/table/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,7 @@ def __init__(self, table: Table, autocommit: bool = False):
self._updates = ()
self._requirements = ()
self._snapshot_producers: list[_SnapshotProducer[Any]] = []
self._known_snapshot_ids: set[int] = set()
self._failed = False

@property
Expand Down Expand Up @@ -1201,6 +1202,7 @@ def commit_transaction(self) -> Table:
try:
try:
for attempt in range(num_retries + 1):
self._known_snapshot_ids = {snapshot.snapshot_id for snapshot in self._table.metadata.snapshots}
try:
self._table._do_commit( # pylint: disable=W0212
updates=self._updates,
Expand Down Expand Up @@ -1279,9 +1281,11 @@ def _attempt_landed(self) -> bool:
"""Refresh the table and return whether a snapshot added by this transaction is present.

Raises:
CommitStateUnknownException: If the table cannot be refreshed, the outcome is unknown and
the files written for the attempt must not be deleted.
CommitStateUnknownException: If the table, a newly added snapshot's manifest list, or a candidate
rewritten manifest cannot be read, the outcome is unknown and the files written for the attempt
must not be deleted.
"""
known_snapshot_ids = self._known_snapshot_ids
try:
self._table.refresh()
except Exception as e:
Expand All @@ -1292,7 +1296,68 @@ def _attempt_landed(self) -> bool:
# A commit adds all of its snapshots or none, so finding one is enough. Another writer may have
# expired the others, since no ref points at a snapshot once another is committed on top of it.
added_snapshot_ids = {update.snapshot.snapshot_id for update in self._updates if isinstance(update, AddSnapshotUpdate)}
return any(self._table.metadata.snapshot_by_id(snapshot_id) is not None for snapshot_id in added_snapshot_ids)
if any(self._table.metadata.snapshot_by_id(snapshot_id) is not None for snapshot_id in added_snapshot_ids):
return True

# Another writer may have committed on top and expired all of the attempt's snapshots, while still
# referencing the manifests written for the attempt or rewriting their live entries into new manifests.
written_manifests = {path for producer in self._snapshot_producers for path in producer._written_manifests}
if not written_manifests or not added_snapshot_ids:
return False

read_error: Exception | None = None
new_snapshot_manifests: list[list[ManifestFile]] = []
for snapshot in reversed(self._table.metadata.snapshots):
if snapshot.snapshot_id in known_snapshot_ids:
continue
try:
manifests = snapshot.manifests(self._table.io, self._table.encryption_manager)
except Exception as e:
if read_error is None:
read_error = e
continue
if any(manifest.manifest_path in written_manifests for manifest in manifests):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the commit on top rewrites this manifest, its path is gone and a retry commits the rows again, as on main: with manifest merging on (commit.manifest-merge.enabled=true, commit.manifest.min-count-to-merge=2) the #4534 repro with one retry ends with [1, 1, 9], and delete("x == 1") on top of an identity-partitioned [1, 2] append gives [1, 2, 2]. The rewritten entries keep the attempt's snapshot id, so also matching entry.snapshot_id in manifests added since the refresh fixed both in a scratch copy (tests/table passes). An overwrite of all its rows still replays, so a follow-up issue may be the simpler route.

return True
new_snapshot_manifests.append(manifests)

if new_snapshot_manifests:
known_manifest_paths: set[str] = set()
for snapshot in self._table.metadata.snapshots:
if snapshot.snapshot_id not in known_snapshot_ids:
continue
try:
known_manifest_paths.update(
manifest.manifest_path for manifest in snapshot.manifests(self._table.io, self._table.encryption_manager)
)
except Exception:
continue

checked_manifest_paths: set[str] = set()
for manifests in new_snapshot_manifests:
for manifest in manifests:
if (
manifest.manifest_path in known_manifest_paths
or manifest.manifest_path in checked_manifest_paths
or manifest.added_snapshot_id in known_snapshot_ids
or not manifest.has_existing_files()
):
continue
checked_manifest_paths.add(manifest.manifest_path)
try:
entries = manifest.fetch_manifest_entry(self._table.io, discard_deleted=True)
except Exception as e:
if read_error is None:
read_error = e
continue
if any(entry.snapshot_id in added_snapshot_ids for entry in entries):
return True

if read_error is not None:
raise CommitStateUnknownException(
f"Commit failed and refreshed snapshot metadata could not be read to check whether it landed: {read_error}"
) from read_error

return False

def _cleanup_uncommitted_manifests(self) -> None:
"""Clean up manifests from failed retry attempts after a successful commit."""
Expand Down
220 changes: 220 additions & 0 deletions tests/table/test_commit_retry.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,11 @@

from pyiceberg.catalog import Catalog
from pyiceberg.exceptions import CommitFailedException, CommitStateUnknownException, ValidationException
from pyiceberg.partitioning import PartitionField, PartitionSpec
from pyiceberg.schema import Schema
from pyiceberg.table import Table, TableProperties, Transaction
from pyiceberg.table.snapshots import IsolationLevel, Operation
from pyiceberg.transforms import IdentityTransform
from pyiceberg.typedef import Record
from pyiceberg.types import DoubleType, LongType, NestedField, StringType

Expand Down Expand Up @@ -1756,6 +1758,224 @@ def append_on_top_and_expire_last_snapshot() -> None:
assert sorted(catalog.load_table(identifier).scan().to_arrow()["x"].to_pylist()) == [1, 2, 9]


def test_lost_response_after_another_writer_expires_all_added_snapshots_keeps_the_landed_commit(catalog: Catalog) -> None:
"""A landed commit is detected through its manifests even when all of its snapshots were expired."""
import pyarrow as pa

catalog.create_namespace("default")
identifier = "default.lost_response_all_snapshots_expired"
table = catalog.create_table(identifier, schema=_test_schema(), properties={TableProperties.COMMIT_NUM_RETRIES: "0"})

def append_on_top_and_expire() -> None:
other = catalog.load_table(identifier)
other.append(pa.table({"x": [9]}))
other.maintenance.expire_snapshots().by_id(other.snapshots()[0].snapshot_id).commit()

with _commit_outcomes(catalog, "lost", after_lost=append_on_top_and_expire):
table.append(pa.table({"x": [1]}))

assert sorted(catalog.load_table(identifier).scan().to_arrow()["x"].to_pylist()) == [1, 9]


def test_lost_response_after_another_writer_expires_all_added_snapshots_is_not_committed_twice(catalog: Catalog) -> None:
"""With retries left, a landed commit whose snapshots were all expired is not committed again."""
import pyarrow as pa

catalog.create_namespace("default")
identifier = "default.lost_response_all_snapshots_expired_with_retries"
table = catalog.create_table(
identifier,
schema=_test_schema(),
properties={
TableProperties.COMMIT_NUM_RETRIES: "1",
TableProperties.COMMIT_MIN_RETRY_WAIT_MS: "1",
TableProperties.COMMIT_MAX_RETRY_WAIT_MS: "2",
},
)

def append_on_top_and_expire() -> None:
other = catalog.load_table(identifier)
other.append(pa.table({"x": [9]}))
other.maintenance.expire_snapshots().by_id(other.snapshots()[0].snapshot_id).commit()

with _commit_outcomes(catalog, "lost", after_lost=append_on_top_and_expire):
table.append(pa.table({"x": [1]}))

assert sorted(catalog.load_table(identifier).scan().to_arrow()["x"].to_pylist()) == [1, 9]


def test_lost_response_on_retry_after_expiring_all_added_snapshots_cleans_only_failed_attempt(catalog: Catalog) -> None:
"""A retried commit that lands and has its snapshot expired keeps its manifest while cleaning earlier failed attempts."""
import pyarrow as pa

catalog.create_namespace("default")
identifier = "default.lost_response_retry_all_snapshots_expired"
table = catalog.create_table(
identifier,
schema=_test_schema(),
properties={
TableProperties.COMMIT_NUM_RETRIES: "2",
TableProperties.COMMIT_MIN_RETRY_WAIT_MS: "1",
TableProperties.COMMIT_MAX_RETRY_WAIT_MS: "2",
},
)

txn = table.transaction()
txn.append(pa.table({"x": [1]}))
first_attempt_manifests = list(txn._snapshot_producers[0]._written_manifests)
assert len(first_attempt_manifests) == 1

def append_on_top_and_expire() -> None:
other = catalog.load_table(identifier)
other.append(pa.table({"x": [9]}))
other.maintenance.expire_snapshots().by_id(other.snapshots()[0].snapshot_id).commit()

with _commit_outcomes(catalog, "conflict", "lost", after_lost=append_on_top_and_expire):
txn.commit_transaction()

assert not table.io.new_input(first_attempt_manifests[0]).exists()
assert sorted(catalog.load_table(identifier).scan().to_arrow()["x"].to_pylist()) == [1, 9]


def test_unreadable_manifest_list_when_checking_landed_commit_raises_commit_state_unknown(catalog: Catalog) -> None:
"""When a refreshed snapshot's manifest list cannot be read, the outcome is unknown and no file is deleted."""
import pyarrow as pa

catalog.create_namespace("default")
identifier = "default.unknown_commit_outcome_manifest_list"
table = catalog.create_table(identifier, schema=_test_schema(), properties={TableProperties.COMMIT_NUM_RETRIES: "0"})

txn = table.transaction()
txn.append(pa.table({"x": [1]}))
written_manifest = txn._snapshot_producers[0]._written_manifests[0]

other = catalog.load_table(identifier)
other.append(pa.table({"x": [9]}))
other_snapshot = other.current_snapshot()
assert other_snapshot is not None
table.io.delete(other_snapshot.manifest_list)

with pytest.raises(CommitStateUnknownException):
txn.commit_transaction()

assert table.io.new_input(written_manifest).exists()


def test_lost_response_when_shared_table_refreshes_after_expiring_added_snapshots(catalog: Catalog) -> None:
"""Refreshing the shared Table before _attempt_landed runs must not hide snapshots added on top."""
import pyarrow as pa

catalog.create_namespace("default")
for num_retries in (0, 1):
identifier = f"default.lost_response_shared_refresh_{num_retries}"
table = catalog.create_table(
identifier,
schema=_test_schema(),
properties={
TableProperties.COMMIT_NUM_RETRIES: str(num_retries),
TableProperties.COMMIT_MIN_RETRY_WAIT_MS: "1",
TableProperties.COMMIT_MAX_RETRY_WAIT_MS: "2",
},
)

def append_on_top_expire_and_refresh(shared_table: Table = table, tbl_id: str = identifier) -> None:
other = catalog.load_table(tbl_id)
other.append(pa.table({"x": [9]}))
other.maintenance.expire_snapshots().by_id(other.snapshots()[0].snapshot_id).commit()
shared_table.refresh()

with _commit_outcomes(catalog, "lost", after_lost=append_on_top_expire_and_refresh):
table.append(pa.table({"x": [1]}))

assert sorted(catalog.load_table(identifier).scan().to_arrow()["x"].to_pylist()) == [1, 9]


def test_lost_response_when_manifest_is_rewritten_and_snapshot_expired_is_not_committed_twice(catalog: Catalog) -> None:
"""A landed commit is detected via entry.snapshot_id when a commit on top merges or rewrites its manifest."""
import pyarrow as pa

catalog.create_namespace("default")
for num_retries in (0, 1):
merge_id = f"default.lost_response_merged_manifest_{num_retries}"
merge_table = catalog.create_table(
merge_id,
schema=_test_schema(),
properties={
TableProperties.COMMIT_NUM_RETRIES: str(num_retries),
TableProperties.COMMIT_MIN_RETRY_WAIT_MS: "1",
TableProperties.COMMIT_MAX_RETRY_WAIT_MS: "2",
TableProperties.MANIFEST_MERGE_ENABLED: "true",
TableProperties.MANIFEST_MIN_MERGE_COUNT: "2",
},
)

def merge_on_top_and_expire(tbl_id: str = merge_id) -> None:
other = catalog.load_table(tbl_id)
other.append(pa.table({"x": [9]}))
other.maintenance.expire_snapshots().by_id(other.snapshots()[0].snapshot_id).commit()

with _commit_outcomes(catalog, "lost", after_lost=merge_on_top_and_expire):
merge_table.append(pa.table({"x": [1]}))

assert sorted(catalog.load_table(merge_id).scan().to_arrow()["x"].to_pylist()) == [1, 9]

delete_id = f"default.lost_response_delete_rewrite_{num_retries}"
delete_table = catalog.create_table(
delete_id,
schema=_test_schema(),
partition_spec=PartitionSpec(PartitionField(source_id=1, field_id=1000, transform=IdentityTransform(), name="x")),
properties={
TableProperties.COMMIT_NUM_RETRIES: str(num_retries),
TableProperties.COMMIT_MIN_RETRY_WAIT_MS: "1",
TableProperties.COMMIT_MAX_RETRY_WAIT_MS: "2",
},
)

def delete_on_top_and_expire(tbl_id: str = delete_id) -> None:
other = catalog.load_table(tbl_id)
other.delete("x == 1")
other.maintenance.expire_snapshots().by_id(other.snapshots()[0].snapshot_id).commit()

with _commit_outcomes(catalog, "lost", after_lost=delete_on_top_and_expire):
delete_table.append(pa.table({"x": [1, 2]}))

assert sorted(catalog.load_table(delete_id).scan().to_arrow()["x"].to_pylist()) == [2]


def test_unreadable_rewritten_manifest_when_checking_landed_commit_raises_commit_state_unknown(catalog: Catalog) -> None:
"""When a candidate rewritten manifest cannot be read, CommitStateUnknownException preserves written files."""
import pyarrow as pa

catalog.create_namespace("default")
identifier = "default.unknown_commit_outcome_rewritten_manifest"
table = catalog.create_table(
identifier,
schema=_test_schema(),
properties={
TableProperties.COMMIT_NUM_RETRIES: "0",
TableProperties.MANIFEST_MERGE_ENABLED: "true",
TableProperties.MANIFEST_MIN_MERGE_COUNT: "2",
},
)

other = catalog.load_table(identifier)
other.append(pa.table({"x": [8]}))
other.append(pa.table({"x": [9]}))
other_snapshot = other.current_snapshot()
assert other_snapshot is not None
merged_manifest = other_snapshot.manifests(other.io)[0]
table.io.delete(merged_manifest.manifest_path)

txn = table.transaction()
txn.append(pa.table({"x": [1]}))
written_manifest = txn._snapshot_producers[0]._written_manifests[0]

with pytest.raises(CommitStateUnknownException):
txn.commit_transaction()

assert table.io.new_input(written_manifest).exists()


def test_unreadable_commit_outcome_raises_commit_state_unknown(catalog: Catalog) -> None:
"""When the table cannot be refreshed, the outcome is unknown and no file is deleted."""
catalog.create_namespace("default")
Expand Down
Loading