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
100 changes: 100 additions & 0 deletions pyiceberg/manifest.py
Original file line number Diff line number Diff line change
Expand Up @@ -901,6 +901,10 @@ def key_metadata(self) -> bytes | None:
def first_row_id(self) -> int | None:
return self._data[15]

@first_row_id.setter
def first_row_id(self, value: int | None) -> None:
self._data[15] = value

def has_added_files(self) -> bool:
return self.added_files_count is None or self.added_files_count > 0

Expand Down Expand Up @@ -1360,18 +1364,56 @@ def prepare_entry(self, entry: ManifestEntry) -> ManifestEntry:
return entry


class ManifestWriterV3(ManifestWriterV2):
"""Writes V3 manifest files.

An optional `first_row_id` can be provided when rewriting a manifest whose
`first_row_id` is already known; it is carried into the produced manifest file
so the manifest list writer preserves it instead of assigning a new one. For
new manifests it is None and assigned when writing the manifest list.
"""

_first_row_id: int | None

def __init__(
self,
spec: PartitionSpec,
schema: Schema,
output_file: OutputFile,
snapshot_id: int,
avro_compression: AvroCompressionCodec,
first_row_id: int | None = None,
):
super().__init__(spec, schema, output_file, snapshot_id, avro_compression)
self._first_row_id = first_row_id

@property
def version(self) -> TableVersion:
return 3

def to_manifest_file(self) -> ManifestFile:

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.

super().to_manifest_file() is already V3 layout so I think this can just be manifest_file.first_row_id = self._first_row_id?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes, done: to_manifest_file now just sets manifest_file.first_row_id = self._first_row_id.

manifest_file = super().to_manifest_file()
manifest_file.first_row_id = self._first_row_id
return manifest_file


def write_manifest(
format_version: TableVersion,
spec: PartitionSpec,
schema: Schema,
output_file: OutputFile,
snapshot_id: int,
avro_compression: AvroCompressionCodec,
first_row_id: int | None = None,
) -> ManifestWriter:
if first_row_id is not None and format_version < 3:
raise ValueError(f"First-row-id is only supported for V3 tables: {format_version}")
if format_version == 1:
return ManifestWriterV1(spec, schema, output_file, snapshot_id, avro_compression)
elif format_version == 2:
return ManifestWriterV2(spec, schema, output_file, snapshot_id, avro_compression)
elif format_version == 3:
return ManifestWriterV3(spec, schema, output_file, snapshot_id, avro_compression, first_row_id)
else:
raise ValueError(f"Cannot write manifest for table version: {format_version}")

Expand Down Expand Up @@ -1495,19 +1537,77 @@ def prepare_manifest(self, manifest_file: ManifestFile) -> ManifestFile:
return wrapped_manifest_file


class ManifestListWriterV3(ManifestListWriterV2):
"""Writes V3 manifest lists, assigning `first_row_id` to data manifests.

Follows the spec's First Row ID Assignment: existing `first_row_id` values of data
manifests are preserved, delete manifests never carry one, and data manifests without a
`first_row_id` are assigned a running value starting at the snapshot's `first-row-id`,
advanced by each assigned manifest's existing and added row counts.
"""

_next_row_id: int

def __init__(
self,
output_file: OutputFile,
snapshot_id: int,
parent_snapshot_id: int | None,
sequence_number: int,
compression: AvroCompressionCodec,
first_row_id: int,
):
super().__init__(output_file, snapshot_id, parent_snapshot_id, sequence_number, compression)
self._format_version = 3
self._meta = {
**self._meta,
"first-row-id": str(first_row_id),
"format-version": "3",
}
self._next_row_id = first_row_id

@property
def next_row_id(self) -> int:
"""The row ID after the last assigned one; the table's `next-row-id` after this snapshot."""
return self._next_row_id

def prepare_manifest(self, manifest_file: ManifestFile) -> ManifestFile:
# Rebind to a fresh record so that assigning `first_row_id` never mutates the caller's manifest file
wrapped_manifest_file = super().prepare_manifest(ManifestFile(*manifest_file._data))

if wrapped_manifest_file.content != ManifestContent.DATA:
wrapped_manifest_file.first_row_id = None
elif wrapped_manifest_file.first_row_id is None:
if wrapped_manifest_file.existing_rows_count is None or wrapped_manifest_file.added_rows_count is None:
# assigning first-row-id with unknown row counts would overlap row ID ranges
raise ValueError(
f"Cannot assign first-row-id to manifest with unknown row counts: {wrapped_manifest_file.manifest_path}"
)
wrapped_manifest_file.first_row_id = self._next_row_id
self._next_row_id += wrapped_manifest_file.existing_rows_count + wrapped_manifest_file.added_rows_count
return wrapped_manifest_file


