diff --git a/pyiceberg/manifest.py b/pyiceberg/manifest.py index d497d6fb19..47a36f0bb2 100644 --- a/pyiceberg/manifest.py +++ b/pyiceberg/manifest.py @@ -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 @@ -1360,6 +1364,39 @@ 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: + 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, @@ -1367,11 +1404,16 @@ def write_manifest( 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}") @@ -1495,6 +1537,57 @@ 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, @@ -1502,6 +1595,7 @@ def write_manifest_list( 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) @@ -1509,5 +1603,11 @@ def write_manifest_list( 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}") diff --git a/pyiceberg/table/update/snapshot.py b/pyiceberg/table/update/snapshot.py index 7a37b76287..d7ec7a23db 100644 --- a/pyiceberg/table/update/snapshot.py +++ b/pyiceberg/table/update/snapshot.py @@ -25,7 +25,7 @@ from dataclasses import dataclass from datetime import datetime from functools import cached_property -from typing import TYPE_CHECKING, Generic +from typing import TYPE_CHECKING, Generic, cast from pyiceberg.avro.codecs import AvroCompressionCodec from pyiceberg.exceptions import ( @@ -51,6 +51,7 @@ ManifestEntry, ManifestEntryStatus, ManifestFile, + ManifestListWriterV3, ManifestWriter, write_manifest, write_manifest_list, @@ -220,19 +221,6 @@ def delete_data_file(self, data_file: DataFile) -> _SnapshotProducer[U]: self._deleted_data_files.add(data_file) return self - def _calculate_added_rows(self, manifests: list[ManifestFile]) -> int: - """Calculate the number of added rows from a list of manifest files.""" - added_rows = 0 - for manifest in manifests: - if manifest.added_snapshot_id is None or manifest.added_snapshot_id == self._snapshot_id: - if manifest.added_rows_count is None: - raise ValueError( - "Cannot determine number of added rows in snapshot because " - f"the entry for manifest {manifest.manifest_path} is missing the field `added-rows-count`" - ) - added_rows += manifest.added_rows_count - return added_rows - @abstractmethod def _deleted_entries(self) -> list[ManifestEntry]: ... @@ -348,6 +336,12 @@ 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 + added_rows: 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), @@ -355,13 +349,13 @@ def _commit(self) -> UpdatesAndRequirements: parent_snapshot_id=self._parent_snapshot_id, sequence_number=next_sequence_number, avro_compression=self._compression, + first_row_id=first_row_id, ) 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 + if first_row_id is not None: + # row IDs assigned to manifests without a first_row_id, including existing rows of upgraded tables + added_rows = cast(ManifestListWriterV3, writer).next_row_id - first_row_id snapshot = Snapshot( snapshot_id=self._snapshot_id, @@ -371,6 +365,7 @@ def _commit(self) -> UpdatesAndRequirements: summary=summary, schema_id=self._transaction.table_metadata.current_schema_id, first_row_id=first_row_id, + added_rows=added_rows, ) add_snapshot_update = AddSnapshotUpdate(snapshot=snapshot) diff --git a/tests/integration/test_writes/test_writes.py b/tests/integration/test_writes/test_writes.py index ba367b0f9c..1e8c644b7d 100644 --- a/tests/integration/test_writes/test_writes.py +++ b/tests/integration/test_writes/test_writes.py @@ -2537,7 +2537,6 @@ def test_stage_only_overwrite_files( assert parent_snapshot_id == [None, first_snapshot, second_snapshot, second_snapshot, second_snapshot] -@pytest.mark.skip("V3 writer support is not enabled.") @pytest.mark.integration def test_v3_write_and_read_row_lineage(spark: SparkSession, session_catalog: Catalog) -> None: """Test writing to a v3 table and reading with Spark.""" @@ -2574,6 +2573,14 @@ def test_v3_write_and_read_row_lineage(spark: SparkSession, session_catalog: Cat "Expected next_row_id to be incremented by the number of added rows" ) + tbl.append(test_data) + assert tbl.metadata.next_row_id == initial_next_row_id + 2 * len(test_data) + + rows = spark.sql(f"SELECT _row_id, _last_updated_sequence_number FROM {identifier} ORDER BY _row_id").collect() + assert [(row._row_id, row._last_updated_sequence_number) for row in rows] == [ + (initial_next_row_id + i, 1 + i // len(test_data)) for i in range(2 * len(test_data)) + ] + # RecordBatchReader streaming append/overwrite — see https://github.com/apache/iceberg-python/issues/2152 # diff --git a/tests/table/test_snapshots.py b/tests/table/test_snapshots.py index 3c4806949e..2af28520c5 100644 --- a/tests/table/test_snapshots.py +++ b/tests/table/test_snapshots.py @@ -844,3 +844,109 @@ 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: + """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 + + +@pytest.fixture +def empty_table_v3(tmp_path: Path, arrow_table_simple: pa.Table) -> Table: + """An empty V3 table; writing V3 metadata files is not supported, so commits stay staged in a transaction.""" + from pyiceberg.catalog.noop import NoopCatalog + from pyiceberg.io import load_file_io + from pyiceberg.partitioning import UNPARTITIONED_PARTITION_SPEC + from pyiceberg.table.metadata import new_table_metadata + from pyiceberg.table.sorting import UNSORTED_SORT_ORDER + + metadata = new_table_metadata( + schema=Catalog._convert_schema_if_needed(arrow_table_simple.schema, format_version=3), + partition_spec=UNPARTITIONED_PARTITION_SPEC, + sort_order=UNSORTED_SORT_ORDER, + location=str(tmp_path), + properties={"format-version": "3"}, + ).model_copy(update={"next_row_id": 0}) + return Table( + identifier=("default", "lineage"), + metadata=metadata, + metadata_location=f"{tmp_path}/metadata/00000.metadata.json", + io=load_file_io(), + catalog=NoopCatalog("NoopCatalog"), + ) + + +def test_v3_append_assigns_row_lineage(empty_table_v3: Table, arrow_table_simple: pa.Table) -> None: + txn = empty_table_v3.transaction() + + txn.append(arrow_table_simple) + first = txn.table_metadata.current_snapshot() + assert first is not None + assert (first.first_row_id, first.added_rows) == (0, 3) + assert txn.table_metadata.next_row_id == 3 + + txn.append(arrow_table_simple) + second = txn.table_metadata.current_snapshot() + assert second is not None + assert (second.first_row_id, second.added_rows) == (3, 3) + assert txn.table_metadata.next_row_id == 6 + + +def test_v3_add_files_assigns_row_lineage(empty_table_v3: Table, arrow_table_simple: pa.Table, tmp_path: Path) -> None: + import pyarrow.parquet as pq + + file_path = str(tmp_path / "data.parquet") + pq.write_table(arrow_table_simple, file_path) + txn = empty_table_v3.transaction() + + txn.add_files([file_path]) + + snapshot = txn.table_metadata.current_snapshot() + assert snapshot is not None + assert (snapshot.first_row_id, snapshot.added_rows) == (0, 3) + assert txn.table_metadata.next_row_id == 3 + + +def test_v3_delete_assigns_row_ids_to_rewritten_rows_only(empty_table_v3: Table, arrow_table_simple: pa.Table) -> None: + txn = empty_table_v3.transaction() + txn.append(arrow_table_simple) + + txn.delete("bar == 1") + + snapshot = txn.table_metadata.current_snapshot() + assert snapshot is not None + # the rewritten data file holds the 2 surviving rows; the old file's DELETED entry uses no row IDs + assert (snapshot.first_row_id, snapshot.added_rows) == (3, 2) + assert txn.table_metadata.next_row_id == 5 diff --git a/tests/utils/test_manifest.py b/tests/utils/test_manifest.py index c084e0ccf7..f2a64f4afc 100644 --- a/tests/utils/test_manifest.py +++ b/tests/utils/test_manifest.py @@ -1661,3 +1661,362 @@ def test_negative_manifest_cache_size_raises_value_error(monkeypatch: pytest.Mon finally: monkeypatch.delenv("PYICEBERG_MANIFEST_CACHE_SIZE", raising=False) importlib.reload(manifest_module) + + +@pytest.mark.parametrize("compression", ["null", "deflate"]) +def test_write_manifest_v3(compression: AvroCompressionCodec) -> None: + io = load_file_io() + test_schema = Schema(NestedField(1, "foo", IntegerType(), False)) + + v3_data_file = DataFile.from_args( + _table_format_version=3, + content=DataFileContent.DATA, + file_path="/data/file-v3.parquet", + file_format=FileFormat.PARQUET, + partition=Record(), + record_count=100, + file_size_in_bytes=1024, + column_sizes={1: 10}, + value_counts={1: 100}, + null_value_counts={1: 0}, + split_offsets=[4], + sort_order_id=1, + first_row_id=1000, + ) + v2_data_file = DataFile.from_args( + content=DataFileContent.DATA, + file_path="/data/file-v2.parquet", + file_format=FileFormat.PARQUET, + partition=Record(), + record_count=50, + file_size_in_bytes=512, + ) + + with TemporaryDirectory() as tmp_dir: + path = tmp_dir + "/manifest-v3.avro" + with write_manifest( + format_version=3, + spec=UNPARTITIONED_PARTITION_SPEC, + schema=test_schema, + output_file=io.new_output(path), + snapshot_id=25, + avro_compression=compression, + ) as writer: + writer.add(ManifestEntry.from_args(status=ManifestEntryStatus.ADDED, snapshot_id=25, data_file=v3_data_file)) + writer.add(ManifestEntry.from_args(status=ManifestEntryStatus.ADDED, snapshot_id=25, data_file=v2_data_file)) + + _verify_metadata_with_fastavro(path, {"format-version": "3", "content": "data"}) + + with open(path, "rb") as f: + entries = list(fastavro.reader(f)) + + assert len(entries) == 2 + assert entries[0]["data_file"]["first_row_id"] == 1000 + assert entries[1]["data_file"]["first_row_id"] is None + for entry in entries: + for v3_field in ("first_row_id", "referenced_data_file", "content_offset", "content_size_in_bytes"): + assert v3_field in entry["data_file"] + assert entries[0]["data_file"]["sort_order_id"] == 1 + assert entries[0]["data_file"]["split_offsets"] == [4] + + # the V3 manifest must remain readable by the current reader + read_entries = writer.to_manifest_file().fetch_manifest_entry(io, discard_deleted=False) + assert len(read_entries) == 2 + assert read_entries[0].status == ManifestEntryStatus.ADDED + assert read_entries[0].data_file.file_path == "/data/file-v3.parquet" + assert read_entries[0].data_file.record_count == 100 + assert read_entries[0].data_file.column_sizes == {1: 10} + assert read_entries[0].data_file.value_counts == {1: 100} + assert read_entries[0].data_file.sort_order_id == 1 + assert read_entries[1].data_file.file_path == "/data/file-v2.parquet" + for read_entry in read_entries: + for v3_field in ("first_row_id", "referenced_data_file", "content_offset", "content_size_in_bytes"): + assert hasattr(read_entry.data_file, v3_field) + + +def test_write_manifest_v3_round_trips_deletion_vector_fields() -> None: + """The V3-only referenced_data_file/content_offset/content_size_in_bytes fields must survive a + write/read round trip with their actual values, not just be present-but-empty on the reader. + """ + io = load_file_io() + test_schema = Schema(NestedField(1, "foo", IntegerType(), False)) + + dv_data_file = DataFile.from_args( + _table_format_version=3, + content=DataFileContent.POSITION_DELETES, + file_path="/data/dv-1.puffin", + file_format=FileFormat.PUFFIN, + partition=Record(), + record_count=5, + file_size_in_bytes=256, + referenced_data_file="/data/file-v3.parquet", + content_offset=128, + content_size_in_bytes=64, + ) + + with TemporaryDirectory() as tmp_dir: + path = tmp_dir + "/manifest-v3-dv.avro" + with write_manifest( + format_version=3, + spec=UNPARTITIONED_PARTITION_SPEC, + schema=test_schema, + output_file=io.new_output(path), + snapshot_id=25, + avro_compression="null", + ) as writer: + writer.add(ManifestEntry.from_args(status=ManifestEntryStatus.ADDED, snapshot_id=25, data_file=dv_data_file)) + + read_entries = writer.to_manifest_file().fetch_manifest_entry(io, discard_deleted=False) + assert len(read_entries) == 1 + read_data_file = read_entries[0].data_file + assert read_data_file.referenced_data_file == "/data/file-v3.parquet" + assert read_data_file.content_offset == 128 + assert read_data_file.content_size_in_bytes == 64 + + +@pytest.mark.parametrize("compression", ["null", "deflate"]) +def test_write_manifest_list_v3_assigns_first_row_id(compression: AvroCompressionCodec) -> None: + io = load_file_io() + + def manifest(path: str, content: ManifestContent, first_row_id: int | None = None, **counts: int) -> ManifestFile: + args: dict[str, Any] = { + "manifest_path": path, + "manifest_length": 100, + "partition_spec_id": 0, + "content": content, + "sequence_number": 1, + "min_sequence_number": 1, + "added_snapshot_id": 25, + "added_files_count": 1, + "existing_files_count": 1, + "deleted_files_count": 0, + "added_rows_count": counts.get("added", 0), + "existing_rows_count": counts.get("existing", 0), + "deleted_rows_count": 0, + } + return ManifestFile.from_args(first_row_id=first_row_id, **args) + + unassigned_data = manifest("/m1.avro", ManifestContent.DATA, added=100, existing=25) + preserved_data = manifest("/m2.avro", ManifestContent.DATA, first_row_id=77, added=10) + deletes = manifest("/m3.avro", ManifestContent.DELETES, added=10) + second_unassigned_data = manifest("/m4.avro", ManifestContent.DATA, added=5) + + with TemporaryDirectory() as tmp_dir: + path = tmp_dir + "/manifest-list-v3.avro" + with write_manifest_list( + format_version=3, + output_file=io.new_output(path), + snapshot_id=25, + parent_snapshot_id=19, + sequence_number=2, + avro_compression=compression, + first_row_id=1000, + ) as writer: + writer.add_manifests([unassigned_data, preserved_data, deletes, second_unassigned_data]) + + # 1000 + (100 + 25) + (5): assigned manifests advance by added + existing rows + assert writer.next_row_id == 1130 # type: ignore[attr-defined] + + _verify_metadata_with_fastavro( + path, + { + "snapshot-id": "25", + "parent-snapshot-id": "19", + "sequence-number": "2", + "first-row-id": "1000", + "format-version": "3", + }, + ) + + with open(path, "rb") as f: + records = list(fastavro.reader(f)) + + assert [r["first_row_id"] for r in records] == [1000, 77, None, 1125] + + # the V3 manifest list must remain readable by the current reader + read_back = list(read_manifest_list(io.new_input(path))) + assert [m.manifest_path for m in read_back] == ["/m1.avro", "/m2.avro", "/m3.avro", "/m4.avro"] + assert read_back[0].added_rows_count == 100 + assert read_back[0].existing_rows_count == 25 + assert read_back[2].content == ManifestContent.DELETES + # the reader must expose the assigned first_row_id values rather than dropping them, otherwise a + # V3 manifest list cannot round-trip through the reader + assert [m.first_row_id for m in read_back] == [1000, 77, None, 1125] + + # re-writing the manifests read back from the V3 list must preserve their already-assigned + # first_row_id values instead of reassigning them + rewritten_path = tmp_dir + "/manifest-list-v3-rewritten.avro" + with write_manifest_list( + format_version=3, + output_file=io.new_output(rewritten_path), + snapshot_id=25, + parent_snapshot_id=19, + sequence_number=2, + avro_compression=compression, + first_row_id=2000, + ) as rewriter: + rewriter.add_manifests(read_back) + + rewritten = list(read_manifest_list(io.new_input(rewritten_path))) + # data manifests keep their prior first_row_id; the delete manifest stays None + assert [m.first_row_id for m in rewritten] == [1000, 77, None, 1125] + + +def _v3_manifest_file(path: str, content: ManifestContent, first_row_id: int | None = None) -> ManifestFile: + return ManifestFile.from_args( + manifest_path=path, + manifest_length=100, + partition_spec_id=0, + content=content, + sequence_number=1, + min_sequence_number=1, + added_snapshot_id=25, + added_files_count=1, + existing_files_count=0, + deleted_files_count=0, + added_rows_count=10, + existing_rows_count=0, + deleted_rows_count=0, + first_row_id=first_row_id, + ) + + +def _write_v3_manifest_list(path: str, manifests: list[ManifestFile]) -> None: + with write_manifest_list( + format_version=3, + output_file=load_file_io().new_output(path), + snapshot_id=25, + parent_snapshot_id=19, + sequence_number=2, + avro_compression="null", + first_row_id=1000, + ) as writer: + writer.add_manifests(manifests) + + +def test_write_manifest_list_v3_clears_first_row_id_on_delete_manifests() -> None: + deletes = _v3_manifest_file("/deletes.avro", ManifestContent.DELETES, first_row_id=77) + + with TemporaryDirectory() as tmp_dir: + path = tmp_dir + "/manifest-list-v3.avro" + _write_v3_manifest_list(path, [deletes]) + + with open(path, "rb") as f: + records = list(fastavro.reader(f)) + + assert [r["first_row_id"] for r in records] == [None] + + +def test_write_manifest_list_v3_does_not_mutate_input_manifests() -> None: + data = _v3_manifest_file("/data.avro", ManifestContent.DATA) + + with TemporaryDirectory() as tmp_dir: + _write_v3_manifest_list(tmp_dir + "/manifest-list-v3.avro", [data]) + + assert data.first_row_id is None + + +def test_write_manifest_list_v3_requires_first_row_id() -> None: + io = load_file_io() + with TemporaryDirectory() as tmp_dir: + with pytest.raises(ValueError, match="First-row-id is required for V3 tables"): + write_manifest_list( + format_version=3, + output_file=io.new_output(tmp_dir + "/manifest-list.avro"), + snapshot_id=25, + parent_snapshot_id=19, + sequence_number=2, + avro_compression="null", + first_row_id=None, + ) + + +@pytest.mark.parametrize("compression", ["null", "deflate"]) +def test_write_manifest_v3_carries_first_row_id(compression: AvroCompressionCodec) -> None: + io = load_file_io() + test_schema = Schema(NestedField(1, "foo", IntegerType(), False)) + data_file = DataFile.from_args( + content=DataFileContent.DATA, + file_path="/data/file.parquet", + file_format=FileFormat.PARQUET, + partition=Record(), + record_count=100, + file_size_in_bytes=1024, + ) + + with TemporaryDirectory() as tmp_dir: + with write_manifest( + format_version=3, + spec=UNPARTITIONED_PARTITION_SPEC, + schema=test_schema, + output_file=io.new_output(tmp_dir + "/manifest-rewrite.avro"), + snapshot_id=25, + avro_compression=compression, + first_row_id=100, + ) as writer: + writer.add(ManifestEntry.from_args(status=ManifestEntryStatus.ADDED, snapshot_id=25, data_file=data_file)) + + manifest_file = writer.to_manifest_file() + assert manifest_file.first_row_id == 100 + + # a manifest list writer must preserve the carried first_row_id and not advance next_row_id for it + path = tmp_dir + "/manifest-list.avro" + with write_manifest_list( + format_version=3, + output_file=io.new_output(path), + snapshot_id=25, + parent_snapshot_id=19, + sequence_number=2, + avro_compression=compression, + first_row_id=1000, + ) as list_writer: + list_writer.add_manifests([manifest_file]) + assert list_writer.next_row_id == 1000 # type: ignore[attr-defined] + + with open(path, "rb") as f: + records = list(fastavro.reader(f)) + assert [r["first_row_id"] for r in records] == [100] + + +def test_write_manifest_first_row_id_requires_v3() -> None: + io = load_file_io() + test_schema = Schema(NestedField(1, "foo", IntegerType(), False)) + with TemporaryDirectory() as tmp_dir: + with pytest.raises(ValueError, match="First-row-id is only supported for V3 tables"): + write_manifest( + format_version=2, + spec=UNPARTITIONED_PARTITION_SPEC, + schema=test_schema, + output_file=io.new_output(tmp_dir + "/manifest.avro"), + snapshot_id=25, + avro_compression="null", + first_row_id=100, + ) + + +def test_write_manifest_list_v3_rejects_unknown_row_counts() -> None: + io = load_file_io() + manifest = ManifestFile.from_args( + manifest_path="/m1.avro", + manifest_length=100, + partition_spec_id=0, + content=ManifestContent.DATA, + sequence_number=1, + min_sequence_number=1, + added_snapshot_id=25, + added_rows_count=None, + existing_rows_count=None, + ) + + with TemporaryDirectory() as tmp_dir: + with pytest.raises(ValueError, match="unknown row counts"): + with write_manifest_list( + format_version=3, + output_file=io.new_output(tmp_dir + "/manifest-list.avro"), + snapshot_id=25, + parent_snapshot_id=19, + sequence_number=2, + avro_compression="null", + first_row_id=1000, + ) as writer: + writer.add_manifests([manifest])