def write_manifest_list(
format_version: TableVersion,
output_file: OutputFile,
snapshot_id: int,
parent_snapshot_id: int | None,
sequence_number: int | None,
avro_compression: AvroCompressionCodec,
first_row_id: int | None = None,
) -> ManifestListWriter:
if format_version == 1:
return ManifestListWriterV1(output_file, snapshot_id, parent_snapshot_id, avro_compression)
elif format_version == 2:
if sequence_number is None:
raise ValueError(f"Sequence-number is required for V2 tables: {sequence_number}")
return ManifestListWriterV2(output_file, snapshot_id, parent_snapshot_id, sequence_number, avro_compression)
elif format_version == 3:
if sequence_number is None:
raise ValueError(f"Sequence-number is required for V3 tables: {sequence_number}")
if first_row_id is None:
raise ValueError("First-row-id is required for V3 tables")
return ManifestListWriterV3(output_file, snapshot_id, parent_snapshot_id, sequence_number, avro_compression, first_row_id)
else:
raise ValueError(f"Cannot write manifest list for table version: {format_version}")
11 changes: 6 additions & 5 deletions pyiceberg/table/update/snapshot.py
Original file line number Diff line number Diff line change
Expand Up @@ -348,21 +348,22 @@ def _commit(self) -> UpdatesAndRequirements:
manifest_list_file_path = location_provider.new_metadata_location(file_name)
self._written_manifest_lists.append(manifest_list_file_path)

first_row_id: int | None = None

if self._transaction.table_metadata.format_version >= 3:
first_row_id = self._transaction.table_metadata.next_row_id

with write_manifest_list(
format_version=self._transaction.table_metadata.format_version,
output_file=self._io.new_output(manifest_list_file_path),
snapshot_id=self._snapshot_id,
parent_snapshot_id=self._parent_snapshot_id,
sequence_number=next_sequence_number,
avro_compression=self._compression,
first_row_id=first_row_id,

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.

I think we also need added_rows on the snapshot here, otherwise AddSnapshotUpdate fails on main with Cannot add snapshot without added rows (Java rejects it too). Might need to check that I'm reading this right.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

You're reading it right: since #3972, AddSnapshotUpdate rejects a V3 snapshot without added_rows, and _commit never sets it. That is already the case on main, so this PR doesn't change it. I'd keep this PR to the writers and leave the fix to #4102 (closes #3621). It is stacked on this PR and sets added_rows to writer.next_row_id - first_row_id, as Java's SnapshotProducer does.

) as writer:
writer.add_manifests(new_manifests)

first_row_id: int | None = None

if self._transaction.table_metadata.format_version >= 3:
first_row_id = self._transaction.table_metadata.next_row_id

snapshot = Snapshot(
snapshot_id=self._snapshot_id,
parent_snapshot_id=self._parent_snapshot_id,
Expand Down
37 changes: 37 additions & 0 deletions tests/table/test_snapshots.py
Original file line number Diff line number Diff line change
Expand Up @@ -844,3 +844,40 @@ def test_overwrite_rejects_explicit_delete_without_parent_snapshot(
with empty.transaction() as tx:
with tx.update_snapshot().overwrite() as overwrite:
overwrite.delete_data_file(stale_file)


def test_manifest_list_receives_first_row_id_for_v3(table_v3: Table) -> None:

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.

nit: would be nice to do a real _commit() here rather than mocking, it would have caught the missing added_rows too.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed. A real _commit() on a V3 table fails until added_rows is set, though, so here it could only assert the failure. #4102 sets added_rows and adds end-to-end commits against the REST fixture, so I'd let the real-commit test land there and keep this one scoped to what the producer passes to the writer.

"""The V3 manifest list writer requires first-row-id, so the producer has to supply it."""
from unittest import mock

from pyiceberg.table.update.snapshot import _FastAppendFiles

txn = table_v3.transaction()
append = _FastAppendFiles(operation=Operation.APPEND, transaction=txn, io=table_v3.io)

with (
mock.patch("pyiceberg.table.update.snapshot.write_manifest_list") as writer,
mock.patch.object(_FastAppendFiles, "_manifests", return_value=[]),
):
append._commit()

assert writer.call_args.kwargs["format_version"] == 3
assert writer.call_args.kwargs["first_row_id"] == table_v3.metadata.next_row_id


def test_manifest_list_has_no_first_row_id_for_v2(table_v2: Table) -> None:
from unittest import mock

from pyiceberg.table.update.snapshot import _FastAppendFiles

txn = table_v2.transaction()
append = _FastAppendFiles(operation=Operation.APPEND, transaction=txn, io=table_v2.io)

with (
mock.patch("pyiceberg.table.update.snapshot.write_manifest_list") as writer,
mock.patch.object(_FastAppendFiles, "_manifests", return_value=[]),
):
append._commit()

assert writer.call_args.kwargs["format_version"] == 2
assert writer.call_args.kwargs["first_row_id"] is None
Loading
Loading