From 90b8da300e410681448a723a4d50ebc50c0061ca Mon Sep 17 00:00:00 2001 From: Abanoub Doss Date: Tue, 30 Jun 2026 21:28:26 -0500 Subject: [PATCH 01/10] feat: support arrow pycapsule streams Adopt the Arrow PyCapsule interface on both sides of the read/write boundary. append/overwrite accept any object implementing __arrow_c_stream__ (coerced to a streaming RecordBatchReader), and Table plus every scan expose __arrow_c_stream__ via BaseScan (not just DataScan) so any Arrow consumer can ingest them. --- pyiceberg/io/pyarrow.py | 61 +++++-- pyiceberg/table/__init__.py | 30 ++-- pyiceberg/typedef.py | 13 ++ tests/catalog/test_catalog_behaviors.py | 2 +- tests/io/test_pyarrow.py | 11 ++ tests/table/test_arrow_capsule.py | 226 ++++++++++++++++++++++++ 6 files changed, 320 insertions(+), 23 deletions(-) create mode 100644 tests/table/test_arrow_capsule.py diff --git a/pyiceberg/io/pyarrow.py b/pyiceberg/io/pyarrow.py index 6259f311e9..05c441203a 100644 --- a/pyiceberg/io/pyarrow.py +++ b/pyiceberg/io/pyarrow.py @@ -150,7 +150,7 @@ from pyiceberg.table.name_mapping import NameMapping, apply_name_mapping from pyiceberg.table.puffin import PuffinFile from pyiceberg.transforms import IdentityTransform, TruncateTransform -from pyiceberg.typedef import EMPTY_DICT, Properties, Record, TableVersion +from pyiceberg.typedef import EMPTY_DICT, ArrowStreamExportable, Properties, Record, TableVersion from pyiceberg.types import ( BinaryType, BooleanType, @@ -2690,30 +2690,45 @@ def bin_pack_arrow_table(tbl: pa.Table, target_file_size: int) -> Iterator[list[ """Bin-pack ``tbl`` into groups of RecordBatches, each ~``target_file_size``. Note: - ``target_file_size`` is measured in **uncompressed in-memory** Arrow bytes - (``Table.nbytes`` / ``RecordBatch.nbytes``), not compressed on-disk Parquet - bytes. The resulting Parquet file after compression (zstd by default, - plus dictionary/RLE encoding) is typically 3-10× smaller than - ``target_file_size``. This is a coarse proxy for the spec-defined + ``target_file_size`` is measured in **uncompressed in-memory** Arrow + bytes, not compressed on-disk Parquet bytes. The size estimate uses + ``nbytes`` when available and falls back to referenced buffer size for + Arrow view types that do not support ``nbytes``. The resulting Parquet + file after compression (zstd by default, plus dictionary/RLE encoding) + is typically 3-10× smaller than ``target_file_size``. This is a coarse + proxy for the spec-defined ``write.target-file-size-bytes`` and will be tightened to true on-disk bytes once the writer is switched to a rolling-``ParquetWriter`` with ``OutputStream.tell()`` (#2998). """ from pyiceberg.utils.bin_packing import PackingIterator - avg_row_size_bytes = tbl.nbytes / tbl.num_rows + avg_row_size_bytes = _arrow_data_size(tbl) / tbl.num_rows target_rows_per_file = max(1, int(target_file_size / avg_row_size_bytes)) batches = tbl.to_batches(max_chunksize=target_rows_per_file) bin_packed_record_batches = PackingIterator( items=batches, target_weight=target_file_size, lookback=len(batches), # ignore lookback - weight_func=lambda x: x.nbytes, + weight_func=_arrow_data_size, largest_bin_first=False, ) return bin_packed_record_batches +def _arrow_data_size(data: pa.Table | pa.RecordBatch) -> int: + """Estimate Arrow data size for writer bin-packing. + + ``nbytes`` is the better logical-size estimate, but PyArrow can raise for + view types such as ``string_view`` exported by libraries like Polars. Fall + back to total referenced buffer size so those streams can still be written. + """ + try: + return data.nbytes + except pyarrow.lib.ArrowTypeError: + return data.get_total_buffer_size() + + def bin_pack_record_batches(batches: Iterable[pa.RecordBatch], target_file_size: int) -> Iterator[list[pa.RecordBatch]]: """Microbatch a single-pass stream of RecordBatches into target-sized groups. @@ -2729,9 +2744,11 @@ def bin_pack_record_batches(batches: Iterable[pa.RecordBatch], target_file_size: Note: ``target_file_size`` is measured in **uncompressed in-memory** Arrow - bytes (``RecordBatch.nbytes``), not compressed on-disk Parquet bytes. - The resulting Parquet file after compression is typically 3-10× - smaller than ``target_file_size``. Matches the existing + bytes, not compressed on-disk Parquet bytes. The size estimate uses + ``nbytes`` when available and falls back to referenced buffer size for + Arrow view types that do not support ``nbytes``. The resulting Parquet + file after compression is typically 3-10× smaller than + ``target_file_size``. Matches the existing :func:`bin_pack_arrow_table` semantics; both will be tightened to true on-disk bytes once the writer is switched to a rolling- ``ParquetWriter`` with ``OutputStream.tell()`` (#2998). @@ -2740,7 +2757,7 @@ def bin_pack_record_batches(batches: Iterable[pa.RecordBatch], target_file_size: buffer_bytes = 0 for batch in batches: buffer.append(batch) - buffer_bytes += batch.nbytes + buffer_bytes += _arrow_data_size(batch) if buffer_bytes >= target_file_size: yield buffer buffer = [] @@ -3043,3 +3060,23 @@ def _get_field_from_arrow_table(arrow_table: pa.Table, field_path: str) -> pa.Ar field_array = arrow_table[path_parts[0]] # Navigate into the struct using the remaining path parts return pc.struct_field(field_array, path_parts[1:]) + + +def _coerce_arrow_input(df: pa.Table | pa.RecordBatchReader | ArrowStreamExportable) -> pa.Table | pa.RecordBatchReader: + """Normalize Arrow write input to a pa.Table or pa.RecordBatchReader. + + Native pyarrow inputs pass through unchanged; any object implementing the + Arrow PyCapsule stream interface (``__arrow_c_stream__``) is imported as a + streaming RecordBatchReader. + """ + if isinstance(df, (pa.Table, pa.RecordBatchReader)): + return df + + # Any object implementing the Arrow PyCapsule stream interface. + if hasattr(df, "__arrow_c_stream__"): + return pa.RecordBatchReader.from_stream(df) + + raise ValueError( + f"Expected pa.Table, pa.RecordBatchReader, or an object implementing the " + f"Arrow PyCapsule interface (__arrow_c_stream__), got: {df!r}" + ) diff --git a/pyiceberg/table/__init__.py b/pyiceberg/table/__init__.py index 63b87d290e..c4fc49533e 100644 --- a/pyiceberg/table/__init__.py +++ b/pyiceberg/table/__init__.py @@ -89,6 +89,7 @@ from pyiceberg.transforms import IdentityTransform from pyiceberg.typedef import ( EMPTY_DICT, + ArrowStreamExportable, IcebergBaseModel, IcebergRootModel, Identifier, @@ -459,7 +460,7 @@ def update_statistics(self) -> UpdateStatistics: def append( self, - df: pa.Table | pa.RecordBatchReader, + df: pa.Table | pa.RecordBatchReader | ArrowStreamExportable, snapshot_properties: dict[str, str] = EMPTY_DICT, branch: str | None = MAIN_BRANCH, ) -> None: @@ -512,10 +513,9 @@ def append( except ModuleNotFoundError as e: raise ModuleNotFoundError("For writes PyArrow needs to be installed") from e - from pyiceberg.io.pyarrow import _check_pyarrow_schema_compatible, _dataframe_to_data_files + from pyiceberg.io.pyarrow import _check_pyarrow_schema_compatible, _coerce_arrow_input, _dataframe_to_data_files - if not isinstance(df, (pa.Table, pa.RecordBatchReader)): - raise ValueError(f"Expected pa.Table or pa.RecordBatchReader, got: {df}") + df = _coerce_arrow_input(df) downcast_ns_timestamp_to_us = Config().get_bool(DOWNCAST_NS_TIMESTAMP_TO_US_ON_WRITE) or False _check_pyarrow_schema_compatible( @@ -605,7 +605,7 @@ def dynamic_partition_overwrite( def overwrite( self, - df: pa.Table | pa.RecordBatchReader, + df: pa.Table | pa.RecordBatchReader | ArrowStreamExportable, overwrite_filter: BooleanExpression | str = ALWAYS_TRUE, snapshot_properties: dict[str, str] = EMPTY_DICT, case_sensitive: bool = True, @@ -669,10 +669,9 @@ def overwrite( except ModuleNotFoundError as e: raise ModuleNotFoundError("For writes PyArrow needs to be installed") from e - from pyiceberg.io.pyarrow import _check_pyarrow_schema_compatible, _dataframe_to_data_files + from pyiceberg.io.pyarrow import _check_pyarrow_schema_compatible, _coerce_arrow_input, _dataframe_to_data_files - if not isinstance(df, (pa.Table, pa.RecordBatchReader)): - raise ValueError(f"Expected pa.Table or pa.RecordBatchReader, got: {df}") + df = _coerce_arrow_input(df) downcast_ns_timestamp_to_us = Config().get_bool(DOWNCAST_NS_TIMESTAMP_TO_US_ON_WRITE) or False _check_pyarrow_schema_compatible( @@ -1534,7 +1533,7 @@ def upsert( def append( self, - df: pa.Table | pa.RecordBatchReader, + df: pa.Table | pa.RecordBatchReader | ArrowStreamExportable, snapshot_properties: dict[str, str] = EMPTY_DICT, branch: str | None = MAIN_BRANCH, ) -> None: @@ -1569,7 +1568,7 @@ def dynamic_partition_overwrite( def overwrite( self, - df: pa.Table | pa.RecordBatchReader, + df: pa.Table | pa.RecordBatchReader | ArrowStreamExportable, overwrite_filter: BooleanExpression | str = ALWAYS_TRUE, snapshot_properties: dict[str, str] = EMPTY_DICT, case_sensitive: bool = True, @@ -1778,6 +1777,10 @@ def __datafusion_table_provider__(self, session: Any | None = None) -> IcebergDa ).__datafusion_table_provider__ return provider(session) + def __arrow_c_stream__(self, requested_schema: object | None = None) -> object: + """Export this Table as an Arrow C stream (PyCapsule interface).""" + return self.scan().to_arrow_batch_reader().__arrow_c_stream__(requested_schema) + class StaticTable(Table): """Load a table directly from a metadata file (i.e., without using a catalog).""" @@ -1908,6 +1911,13 @@ def plan_files(self) -> Iterable[ScanTask]: ... @abstractmethod def to_arrow(self) -> pa.Table: ... + @abstractmethod + def to_arrow_batch_reader(self) -> pa.RecordBatchReader: ... + + def __arrow_c_stream__(self, requested_schema: object | None = None) -> object: + """Export this scan's result as an Arrow C stream (PyCapsule interface).""" + return self.to_arrow_batch_reader().__arrow_c_stream__(requested_schema) + def update(self: A, **overrides: Any) -> A: """Create a copy of this table scan with updated fields.""" from inspect import signature diff --git a/pyiceberg/typedef.py b/pyiceberg/typedef.py index 6989144ef9..e965aebfe4 100644 --- a/pyiceberg/typedef.py +++ b/pyiceberg/typedef.py @@ -112,6 +112,19 @@ def __setitem__(self, pos: int, value: Any) -> None: """Assign a value to a StructProtocol.""" +@runtime_checkable +class ArrowStreamExportable(Protocol): # pragma: no cover + """Any object implementing the Arrow PyCapsule stream interface. + + Covers pa.Table, pa.RecordBatchReader, and third-party producers + (polars, arro3, nanoarrow, ...) without depending on any of them. + """ + + @abstractmethod + def __arrow_c_stream__(self, requested_schema: object | None = None) -> object: + """Export the object as an Arrow C stream PyCapsule.""" + + class IcebergBaseModel(BaseModel): """ This class extends the Pydantic BaseModel to set default values by overriding them. diff --git a/tests/catalog/test_catalog_behaviors.py b/tests/catalog/test_catalog_behaviors.py index b859e2d541..4c94c7d3c0 100644 --- a/tests/catalog/test_catalog_behaviors.py +++ b/tests/catalog/test_catalog_behaviors.py @@ -1318,7 +1318,7 @@ def test_append_invalid_input_type_raises(catalog: Catalog) -> None: identifier = f"default.append_invalid_input_{catalog.name}" pa_table = _simple_arrow_table() tbl = catalog.create_table(identifier=identifier, schema=pa_table.schema) - with pytest.raises(ValueError, match="Expected pa.Table or pa.RecordBatchReader"): + with pytest.raises(ValueError, match="Expected pa.Table, pa.RecordBatchReader, or an object implementing"): tbl.append("not an arrow object") diff --git a/tests/io/test_pyarrow.py b/tests/io/test_pyarrow.py index 532311899d..f821195d76 100644 --- a/tests/io/test_pyarrow.py +++ b/tests/io/test_pyarrow.py @@ -2435,6 +2435,17 @@ def test_bin_pack_arrow_table_target_size_smaller_than_row(arrow_table_with_null assert sum(batch.num_rows for bin_ in bin_packed for batch in bin_) == arrow_table_with_null.num_rows +def test_bin_pack_arrow_table_with_string_view() -> None: + if not hasattr(pa, "string_view"): + pytest.skip("pyarrow does not support string_view") + + table = pa.table({"region": pa.array(["ca", "mx"], type=pa.string_view())}) + + bins = list(bin_pack_arrow_table(table, target_file_size=1)) + + assert sum(batch.num_rows for bin_ in bins for batch in bin_) == table.num_rows + + def test_bin_pack_record_batches_single_bin(arrow_table_with_null: pa.Table) -> None: batches = arrow_table_with_null.to_batches() bins = list(bin_pack_record_batches(iter(batches), target_file_size=arrow_table_with_null.nbytes * 10)) diff --git a/tests/table/test_arrow_capsule.py b/tests/table/test_arrow_capsule.py new file mode 100644 index 0000000000..21bc3fa3e5 --- /dev/null +++ b/tests/table/test_arrow_capsule.py @@ -0,0 +1,226 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +"""Tests for Arrow PyCapsule interface support on the read and write paths. + +Covers the input/consumer side (write methods accept any object implementing +``__arrow_c_stream__``) and the output/producer side (``Table`` and every scan +expose ``__arrow_c_stream__`` so any Arrow consumer can ingest them). +""" + +from collections.abc import Callable +from pathlib import PosixPath +from typing import Any + +import pyarrow as pa +import pytest + +from pyiceberg.catalog.memory import InMemoryCatalog +from pyiceberg.io.pyarrow import _coerce_arrow_input +from pyiceberg.partitioning import PartitionField, PartitionSpec +from pyiceberg.schema import Schema +from pyiceberg.table import Table +from pyiceberg.transforms import IdentityTransform +from pyiceberg.types import IntegerType, NestedField, StringType + +SCHEMA = Schema( + NestedField(1, "id", IntegerType(), required=False), + NestedField(2, "region", StringType(), required=False), +) +ARROW_SCHEMA = pa.schema( + [ + pa.field("id", pa.int32(), nullable=True), + pa.field("region", pa.string(), nullable=True), + ] +) +PARTITION_SPEC = PartitionSpec(PartitionField(source_id=2, field_id=1000, transform=IdentityTransform(), name="region")) + + +class _ArrowStreamWrapper: + """A minimal third-party-style Arrow producer. + + Exposes only ``__arrow_c_stream__`` -- it is deliberately *not* a + ``pa.Table``/``pa.RecordBatchReader`` -- to stand in for libraries such as + polars or arro3 without taking a dependency on them. + """ + + def __init__(self, data: pa.Table): + self._data = data + + def __arrow_c_stream__(self, requested_schema: object | None = None) -> object: + return self._data.__arrow_c_stream__(requested_schema) + + +@pytest.fixture +def catalog(tmp_path: PosixPath) -> InMemoryCatalog: + catalog = InMemoryCatalog("test.in_memory.catalog", warehouse=tmp_path.absolute().as_posix()) + catalog.create_namespace("default") + return catalog + + +def _data(ids: list[int], regions: list[str]) -> pa.Table: + return pa.table({"id": pa.array(ids, type=pa.int32()), "region": regions}, schema=ARROW_SCHEMA) + + +def _string_view_data(ids: list[int], regions: list[str]) -> pa.Table: + if not hasattr(pa, "string_view"): + pytest.skip("pyarrow does not support string_view") + return pa.table( + {"id": pa.array(ids, type=pa.int32()), "region": pa.array(regions, type=pa.string_view())}, + schema=pa.schema( + [ + pa.field("id", pa.int32(), nullable=True), + pa.field("region", pa.string_view(), nullable=True), + ] + ), + ) + + +def _rows(table: pa.Table) -> list[dict[str, Any]]: + return sorted(table.to_pylist(), key=lambda r: r["id"]) + + +def test_coerce_arrow_input() -> None: + """Unit coverage of every branch of the coercion helper.""" + table = _data([1, 2, 3], ["us", "eu", "us"]) + + # native types pass through unchanged (identity) + assert _coerce_arrow_input(table) is table + reader = table.to_reader() + assert _coerce_arrow_input(reader) is reader + + # a foreign capsule producer is imported as a RecordBatchReader (streaming preserved) + coerced = _coerce_arrow_input(_ArrowStreamWrapper(table)) + assert isinstance(coerced, pa.RecordBatchReader) + assert coerced.read_all().num_rows == 3 + + # anything else is rejected + with pytest.raises(ValueError, match="Expected pa.Table, pa.RecordBatchReader"): + _coerce_arrow_input(object()) + + +# --------------------------------------------------------------------------- +# Input / consumer side (issue #2680) +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "make_input", + [ + pytest.param(lambda d: d, id="table"), + pytest.param(lambda d: d.to_reader(), id="reader"), + pytest.param(lambda d: _ArrowStreamWrapper(d), id="capsule"), + # A capsule whose stream yields multiple batches must be fully drained. + pytest.param( + lambda d: _ArrowStreamWrapper(pa.Table.from_batches(d.to_batches(max_chunksize=1))), + id="capsule_multi_batch", + ), + ], +) +def test_append_accepts_arrow_inputs(catalog: InMemoryCatalog, make_input: Callable[[pa.Table], object]) -> None: + tbl = catalog.create_table("default.append", schema=SCHEMA) + + tbl.append(make_input(_data([1, 2, 3], ["us", "eu", "us"]))) + + assert _rows(tbl.scan().to_arrow()) == _rows(_data([1, 2, 3], ["us", "eu", "us"])) + + +def test_overwrite_accepts_arrow_capsule(catalog: InMemoryCatalog) -> None: + tbl = catalog.create_table("default.overwrite_capsule", schema=SCHEMA) + tbl.append(_data([1, 2], ["us", "eu"])) + + tbl.overwrite(_ArrowStreamWrapper(_data([9], ["jp"]))) + + assert _rows(tbl.scan().to_arrow()) == _rows(_data([9], ["jp"])) + + +def test_append_accepts_arrow_capsule_with_string_view(catalog: InMemoryCatalog) -> None: + """Regression: Polars exports string columns as string_view over PyCapsule.""" + tbl = catalog.create_table("default.append_string_view", schema=SCHEMA) + + tbl.append(_ArrowStreamWrapper(_string_view_data([10, 11], ["ca", "mx"]))) + + assert _rows(tbl.scan().to_arrow()) == _rows(_data([10, 11], ["ca", "mx"])) + + +def test_append_pa_table_to_partitioned_table(catalog: InMemoryCatalog) -> None: + """Regression: a native pa.Table on a partitioned table must take the table + (partition-splitting) path, not be coerced into a RecordBatchReader (which + only supports unpartitioned writes).""" + tbl = catalog.create_table("default.append_partitioned", schema=SCHEMA, partition_spec=PARTITION_SPEC) + + tbl.append(_data([1, 2], ["us", "eu"])) + + assert tbl.scan().to_arrow().num_rows == 2 + + +# --------------------------------------------------------------------------- +# Output / producer side (issue #1655) +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "produce", + [ + pytest.param(lambda tbl: tbl, id="table"), + pytest.param(lambda tbl: tbl.scan(), id="scan"), + ], +) +def test_supports_arrow_c_stream(catalog: InMemoryCatalog, produce: Callable[[Table], object]) -> None: + tbl = catalog.create_table("default.stream", schema=SCHEMA) + tbl.append(_data([1, 2, 3], ["us", "eu", "us"])) + + # A consumer ingests the Table/DataScan directly via the PyCapsule interface. + consumed = pa.table(produce(tbl)) + + assert _rows(consumed) == _rows(tbl.scan().to_arrow()) + + +def test_scan_arrow_c_stream_respects_filter_and_projection(catalog: InMemoryCatalog) -> None: + tbl = catalog.create_table("default.scan_stream_filtered", schema=SCHEMA) + tbl.append(_data([1, 2, 3], ["us", "eu", "us"])) + + scan = tbl.scan(row_filter="region == 'us'", selected_fields=("id",)) + consumed = pa.table(scan) + + assert consumed.column_names == ["id"] + assert sorted(consumed.column("id").to_pylist()) == [1, 3] + + +def test_capsule_roundtrip_scan_into_append(catalog: InMemoryCatalog) -> None: + """The two halves compose: a scan (producer) can be appended into another + table (consumer) with no explicit pyarrow conversion in between.""" + src = catalog.create_table("default.roundtrip_src", schema=SCHEMA) + src.append(_data([1, 2, 3], ["us", "eu", "us"])) + dst = catalog.create_table("default.roundtrip_dst", schema=SCHEMA) + + dst.append(src.scan()) + + assert _rows(dst.scan().to_arrow()) == _rows(src.scan().to_arrow()) + + +def test_incremental_append_scan_supports_arrow_c_stream(catalog: InMemoryCatalog) -> None: + """IncrementalAppendScan is an Arrow producer too, so it must expose the + PyCapsule interface just like DataScan (inherited from BaseScan).""" + tbl = catalog.create_table("default.incremental_stream", schema=SCHEMA) + tbl.append(_data([1, 2, 3], ["us", "eu", "us"])) + + scan = tbl.incremental_append_scan() + + # A consumer ingests the incremental scan directly via the PyCapsule interface. + consumed = pa.table(scan) + + assert _rows(consumed) == _rows(scan.to_arrow()) From 6b1fbd829af82e32191053abaf6d74a6a2263e9a Mon Sep 17 00:00:00 2001 From: Abanoub Doss Date: Tue, 30 Jun 2026 21:28:26 -0500 Subject: [PATCH 02/10] test: update arrow input error expectations --- tests/integration/test_writes/test_partitioned_writes.py | 2 +- tests/integration/test_writes/test_writes.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/integration/test_writes/test_partitioned_writes.py b/tests/integration/test_writes/test_partitioned_writes.py index 1d1488255f..eb391144fd 100644 --- a/tests/integration/test_writes/test_partitioned_writes.py +++ b/tests/integration/test_writes/test_partitioned_writes.py @@ -768,7 +768,7 @@ def test_invalid_arguments(spark: SparkSession, session_catalog: Catalog) -> Non properties={"format-version": "1"}, ) - with pytest.raises(ValueError, match="Expected pa.Table or pa.RecordBatchReader, got: not a df"): + with pytest.raises(ValueError, match="Expected pa.Table, pa.RecordBatchReader, or an object implementing"): tbl.append("not a df") diff --git a/tests/integration/test_writes/test_writes.py b/tests/integration/test_writes/test_writes.py index 30fdd76ab7..e86f084754 100644 --- a/tests/integration/test_writes/test_writes.py +++ b/tests/integration/test_writes/test_writes.py @@ -791,10 +791,10 @@ def test_invalid_arguments(spark: SparkSession, session_catalog: Catalog, arrow_ identifier = "default.arrow_data_files" tbl = _create_table(session_catalog, identifier, {"format-version": "1"}, []) - with pytest.raises(ValueError, match="Expected pa.Table or pa.RecordBatchReader, got: not a df"): + with pytest.raises(ValueError, match="Expected pa.Table, pa.RecordBatchReader, or an object implementing"): tbl.overwrite("not a df") - with pytest.raises(ValueError, match="Expected pa.Table or pa.RecordBatchReader, got: not a df"): + with pytest.raises(ValueError, match="Expected pa.Table, pa.RecordBatchReader, or an object implementing"): tbl.append("not a df") From dfff87e10405fde95d64a0fb922f4719c535b479 Mon Sep 17 00:00:00 2001 From: Abanoub Doss Date: Wed, 25 Nov 2026 13:54:46 -0600 Subject: [PATCH 03/10] fix: keep BaseScan free of new abstract methods --- pyiceberg/table/__init__.py | 15 ++++++++------- tests/table/test_arrow_capsule.py | 2 -- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/pyiceberg/table/__init__.py b/pyiceberg/table/__init__.py index 9ce934ecbf..9321fe6946 100644 --- a/pyiceberg/table/__init__.py +++ b/pyiceberg/table/__init__.py @@ -2220,13 +2220,6 @@ def plan_files(self) -> Iterable[ScanTask]: ... @abstractmethod def to_arrow(self) -> pa.Table: ... - @abstractmethod - def to_arrow_batch_reader(self) -> pa.RecordBatchReader: ... - - def __arrow_c_stream__(self, requested_schema: object | None = None) -> object: - """Export this scan's result as an Arrow C stream (PyCapsule interface).""" - return self.to_arrow_batch_reader().__arrow_c_stream__(requested_schema) - def update(self: A, **overrides: Any) -> A: """Create a copy of this table scan with updated fields.""" from inspect import signature @@ -2687,6 +2680,10 @@ def to_arrow_batch_reader(self, dictionary_columns: tuple[str, ...] = ()) -> pa. self, self.projection(), self.plan_files(), dictionary_columns=dictionary_columns ) + def __arrow_c_stream__(self, requested_schema: object | None = None) -> object: + """Export this scan's result as an Arrow C stream (PyCapsule interface).""" + return self.to_arrow_batch_reader().__arrow_c_stream__(requested_schema) + def count(self) -> int: from pyiceberg.io.pyarrow import ArrowScan @@ -2866,6 +2863,10 @@ def to_arrow_batch_reader(self) -> pa.RecordBatchReader: """ return _to_arrow_batch_reader_via_file_scan_tasks(self, self.projection(), self.plan_files()) + def __arrow_c_stream__(self, requested_schema: object | None = None) -> object: + """Export this scan's result as an Arrow C stream (PyCapsule interface).""" + return self.to_arrow_batch_reader().__arrow_c_stream__(requested_schema) + def _validate_and_resolve_snapshots(self) -> tuple[int | None, int]: """Resolve the configured range to ``(from_snapshot_id_exclusive, to_snapshot_id_inclusive)``. diff --git a/tests/table/test_arrow_capsule.py b/tests/table/test_arrow_capsule.py index 21bc3fa3e5..533482b425 100644 --- a/tests/table/test_arrow_capsule.py +++ b/tests/table/test_arrow_capsule.py @@ -213,8 +213,6 @@ def test_capsule_roundtrip_scan_into_append(catalog: InMemoryCatalog) -> None: def test_incremental_append_scan_supports_arrow_c_stream(catalog: InMemoryCatalog) -> None: - """IncrementalAppendScan is an Arrow producer too, so it must expose the - PyCapsule interface just like DataScan (inherited from BaseScan).""" tbl = catalog.create_table("default.incremental_stream", schema=SCHEMA) tbl.append(_data([1, 2, 3], ["us", "eu", "us"])) From 5ef7c665ff0cf3dff49ec255b7b3480afe81b2db Mon Sep 17 00:00:00 2001 From: Abanoub Doss Date: Wed, 25 Nov 2026 13:55:38 -0600 Subject: [PATCH 04/10] fix: remove Table.__arrow_c_stream__ --- pyiceberg/table/__init__.py | 4 ---- tests/table/test_arrow_capsule.py | 17 ++++------------- 2 files changed, 4 insertions(+), 17 deletions(-) diff --git a/pyiceberg/table/__init__.py b/pyiceberg/table/__init__.py index 9321fe6946..8a3e14137b 100644 --- a/pyiceberg/table/__init__.py +++ b/pyiceberg/table/__init__.py @@ -2079,10 +2079,6 @@ def __datafusion_table_provider__(self, session: Any | None = None) -> IcebergDa ).__datafusion_table_provider__ return provider(session) - def __arrow_c_stream__(self, requested_schema: object | None = None) -> object: - """Export this Table as an Arrow C stream (PyCapsule interface).""" - return self.scan().to_arrow_batch_reader().__arrow_c_stream__(requested_schema) - class StaticTable(Table): """Load a table directly from a metadata file (i.e., without using a catalog).""" diff --git a/tests/table/test_arrow_capsule.py b/tests/table/test_arrow_capsule.py index 533482b425..fc93f45a4d 100644 --- a/tests/table/test_arrow_capsule.py +++ b/tests/table/test_arrow_capsule.py @@ -17,8 +17,8 @@ """Tests for Arrow PyCapsule interface support on the read and write paths. Covers the input/consumer side (write methods accept any object implementing -``__arrow_c_stream__``) and the output/producer side (``Table`` and every scan -expose ``__arrow_c_stream__`` so any Arrow consumer can ingest them). +``__arrow_c_stream__``) and the output/producer side (scans expose +``__arrow_c_stream__`` so any Arrow consumer can ingest them). """ from collections.abc import Callable @@ -32,7 +32,6 @@ from pyiceberg.io.pyarrow import _coerce_arrow_input from pyiceberg.partitioning import PartitionField, PartitionSpec from pyiceberg.schema import Schema -from pyiceberg.table import Table from pyiceberg.transforms import IdentityTransform from pyiceberg.types import IntegerType, NestedField, StringType @@ -172,19 +171,11 @@ def test_append_pa_table_to_partitioned_table(catalog: InMemoryCatalog) -> None: # --------------------------------------------------------------------------- -@pytest.mark.parametrize( - "produce", - [ - pytest.param(lambda tbl: tbl, id="table"), - pytest.param(lambda tbl: tbl.scan(), id="scan"), - ], -) -def test_supports_arrow_c_stream(catalog: InMemoryCatalog, produce: Callable[[Table], object]) -> None: +def test_scan_supports_arrow_c_stream(catalog: InMemoryCatalog) -> None: tbl = catalog.create_table("default.stream", schema=SCHEMA) tbl.append(_data([1, 2, 3], ["us", "eu", "us"])) - # A consumer ingests the Table/DataScan directly via the PyCapsule interface. - consumed = pa.table(produce(tbl)) + consumed = pa.table(tbl.scan()) assert _rows(consumed) == _rows(tbl.scan().to_arrow()) From d9230161d165d7ab758372554caf4d4e547c6e0f Mon Sep 17 00:00:00 2001 From: Abanoub Doss Date: Wed, 25 Nov 2026 13:55:20 -0600 Subject: [PATCH 05/10] fix: export scan arrow c streams without field ids --- pyiceberg/table/__init__.py | 28 ++++++++++++++++++++++------ tests/table/test_arrow_capsule.py | 29 +++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 6 deletions(-) diff --git a/pyiceberg/table/__init__.py b/pyiceberg/table/__init__.py index 8a3e14137b..bb433f4134 100644 --- a/pyiceberg/table/__init__.py +++ b/pyiceberg/table/__init__.py @@ -2517,14 +2517,18 @@ def _to_arrow_via_file_scan_tasks( def _to_arrow_batch_reader_via_file_scan_tasks( - scan: BaseScan, projected_schema: Schema, tasks: Iterable[FileScanTask], dictionary_columns: tuple[str, ...] = () + scan: BaseScan, + projected_schema: Schema, + tasks: Iterable[FileScanTask], + dictionary_columns: tuple[str, ...] = (), + include_field_ids: bool = True, ) -> pa.RecordBatchReader: """Stream a scan into an Arrow ``RecordBatchReader`` given its planned ``FileScanTask``s.""" import pyarrow as pa from pyiceberg.io.pyarrow import ArrowScan, schema_to_pyarrow - target_schema = schema_to_pyarrow(projected_schema) + target_schema = schema_to_pyarrow(projected_schema, include_field_ids=include_field_ids) batches = ArrowScan( scan.table_metadata, scan.io, @@ -2677,8 +2681,14 @@ def to_arrow_batch_reader(self, dictionary_columns: tuple[str, ...] = ()) -> pa. ) def __arrow_c_stream__(self, requested_schema: object | None = None) -> object: - """Export this scan's result as an Arrow C stream (PyCapsule interface).""" - return self.to_arrow_batch_reader().__arrow_c_stream__(requested_schema) + """Export this scan's result as an Arrow C stream (PyCapsule interface). + + We must drop field IDs, as to_arrow() does. They only have meaning + inside this table, and a write to another table would match columns + by them. + """ + reader = _to_arrow_batch_reader_via_file_scan_tasks(self, self.projection(), self.plan_files(), include_field_ids=False) + return reader.__arrow_c_stream__(requested_schema) def count(self) -> int: from pyiceberg.io.pyarrow import ArrowScan @@ -2860,8 +2870,14 @@ def to_arrow_batch_reader(self) -> pa.RecordBatchReader: return _to_arrow_batch_reader_via_file_scan_tasks(self, self.projection(), self.plan_files()) def __arrow_c_stream__(self, requested_schema: object | None = None) -> object: - """Export this scan's result as an Arrow C stream (PyCapsule interface).""" - return self.to_arrow_batch_reader().__arrow_c_stream__(requested_schema) + """Export this scan's result as an Arrow C stream (PyCapsule interface). + + We must drop field IDs, as to_arrow() does. They only have meaning + inside this table, and a write to another table would match columns + by them. + """ + reader = _to_arrow_batch_reader_via_file_scan_tasks(self, self.projection(), self.plan_files(), include_field_ids=False) + return reader.__arrow_c_stream__(requested_schema) def _validate_and_resolve_snapshots(self) -> tuple[int | None, int]: """Resolve the configured range to ``(from_snapshot_id_exclusive, to_snapshot_id_inclusive)``. diff --git a/tests/table/test_arrow_capsule.py b/tests/table/test_arrow_capsule.py index fc93f45a4d..f68af7a9d7 100644 --- a/tests/table/test_arrow_capsule.py +++ b/tests/table/test_arrow_capsule.py @@ -203,6 +203,35 @@ def test_capsule_roundtrip_scan_into_append(catalog: InMemoryCatalog) -> None: assert _rows(dst.scan().to_arrow()) == _rows(src.scan().to_arrow()) +def test_scan_arrow_c_stream_has_no_field_ids(catalog: InMemoryCatalog) -> None: + tbl = catalog.create_table("default.stream_field_ids", schema=SCHEMA) + tbl.append(_data([1, 2, 3], ["us", "eu", "us"])) + + for scan in (tbl.scan(), tbl.incremental_append_scan()): + assert all(field.metadata is None for field in pa.table(scan).schema) + + +def test_append_scan_matches_columns_by_name(catalog: InMemoryCatalog) -> None: + """The source and destination give the same names to different field ids.""" + src = catalog.create_table( + "default.by_name_src", + schema=Schema( + NestedField(1, "last", StringType(), required=False), NestedField(2, "first", StringType(), required=False) + ), + ) + src.append(pa.table({"last": ["Doe"], "first": ["Jane"]})) + dst = catalog.create_table( + "default.by_name_dst", + schema=Schema( + NestedField(1, "first", StringType(), required=False), NestedField(2, "last", StringType(), required=False) + ), + ) + + dst.append(src.scan()) + + assert dst.scan().to_arrow().to_pylist() == [{"first": "Jane", "last": "Doe"}] + + def test_incremental_append_scan_supports_arrow_c_stream(catalog: InMemoryCatalog) -> None: tbl = catalog.create_table("default.incremental_stream", schema=SCHEMA) tbl.append(_data([1, 2, 3], ["us", "eu", "us"])) From 9e1ff963fcd37e44eddbab233b905b7676e0fda3 Mon Sep 17 00:00:00 2001 From: Abanoub Doss Date: Wed, 25 Nov 2026 13:56:18 -0600 Subject: [PATCH 06/10] fix: cast arrow view types on write --- pyiceberg/io/pyarrow.py | 47 ++++++++++++------------------ tests/io/test_pyarrow.py | 48 ++++++++++++++++++++++++------- tests/table/test_arrow_capsule.py | 1 + 3 files changed, 57 insertions(+), 39 deletions(-) diff --git a/pyiceberg/io/pyarrow.py b/pyiceberg/io/pyarrow.py index 3b2a41084f..ead2426eca 100644 --- a/pyiceberg/io/pyarrow.py +++ b/pyiceberg/io/pyarrow.py @@ -3158,45 +3158,30 @@ def bin_pack_arrow_table(tbl: pa.Table, target_file_size: int) -> Iterator[list[ """Bin-pack ``tbl`` into groups of RecordBatches, each ~``target_file_size``. Note: - ``target_file_size`` is measured in **uncompressed in-memory** Arrow - bytes, not compressed on-disk Parquet bytes. The size estimate uses - ``nbytes`` when available and falls back to referenced buffer size for - Arrow view types that do not support ``nbytes``. The resulting Parquet - file after compression (zstd by default, plus dictionary/RLE encoding) - is typically 3-10× smaller than ``target_file_size``. This is a coarse - proxy for the spec-defined + ``target_file_size`` is measured in **uncompressed in-memory** Arrow bytes + (``Table.nbytes`` / ``RecordBatch.nbytes``), not compressed on-disk Parquet + bytes. The resulting Parquet file after compression (zstd by default, + plus dictionary/RLE encoding) is typically 3-10× smaller than + ``target_file_size``. This is a coarse proxy for the spec-defined ``write.target-file-size-bytes`` and will be tightened to true on-disk bytes once the writer is switched to a rolling-``ParquetWriter`` with ``OutputStream.tell()`` (#2998). """ from pyiceberg.utils.bin_packing import PackingIterator - avg_row_size_bytes = _arrow_data_size(tbl) / tbl.num_rows + avg_row_size_bytes = tbl.nbytes / tbl.num_rows target_rows_per_file = max(1, int(target_file_size / avg_row_size_bytes)) batches = tbl.to_batches(max_chunksize=target_rows_per_file) bin_packed_record_batches = PackingIterator( items=batches, target_weight=target_file_size, lookback=len(batches), # ignore lookback - weight_func=_arrow_data_size, + weight_func=lambda x: x.nbytes, largest_bin_first=False, ) return bin_packed_record_batches -def _arrow_data_size(data: pa.Table | pa.RecordBatch) -> int: - """Estimate Arrow data size for writer bin-packing. - - ``nbytes`` is the better logical-size estimate, but PyArrow can raise for - view types such as ``string_view`` exported by libraries like Polars. Fall - back to total referenced buffer size so those streams can still be written. - """ - try: - return data.nbytes - except pyarrow.lib.ArrowTypeError: - return data.get_total_buffer_size() - - def bin_pack_record_batches(batches: Iterable[pa.RecordBatch], target_file_size: int) -> Iterator[list[pa.RecordBatch]]: """Microbatch a single-pass stream of RecordBatches into target-sized groups. @@ -3212,11 +3197,9 @@ def bin_pack_record_batches(batches: Iterable[pa.RecordBatch], target_file_size: Note: ``target_file_size`` is measured in **uncompressed in-memory** Arrow - bytes, not compressed on-disk Parquet bytes. The size estimate uses - ``nbytes`` when available and falls back to referenced buffer size for - Arrow view types that do not support ``nbytes``. The resulting Parquet - file after compression is typically 3-10× smaller than - ``target_file_size``. Matches the existing + bytes (``RecordBatch.nbytes``), not compressed on-disk Parquet bytes. + The resulting Parquet file after compression is typically 3-10× + smaller than ``target_file_size``. Matches the existing :func:`bin_pack_arrow_table` semantics; both will be tightened to true on-disk bytes once the writer is switched to a rolling- ``ParquetWriter`` with ``OutputStream.tell()`` (#2998). @@ -3225,7 +3208,7 @@ def bin_pack_record_batches(batches: Iterable[pa.RecordBatch], target_file_size: buffer_bytes = 0 for batch in batches: buffer.append(batch) - buffer_bytes += _arrow_data_size(batch) + buffer_bytes += batch.nbytes if buffer_bytes >= target_file_size: yield buffer buffer = [] @@ -3386,6 +3369,14 @@ def _dataframe_to_data_files( property_name=TableProperties.WRITE_TARGET_FILE_SIZE_BYTES, default=TableProperties.WRITE_TARGET_FILE_SIZE_BYTES_DEFAULT, ) + # Cast view types to plain string and binary. PyArrow cannot yet filter + # on view types or combine them with the plain columns of other data + # files, so a table written with them could not be scanned with a filter + # or deleted from. This cast can be removed once PyArrow supports both. + arrow_schema = visit_pyarrow(df.schema, _ConvertViewTypes()) + if arrow_schema != df.schema: + df = df.cast(arrow_schema) + name_mapping = table_metadata.schema().name_mapping downcast_ns_timestamp_to_us = Config().get_bool(DOWNCAST_NS_TIMESTAMP_TO_US_ON_WRITE) or False task_schema = pyarrow_to_schema( diff --git a/tests/io/test_pyarrow.py b/tests/io/test_pyarrow.py index 46d4fe1215..f2758b4921 100644 --- a/tests/io/test_pyarrow.py +++ b/tests/io/test_pyarrow.py @@ -3138,17 +3138,6 @@ def test_bin_pack_arrow_table_target_size_smaller_than_row(arrow_table_with_null assert sum(batch.num_rows for bin_ in bin_packed for batch in bin_) == arrow_table_with_null.num_rows -def test_bin_pack_arrow_table_with_string_view() -> None: - if not hasattr(pa, "string_view"): - pytest.skip("pyarrow does not support string_view") - - table = pa.table({"region": pa.array(["ca", "mx"], type=pa.string_view())}) - - bins = list(bin_pack_arrow_table(table, target_file_size=1)) - - assert sum(batch.num_rows for bin_ in bins for batch in bin_) == table.num_rows - - def test_bin_pack_record_batches_single_bin(arrow_table_with_null: pa.Table) -> None: batches = arrow_table_with_null.to_batches() bins = list(bin_pack_record_batches(iter(batches), target_file_size=arrow_table_with_null.nbytes * 10)) @@ -3724,6 +3713,43 @@ def test_append_view_types_to_partitioned_table(catalog: InMemoryCatalog) -> Non assert sorted(table.scan().to_arrow().to_pylist(), key=lambda row: row["id"]) == arrow_table.to_pylist() +def test_append_view_types_to_unpartitioned_table(catalog: InMemoryCatalog) -> None: + schema = Schema( + NestedField(id=1, name="id", field_type=LongType(), required=False), + NestedField(id=2, name="region", field_type=StringType(), required=False), + NestedField(id=3, name="payload", field_type=BinaryType(), required=False), + NestedField(id=4, name="tags", field_type=ListType(element_id=5, element_type=StringType(), element_required=False)), + ) + catalog.create_namespace("default") + plain_table = pa.table( + { + "id": pa.array([1], type=pa.int64()), + "region": pa.array(["us"], type=pa.string()), + "payload": pa.array([b"a"], type=pa.binary()), + "tags": pa.array([["x"]], type=pa.list_(pa.string())), + } + ) + view_table = pa.table( + { + "id": pa.array([2, 3], type=pa.int64()), + "region": pa.array(["us", "eu"], type=pa.string_view()), + "payload": pa.array([b"a", b"b"], type=pa.binary_view()), + "tags": pa.array([["x"], ["y"]], type=pa.list_(pa.string_view())), + } + ) + + for name, df in (("table", view_table), ("reader", view_table.to_reader())): + table = catalog.create_table(f"default.test_append_view_types_{name}", schema=schema) + table.append(plain_table) + table.append(df) + + assert sorted(table.scan().to_arrow()["tags"].to_pylist()) == [["x"], ["x"], ["y"]], name + assert sorted(table.scan(row_filter="region == 'us'").to_arrow()["id"].to_pylist()) == [1, 2], name + assert sorted(table.scan(row_filter=EqualTo("payload", b"a")).to_arrow()["id"].to_pylist()) == [1, 2], name + table.delete("region == 'us'") + assert table.scan().to_arrow()["id"].to_pylist() == [3], name + + def test_append_to_table_bucketed_by_time(catalog: InMemoryCatalog) -> None: schema = Schema( NestedField(id=1, name="id", field_type=LongType(), required=False), diff --git a/tests/table/test_arrow_capsule.py b/tests/table/test_arrow_capsule.py index f68af7a9d7..23c5d971ac 100644 --- a/tests/table/test_arrow_capsule.py +++ b/tests/table/test_arrow_capsule.py @@ -153,6 +153,7 @@ def test_append_accepts_arrow_capsule_with_string_view(catalog: InMemoryCatalog) tbl.append(_ArrowStreamWrapper(_string_view_data([10, 11], ["ca", "mx"]))) assert _rows(tbl.scan().to_arrow()) == _rows(_data([10, 11], ["ca", "mx"])) + assert _rows(tbl.scan(row_filter="region == 'ca'").to_arrow()) == _rows(_data([10], ["ca"])) def test_append_pa_table_to_partitioned_table(catalog: InMemoryCatalog) -> None: From 8cee5252ec6baa72ddba74bc0c73b8f02d15a452 Mon Sep 17 00:00:00 2001 From: Abanoub Doss Date: Wed, 25 Nov 2026 13:57:16 -0600 Subject: [PATCH 07/10] test: tighten arrow capsule coverage --- tests/table/test_arrow_capsule.py | 65 +++++++++++++------------------ 1 file changed, 27 insertions(+), 38 deletions(-) diff --git a/tests/table/test_arrow_capsule.py b/tests/table/test_arrow_capsule.py index 23c5d971ac..69842b0d98 100644 --- a/tests/table/test_arrow_capsule.py +++ b/tests/table/test_arrow_capsule.py @@ -21,7 +21,6 @@ ``__arrow_c_stream__`` so any Arrow consumer can ingest them). """ -from collections.abc import Callable from pathlib import PosixPath from typing import Any @@ -75,8 +74,6 @@ def _data(ids: list[int], regions: list[str]) -> pa.Table: def _string_view_data(ids: list[int], regions: list[str]) -> pa.Table: - if not hasattr(pa, "string_view"): - pytest.skip("pyarrow does not support string_view") return pa.table( {"id": pa.array(ids, type=pa.int32()), "region": pa.array(regions, type=pa.string_view())}, schema=pa.schema( @@ -116,25 +113,16 @@ def test_coerce_arrow_input() -> None: # --------------------------------------------------------------------------- -@pytest.mark.parametrize( - "make_input", - [ - pytest.param(lambda d: d, id="table"), - pytest.param(lambda d: d.to_reader(), id="reader"), - pytest.param(lambda d: _ArrowStreamWrapper(d), id="capsule"), - # A capsule whose stream yields multiple batches must be fully drained. - pytest.param( - lambda d: _ArrowStreamWrapper(pa.Table.from_batches(d.to_batches(max_chunksize=1))), - id="capsule_multi_batch", - ), - ], -) -def test_append_accepts_arrow_inputs(catalog: InMemoryCatalog, make_input: Callable[[pa.Table], object]) -> None: - tbl = catalog.create_table("default.append", schema=SCHEMA) +def test_append_accepts_arrow_capsule(catalog: InMemoryCatalog) -> None: + data = _data([1, 2, 3], ["us", "eu", "us"]) - tbl.append(make_input(_data([1, 2, 3], ["us", "eu", "us"]))) + # A stream of several batches must be fully drained. + for name, stream in (("single", data), ("multi", pa.Table.from_batches(data.to_batches(max_chunksize=1)))): + tbl = catalog.create_table(f"default.append_{name}_batch", schema=SCHEMA) - assert _rows(tbl.scan().to_arrow()) == _rows(_data([1, 2, 3], ["us", "eu", "us"])) + tbl.append(_ArrowStreamWrapper(stream)) + + assert _rows(tbl.scan().to_arrow()) == _rows(data), name def test_overwrite_accepts_arrow_capsule(catalog: InMemoryCatalog) -> None: @@ -156,17 +144,6 @@ def test_append_accepts_arrow_capsule_with_string_view(catalog: InMemoryCatalog) assert _rows(tbl.scan(row_filter="region == 'ca'").to_arrow()) == _rows(_data([10], ["ca"])) -def test_append_pa_table_to_partitioned_table(catalog: InMemoryCatalog) -> None: - """Regression: a native pa.Table on a partitioned table must take the table - (partition-splitting) path, not be coerced into a RecordBatchReader (which - only supports unpartitioned writes).""" - tbl = catalog.create_table("default.append_partitioned", schema=SCHEMA, partition_spec=PARTITION_SPEC) - - tbl.append(_data([1, 2], ["us", "eu"])) - - assert tbl.scan().to_arrow().num_rows == 2 - - # --------------------------------------------------------------------------- # Output / producer side (issue #1655) # --------------------------------------------------------------------------- @@ -181,7 +158,7 @@ def test_scan_supports_arrow_c_stream(catalog: InMemoryCatalog) -> None: assert _rows(consumed) == _rows(tbl.scan().to_arrow()) -def test_scan_arrow_c_stream_respects_filter_and_projection(catalog: InMemoryCatalog) -> None: +def test_scan_arrow_c_stream_respects_filter_projection_and_limit(catalog: InMemoryCatalog) -> None: tbl = catalog.create_table("default.scan_stream_filtered", schema=SCHEMA) tbl.append(_data([1, 2, 3], ["us", "eu", "us"])) @@ -190,6 +167,7 @@ def test_scan_arrow_c_stream_respects_filter_and_projection(catalog: InMemoryCat assert consumed.column_names == ["id"] assert sorted(consumed.column("id").to_pylist()) == [1, 3] + assert pa.table(scan.update(limit=1)).num_rows == 1 def test_capsule_roundtrip_scan_into_append(catalog: InMemoryCatalog) -> None: @@ -204,6 +182,18 @@ def test_capsule_roundtrip_scan_into_append(catalog: InMemoryCatalog) -> None: assert _rows(dst.scan().to_arrow()) == _rows(src.scan().to_arrow()) +def test_scan_arrow_c_stream_casts_to_requested_schema(catalog: InMemoryCatalog) -> None: + tbl = catalog.create_table("default.stream_requested_schema", schema=SCHEMA) + tbl.append(_data([1, 2, 3], ["us", "eu", "us"])) + requested = pa.schema([pa.field("id", pa.int64()), pa.field("region", pa.string())]) + + for scan in (tbl.scan(), tbl.incremental_append_scan()): + consumed = pa.RecordBatchReader.from_stream(scan, schema=requested).read_all() + + assert consumed.schema == requested + assert _rows(consumed) == _rows(_data([1, 2, 3], ["us", "eu", "us"])) + + def test_scan_arrow_c_stream_has_no_field_ids(catalog: InMemoryCatalog) -> None: tbl = catalog.create_table("default.stream_field_ids", schema=SCHEMA) tbl.append(_data([1, 2, 3], ["us", "eu", "us"])) @@ -235,11 +225,10 @@ def test_append_scan_matches_columns_by_name(catalog: InMemoryCatalog) -> None: def test_incremental_append_scan_supports_arrow_c_stream(catalog: InMemoryCatalog) -> None: tbl = catalog.create_table("default.incremental_stream", schema=SCHEMA) - tbl.append(_data([1, 2, 3], ["us", "eu", "us"])) - - scan = tbl.incremental_append_scan() + tbl.append(_data([1, 2], ["us", "eu"])) + first_snapshot_id = tbl.metadata.current_snapshot_id + tbl.append(_data([3], ["us"])) - # A consumer ingests the incremental scan directly via the PyCapsule interface. - consumed = pa.table(scan) + consumed = pa.table(tbl.incremental_append_scan(from_snapshot_id_exclusive=first_snapshot_id)) - assert _rows(consumed) == _rows(scan.to_arrow()) + assert _rows(consumed) == _rows(_data([3], ["us"])) From 9df1a380092f9e5b2d6d9aba58b80d39a5a4bae6 Mon Sep 17 00:00:00 2001 From: Abanoub Doss Date: Wed, 25 Nov 2026 13:57:09 -0600 Subject: [PATCH 08/10] fix: accept arrow c stream input for partitioned tables --- pyiceberg/io/pyarrow.py | 22 +---------- pyiceberg/table/__init__.py | 54 ++++++++++++++++---------- tests/table/test_arrow_capsule.py | 64 ++++++++++++++++++++----------- 3 files changed, 77 insertions(+), 63 deletions(-) diff --git a/pyiceberg/io/pyarrow.py b/pyiceberg/io/pyarrow.py index ead2426eca..f6c302a723 100644 --- a/pyiceberg/io/pyarrow.py +++ b/pyiceberg/io/pyarrow.py @@ -161,7 +161,7 @@ from pyiceberg.table.metadata_columns import LAST_UPDATED_SEQUENCE_NUMBER, ROW_ID from pyiceberg.table.name_mapping import NameMapping, apply_name_mapping from pyiceberg.transforms import IdentityTransform, TruncateTransform -from pyiceberg.typedef import EMPTY_DICT, ArrowStreamExportable, Properties, Record, TableVersion +from pyiceberg.typedef import EMPTY_DICT, Properties, Record, TableVersion from pyiceberg.types import ( DEFAULT_GEOMETRY_CRS, BinaryType, @@ -3543,23 +3543,3 @@ def _get_field_from_arrow_table(arrow_table: pa.Table, field_path: str) -> pa.Ar field_array = arrow_table[path_parts[0]] # Navigate into the struct using the remaining path parts return pc.struct_field(field_array, path_parts[1:]) - - -def _coerce_arrow_input(df: pa.Table | pa.RecordBatchReader | ArrowStreamExportable) -> pa.Table | pa.RecordBatchReader: - """Normalize Arrow write input to a pa.Table or pa.RecordBatchReader. - - Native pyarrow inputs pass through unchanged; any object implementing the - Arrow PyCapsule stream interface (``__arrow_c_stream__``) is imported as a - streaming RecordBatchReader. - """ - if isinstance(df, (pa.Table, pa.RecordBatchReader)): - return df - - # Any object implementing the Arrow PyCapsule stream interface. - if hasattr(df, "__arrow_c_stream__"): - return pa.RecordBatchReader.from_stream(df) - - raise ValueError( - f"Expected pa.Table, pa.RecordBatchReader, or an object implementing the " - f"Arrow PyCapsule interface (__arrow_c_stream__), got: {df!r}" - ) diff --git a/pyiceberg/table/__init__.py b/pyiceberg/table/__init__.py index bb433f4134..58d737b9e9 100644 --- a/pyiceberg/table/__init__.py +++ b/pyiceberg/table/__init__.py @@ -522,6 +522,36 @@ def update_partition_statistics(self) -> UpdatePartitionStatistics: """ return UpdatePartitionStatistics(transaction=self) + def _prepare_arrow_input( + self, df: pa.Table | pa.RecordBatchReader | ArrowStreamExportable + ) -> pa.Table | pa.RecordBatchReader: + """Return the write input as Arrow data that matches the table schema.""" + import pyarrow as pa + + from pyiceberg.io.pyarrow import _check_pyarrow_schema_compatible + + if isinstance(df, (pa.Table, pa.RecordBatchReader)): + arrow_data, read_into_memory = df, False + elif hasattr(df, "__arrow_c_stream__"): + # Streaming writes need an unpartitioned table, so the stream is + # read into memory for a partitioned one + arrow_data = pa.RecordBatchReader.from_stream(df) + read_into_memory = not self.table_metadata.spec().is_unpartitioned() + else: + raise ValueError( + f"Expected pa.Table, pa.RecordBatchReader, or an object implementing the " + f"Arrow PyCapsule interface (__arrow_c_stream__), got: {df!r}" + ) + + _check_pyarrow_schema_compatible( + self.table_metadata.schema(), + provided_schema=arrow_data.schema, + downcast_ns_timestamp_to_us=Config().get_bool(DOWNCAST_NS_TIMESTAMP_TO_US_ON_WRITE) or False, + format_version=self.table_metadata.format_version, + ) + + return arrow_data.read_all() if read_into_memory else arrow_data + def append( self, df: pa.Table | pa.RecordBatchReader | ArrowStreamExportable, @@ -577,17 +607,9 @@ def append( except ModuleNotFoundError as e: raise ModuleNotFoundError("For writes PyArrow needs to be installed") from e - from pyiceberg.io.pyarrow import _check_pyarrow_schema_compatible, _coerce_arrow_input, _dataframe_to_data_files + from pyiceberg.io.pyarrow import _dataframe_to_data_files - df = _coerce_arrow_input(df) - - downcast_ns_timestamp_to_us = Config().get_bool(DOWNCAST_NS_TIMESTAMP_TO_US_ON_WRITE) or False - _check_pyarrow_schema_compatible( - self.table_metadata.schema(), - provided_schema=df.schema, - downcast_ns_timestamp_to_us=downcast_ns_timestamp_to_us, - format_version=self.table_metadata.format_version, - ) + df = self._prepare_arrow_input(df) with self._append_snapshot_producer(snapshot_properties, branch=branch) as append_files: # For pa.Table we can short-circuit empty inputs cheaply. For a @@ -741,17 +763,9 @@ def overwrite( except ModuleNotFoundError as e: raise ModuleNotFoundError("For writes PyArrow needs to be installed") from e - from pyiceberg.io.pyarrow import _check_pyarrow_schema_compatible, _coerce_arrow_input, _dataframe_to_data_files - - df = _coerce_arrow_input(df) + from pyiceberg.io.pyarrow import _dataframe_to_data_files - downcast_ns_timestamp_to_us = Config().get_bool(DOWNCAST_NS_TIMESTAMP_TO_US_ON_WRITE) or False - _check_pyarrow_schema_compatible( - self.table_metadata.schema(), - provided_schema=df.schema, - downcast_ns_timestamp_to_us=downcast_ns_timestamp_to_us, - format_version=self.table_metadata.format_version, - ) + df = self._prepare_arrow_input(df) if overwrite_filter != AlwaysFalse(): # Only delete when the filter is != AlwaysFalse diff --git a/tests/table/test_arrow_capsule.py b/tests/table/test_arrow_capsule.py index 69842b0d98..192b2653ff 100644 --- a/tests/table/test_arrow_capsule.py +++ b/tests/table/test_arrow_capsule.py @@ -21,6 +21,7 @@ ``__arrow_c_stream__`` so any Arrow consumer can ingest them). """ +from collections.abc import Iterator from pathlib import PosixPath from typing import Any @@ -28,8 +29,7 @@ import pytest from pyiceberg.catalog.memory import InMemoryCatalog -from pyiceberg.io.pyarrow import _coerce_arrow_input -from pyiceberg.partitioning import PartitionField, PartitionSpec +from pyiceberg.partitioning import UNPARTITIONED_PARTITION_SPEC, PartitionField, PartitionSpec from pyiceberg.schema import Schema from pyiceberg.transforms import IdentityTransform from pyiceberg.types import IntegerType, NestedField, StringType @@ -55,7 +55,7 @@ class _ArrowStreamWrapper: polars or arro3 without taking a dependency on them. """ - def __init__(self, data: pa.Table): + def __init__(self, data: pa.Table | pa.RecordBatchReader): self._data = data def __arrow_c_stream__(self, requested_schema: object | None = None) -> object: @@ -89,25 +89,6 @@ def _rows(table: pa.Table) -> list[dict[str, Any]]: return sorted(table.to_pylist(), key=lambda r: r["id"]) -def test_coerce_arrow_input() -> None: - """Unit coverage of every branch of the coercion helper.""" - table = _data([1, 2, 3], ["us", "eu", "us"]) - - # native types pass through unchanged (identity) - assert _coerce_arrow_input(table) is table - reader = table.to_reader() - assert _coerce_arrow_input(reader) is reader - - # a foreign capsule producer is imported as a RecordBatchReader (streaming preserved) - coerced = _coerce_arrow_input(_ArrowStreamWrapper(table)) - assert isinstance(coerced, pa.RecordBatchReader) - assert coerced.read_all().num_rows == 3 - - # anything else is rejected - with pytest.raises(ValueError, match="Expected pa.Table, pa.RecordBatchReader"): - _coerce_arrow_input(object()) - - # --------------------------------------------------------------------------- # Input / consumer side (issue #2680) # --------------------------------------------------------------------------- @@ -144,6 +125,45 @@ def test_append_accepts_arrow_capsule_with_string_view(catalog: InMemoryCatalog) assert _rows(tbl.scan(row_filter="region == 'ca'").to_arrow()) == _rows(_data([10], ["ca"])) +def test_append_arrow_capsule_to_partitioned_table(catalog: InMemoryCatalog) -> None: + tbl = catalog.create_table("default.append_capsule_partitioned", schema=SCHEMA, partition_spec=PARTITION_SPEC) + + tbl.append(_ArrowStreamWrapper(_string_view_data([1, 2, 3], ["us", "eu", "us"]))) + + assert len(tbl.inspect.partitions()) == 2 + assert _rows(tbl.scan().to_arrow()) == _rows(_data([1, 2, 3], ["us", "eu", "us"])) + + +def test_arrow_capsule_is_streamed_into_an_unpartitioned_table_only(catalog: InMemoryCatalog) -> None: + data = _data([1, 2, 3], ["us", "eu", "us"]) + + for name, spec, expected in ( + ("unpartitioned", UNPARTITIONED_PARTITION_SPEC, pa.RecordBatchReader), + ("partitioned", PARTITION_SPEC, pa.Table), + ): + tbl = catalog.create_table(f"default.streamed_{name}", schema=SCHEMA, partition_spec=spec) + + assert isinstance(tbl.transaction()._prepare_arrow_input(_ArrowStreamWrapper(data)), expected), name + + +def test_append_checks_schema_before_reading_arrow_capsule(catalog: InMemoryCatalog) -> None: + pulled: list[pa.RecordBatch] = [] + mismatched = pa.table({"id": ["a", "b"], "region": ["us", "eu"]}) + + def batches() -> Iterator[pa.RecordBatch]: + for batch in mismatched.to_batches(max_chunksize=1): + pulled.append(batch) + yield batch + + for name, spec in (("unpartitioned", UNPARTITIONED_PARTITION_SPEC), ("partitioned", PARTITION_SPEC)): + tbl = catalog.create_table(f"default.schema_check_{name}", schema=SCHEMA, partition_spec=spec) + + with pytest.raises(ValueError, match="Mismatch in fields"): + tbl.append(_ArrowStreamWrapper(pa.RecordBatchReader.from_batches(mismatched.schema, batches()))) + + assert not pulled, name + + # --------------------------------------------------------------------------- # Output / producer side (issue #1655) # --------------------------------------------------------------------------- From 3d8e175bfb3389305c0069b77631001ac4c7e3a2 Mon Sep 17 00:00:00 2001 From: Abanoub Doss Date: Wed, 25 Nov 2026 13:57:53 -0600 Subject: [PATCH 09/10] docs: describe arrow c stream input and scan export --- mkdocs/docs/api.md | 19 +++++++++++++++++++ pyiceberg/table/__init__.py | 32 ++++++++++++++++++++++---------- pyiceberg/typedef.py | 1 - 3 files changed, 41 insertions(+), 11 deletions(-) diff --git a/mkdocs/docs/api.md b/mkdocs/docs/api.md index f823a2fc60..518d8e15e6 100644 --- a/mkdocs/docs/api.md +++ b/mkdocs/docs/api.md @@ -407,6 +407,25 @@ long: [[4.896029,-122.431297,6.0989],[6.56667]] In the case of `tbl.delete(delete_filter="city == 'Groningen'")`, the whole Parquet file will be dropped without checking it contents, since from the Iceberg metadata PyIceberg can derive that all the content in the file matches the predicate. +### Arrow PyCapsule interface + + +`tbl.append()` and `tbl.overwrite()` accept any object that implements the [Arrow PyCapsule stream interface](https://arrow.apache.org/docs/format/CDataInterface/PyCapsuleInterface.html) (`__arrow_c_stream__`), so a dataframe from a library such as Polars can be written without converting it to PyArrow first: + +```python +import polars as pl + +tbl.append(pl.DataFrame({"city": ["Groningen"], "lat": [53.21917], "long": [6.56667]})) +``` + +Such an object is streamed into an unpartitioned table, and read into memory as a `pa.Table` for a partitioned one. + +Scans implement the same interface, so any Arrow consumer can read one directly: + +```python +df = pl.DataFrame(tbl.scan(row_filter="lat > 50")) +``` + ### Partial overwrites When using the `overwrite` API, you can use an `overwrite_filter` to delete data that matches the filter before appending new data into the table. For example, consider the following Iceberg table: diff --git a/pyiceberg/table/__init__.py b/pyiceberg/table/__init__.py index 58d737b9e9..130adf335b 100644 --- a/pyiceberg/table/__init__.py +++ b/pyiceberg/table/__init__.py @@ -561,7 +561,7 @@ def append( """ Shorthand API for appending PyArrow data to a table transaction. - Accepts either a fully materialised ``pa.Table`` or a streaming + Accepts a fully materialised ``pa.Table`` or a streaming ``pa.RecordBatchReader``. Streaming is microbatched by ``write.target-file-size-bytes`` so memory stays bounded; the reader is consumed once and cannot be reused. @@ -571,6 +571,11 @@ def append( ``NotImplementedError``. See https://github.com/apache/iceberg-python/issues/2152. + Any other object implementing the Arrow PyCapsule stream interface + (``__arrow_c_stream__``), such as a Polars DataFrame, is accepted as + well. It is streamed into an unpartitioned table and read into memory + for a partitioned one. + Note: When ``df`` is a ``pa.RecordBatchReader`` the reader is consumed once and cannot be replayed. If the catalog commit fails (e.g. @@ -598,7 +603,7 @@ def append( rolling-``ParquetWriter`` with ``OutputStream.tell()`` (#2998). Args: - df: An Arrow Table or a RecordBatchReader of records to append. + df: An Arrow Table, RecordBatchReader or PyCapsule stream of records to append. snapshot_properties: Custom properties to be added to the snapshot summary branch: Branch Reference to run the append operation """ @@ -708,7 +713,7 @@ def overwrite( """ Shorthand for adding a table overwrite with a PyArrow table or RecordBatchReader to the transaction. - Accepts either a fully materialised ``pa.Table`` or a streaming + Accepts a fully materialised ``pa.Table`` or a streaming ``pa.RecordBatchReader``. Streaming is microbatched by ``write.target-file-size-bytes`` so memory stays bounded; the reader is consumed once and cannot be reused. @@ -718,6 +723,11 @@ def overwrite( ``NotImplementedError``. See https://github.com/apache/iceberg-python/issues/2152. + Any other object implementing the Arrow PyCapsule stream interface + (``__arrow_c_stream__``), such as a Polars DataFrame, is accepted as + well. It is streamed into an unpartitioned table and read into memory + for a partitioned one. + Note: When ``df`` is a ``pa.RecordBatchReader`` the reader is consumed once and cannot be replayed. If the catalog commit fails (e.g. @@ -751,7 +761,7 @@ def overwrite( - APPEND: In case new data is being inserted into the table. Args: - df: An Arrow Table or a RecordBatchReader of records to write. + df: An Arrow Table, RecordBatchReader or PyCapsule stream of records to write. overwrite_filter: ALWAYS_TRUE when you overwrite all the data, or a boolean expression in case of a partial overwrite snapshot_properties: Custom properties to be added to the snapshot summary @@ -1852,12 +1862,13 @@ def append( """ Shorthand API for appending PyArrow data to the table. - Accepts either a ``pa.Table`` or a streaming ``pa.RecordBatchReader``. - See :meth:`Transaction.append` for streaming semantics and partition + Accepts a ``pa.Table``, a streaming ``pa.RecordBatchReader`` or any other + object implementing the Arrow PyCapsule stream interface. See + :meth:`Transaction.append` for streaming semantics and partition limitations. Args: - df: An Arrow Table or a RecordBatchReader of records to append. + df: An Arrow Table, RecordBatchReader or PyCapsule stream of records to append. snapshot_properties: Custom properties to be added to the snapshot summary branch: Branch Reference to run the append operation """ @@ -1889,8 +1900,9 @@ def overwrite( """ Shorthand for overwriting the table with a PyArrow Table or RecordBatchReader. - Accepts either a ``pa.Table`` or a streaming ``pa.RecordBatchReader``. - See :meth:`Transaction.overwrite` for streaming semantics and partition + Accepts a ``pa.Table``, a streaming ``pa.RecordBatchReader`` or any other + object implementing the Arrow PyCapsule stream interface. See + :meth:`Transaction.overwrite` for streaming semantics and partition limitations. An overwrite may produce zero or more snapshots based on the operation: @@ -1900,7 +1912,7 @@ def overwrite( - APPEND: In case new data is being inserted into the table. Args: - df: An Arrow Table or a RecordBatchReader of records to write. + df: An Arrow Table, RecordBatchReader or PyCapsule stream of records to write. overwrite_filter: ALWAYS_TRUE when you overwrite all the data, or a boolean expression in case of a partial overwrite snapshot_properties: Custom properties to be added to the snapshot summary diff --git a/pyiceberg/typedef.py b/pyiceberg/typedef.py index d520f10def..58735f6e62 100644 --- a/pyiceberg/typedef.py +++ b/pyiceberg/typedef.py @@ -113,7 +113,6 @@ def __setitem__(self, pos: int, value: Any) -> None: """Assign a value to a StructProtocol.""" -@runtime_checkable class ArrowStreamExportable(Protocol): # pragma: no cover """Any object implementing the Arrow PyCapsule stream interface. From 5240aa58efab4a6341b5d102dd70cbcdc40e922b Mon Sep 17 00:00:00 2001 From: Abanoub Doss Date: Wed, 25 Nov 2026 19:35:03 -0600 Subject: [PATCH 10/10] fix: clean up arrow c stream comments, docs and duplicate view cast --- mkdocs/docs/api.md | 4 +- pyiceberg/io/pyarrow.py | 14 ++-- pyiceberg/table/__init__.py | 4 +- tests/io/test_pyarrow.py | 4 ++ tests/table/test_arrow_capsule.py | 105 ++++++++---------------------- 5 files changed, 41 insertions(+), 90 deletions(-) diff --git a/mkdocs/docs/api.md b/mkdocs/docs/api.md index 518d8e15e6..d0d6d08332 100644 --- a/mkdocs/docs/api.md +++ b/mkdocs/docs/api.md @@ -418,7 +418,9 @@ import polars as pl tbl.append(pl.DataFrame({"city": ["Groningen"], "lat": [53.21917], "long": [6.56667]})) ``` -Such an object is streamed into an unpartitioned table, and read into memory as a `pa.Table` for a partitioned one. +Such an object is streamed into an unpartitioned table, and read into memory as a `pa.Table` for a partitioned one. A streamed batch is never split, so a dataframe that exports one large batch is written as one file. + +The stream's schema must match the table's, including nullability. Polars exports every column as optional, so a Polars dataframe cannot be written to a table with required fields. Scans implement the same interface, so any Arrow consumer can read one directly: diff --git a/pyiceberg/io/pyarrow.py b/pyiceberg/io/pyarrow.py index f6c302a723..304be94ac5 100644 --- a/pyiceberg/io/pyarrow.py +++ b/pyiceberg/io/pyarrow.py @@ -3369,10 +3369,11 @@ def _dataframe_to_data_files( property_name=TableProperties.WRITE_TARGET_FILE_SIZE_BYTES, default=TableProperties.WRITE_TARGET_FILE_SIZE_BYTES_DEFAULT, ) - # Cast view types to plain string and binary. PyArrow cannot yet filter - # on view types or combine them with the plain columns of other data - # files, so a table written with them could not be scanned with a filter - # or deleted from. This cast can be removed once PyArrow supports both. + # Cast view types to large_string and large_binary. PyArrow cannot yet + # filter on view types or combine them with the string and binary columns + # of other data files, so a table written with them could not be scanned + # with a filter or deleted from. This cast can be removed once PyArrow + # supports both. arrow_schema = visit_pyarrow(df.schema, _ConvertViewTypes()) if arrow_schema != df.schema: df = df.cast(arrow_schema) @@ -3451,11 +3452,6 @@ def _determine_partitions(spec: PartitionSpec, schema: Schema, arrow_table: pa.T - Then we produce a set of partitions by filtering on each of the combinations - We combine the chunks to create a copy to avoid GIL congestion on the original table """ - # PyArrow has no group by, filter or take kernels for view types, so replace them with their large counterparts - arrow_schema = visit_pyarrow(arrow_table.schema, _ConvertViewTypes()) - if arrow_schema != arrow_table.schema: - arrow_table = arrow_table.cast(arrow_schema) - # Assign unique names to columns where the partition transform has been applied # to avoid conflicts with the data columns partition_fields: list[str] = [] diff --git a/pyiceberg/table/__init__.py b/pyiceberg/table/__init__.py index 130adf335b..a96d67c6a0 100644 --- a/pyiceberg/table/__init__.py +++ b/pyiceberg/table/__init__.py @@ -2709,7 +2709,7 @@ def to_arrow_batch_reader(self, dictionary_columns: tuple[str, ...] = ()) -> pa. def __arrow_c_stream__(self, requested_schema: object | None = None) -> object: """Export this scan's result as an Arrow C stream (PyCapsule interface). - We must drop field IDs, as to_arrow() does. They only have meaning + Field IDs are dropped, as in to_arrow(). They only have meaning inside this table, and a write to another table would match columns by them. """ @@ -2898,7 +2898,7 @@ def to_arrow_batch_reader(self) -> pa.RecordBatchReader: def __arrow_c_stream__(self, requested_schema: object | None = None) -> object: """Export this scan's result as an Arrow C stream (PyCapsule interface). - We must drop field IDs, as to_arrow() does. They only have meaning + Field IDs are dropped, as in to_arrow(). They only have meaning inside this table, and a write to another table would match columns by them. """ diff --git a/tests/io/test_pyarrow.py b/tests/io/test_pyarrow.py index f2758b4921..113f09f6e8 100644 --- a/tests/io/test_pyarrow.py +++ b/tests/io/test_pyarrow.py @@ -85,6 +85,7 @@ StatsAggregator, _check_pyarrow_schema_compatible, _ConvertToArrowSchema, + _ConvertViewTypes, _create_arrow_read_format, _determine_partitions, _primitive_to_physical, @@ -99,6 +100,7 @@ expression_to_pyarrow, parquet_path_to_id_mapping, schema_to_pyarrow, + visit_pyarrow, write_file, ) from pyiceberg.manifest import DataFile, DataFileContent, FileFormat, ManifestEntry, ManifestEntryStatus @@ -3580,6 +3582,8 @@ def test_determine_partitions_with_view_types(transform: Transform[Any, Any]) -> {"region": None, "payload": b"c", "info": {"tags": ["y", None], "attrs": []}}, ] arrow_table = pa.Table.from_pylist(rows, schema=arrow_schema) + # View types are cast before the table is split into partitions + arrow_table = arrow_table.cast(visit_pyarrow(arrow_schema, _ConvertViewTypes())) partitions = list(_determine_partitions(spec, schema, arrow_table)) diff --git a/tests/table/test_arrow_capsule.py b/tests/table/test_arrow_capsule.py index 192b2653ff..4ca8b3db35 100644 --- a/tests/table/test_arrow_capsule.py +++ b/tests/table/test_arrow_capsule.py @@ -14,12 +14,7 @@ # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. -"""Tests for Arrow PyCapsule interface support on the read and write paths. - -Covers the input/consumer side (write methods accept any object implementing -``__arrow_c_stream__``) and the output/producer side (scans expose -``__arrow_c_stream__`` so any Arrow consumer can ingest them). -""" +"""Tests for Arrow PyCapsule stream input on writes and export from scans.""" from collections.abc import Iterator from pathlib import PosixPath @@ -38,12 +33,6 @@ NestedField(1, "id", IntegerType(), required=False), NestedField(2, "region", StringType(), required=False), ) -ARROW_SCHEMA = pa.schema( - [ - pa.field("id", pa.int32(), nullable=True), - pa.field("region", pa.string(), nullable=True), - ] -) PARTITION_SPEC = PartitionSpec(PartitionField(source_id=2, field_id=1000, transform=IdentityTransform(), name="region")) @@ -69,32 +58,27 @@ def catalog(tmp_path: PosixPath) -> InMemoryCatalog: return catalog -def _data(ids: list[int], regions: list[str]) -> pa.Table: - return pa.table({"id": pa.array(ids, type=pa.int32()), "region": regions}, schema=ARROW_SCHEMA) +def _data(ids: list[int], regions: list[str], region_type: pa.DataType | None = None) -> pa.Table: + return pa.table({"id": pa.array(ids, type=pa.int32()), "region": pa.array(regions, type=region_type or pa.string())}) -def _string_view_data(ids: list[int], regions: list[str]) -> pa.Table: - return pa.table( - {"id": pa.array(ids, type=pa.int32()), "region": pa.array(regions, type=pa.string_view())}, - schema=pa.schema( - [ - pa.field("id", pa.int32(), nullable=True), - pa.field("region", pa.string_view(), nullable=True), - ] - ), - ) +def _counting_reader(table: pa.Table) -> tuple[pa.RecordBatchReader, list[pa.RecordBatch]]: + """Return a one-row-per-batch reader over the table and the list of batches pulled from it so far.""" + pulled: list[pa.RecordBatch] = [] + def batches() -> Iterator[pa.RecordBatch]: + for batch in table.to_batches(max_chunksize=1): + pulled.append(batch) + yield batch -def _rows(table: pa.Table) -> list[dict[str, Any]]: - return sorted(table.to_pylist(), key=lambda r: r["id"]) + return pa.RecordBatchReader.from_batches(table.schema, batches()), pulled -# --------------------------------------------------------------------------- -# Input / consumer side (issue #2680) -# --------------------------------------------------------------------------- +def _rows(table: pa.Table) -> list[dict[str, Any]]: + return sorted(table.to_pylist(), key=lambda r: r["id"]) -def test_append_accepts_arrow_capsule(catalog: InMemoryCatalog) -> None: +def test_append_and_overwrite_accept_arrow_capsule(catalog: InMemoryCatalog) -> None: data = _data([1, 2, 3], ["us", "eu", "us"]) # A stream of several batches must be fully drained. @@ -105,21 +89,17 @@ def test_append_accepts_arrow_capsule(catalog: InMemoryCatalog) -> None: assert _rows(tbl.scan().to_arrow()) == _rows(data), name - -def test_overwrite_accepts_arrow_capsule(catalog: InMemoryCatalog) -> None: - tbl = catalog.create_table("default.overwrite_capsule", schema=SCHEMA) - tbl.append(_data([1, 2], ["us", "eu"])) - tbl.overwrite(_ArrowStreamWrapper(_data([9], ["jp"]))) assert _rows(tbl.scan().to_arrow()) == _rows(_data([9], ["jp"])) -def test_append_accepts_arrow_capsule_with_string_view(catalog: InMemoryCatalog) -> None: - """Regression: Polars exports string columns as string_view over PyCapsule.""" - tbl = catalog.create_table("default.append_string_view", schema=SCHEMA) +def test_append_accepts_polars_dataframe(catalog: InMemoryCatalog) -> None: + import polars as pl - tbl.append(_ArrowStreamWrapper(_string_view_data([10, 11], ["ca", "mx"]))) + tbl = catalog.create_table("default.append_polars", schema=SCHEMA) + + tbl.append(pl.DataFrame({"id": [10, 11], "region": ["ca", "mx"]}, schema={"id": pl.Int32, "region": pl.String})) assert _rows(tbl.scan().to_arrow()) == _rows(_data([10, 11], ["ca", "mx"])) assert _rows(tbl.scan(row_filter="region == 'ca'").to_arrow()) == _rows(_data([10], ["ca"])) @@ -128,7 +108,7 @@ def test_append_accepts_arrow_capsule_with_string_view(catalog: InMemoryCatalog) def test_append_arrow_capsule_to_partitioned_table(catalog: InMemoryCatalog) -> None: tbl = catalog.create_table("default.append_capsule_partitioned", schema=SCHEMA, partition_spec=PARTITION_SPEC) - tbl.append(_ArrowStreamWrapper(_string_view_data([1, 2, 3], ["us", "eu", "us"]))) + tbl.append(_ArrowStreamWrapper(_data([1, 2, 3], ["us", "eu", "us"], pa.string_view()))) assert len(tbl.inspect.partitions()) == 2 assert _rows(tbl.scan().to_arrow()) == _rows(_data([1, 2, 3], ["us", "eu", "us"])) @@ -137,47 +117,28 @@ def test_append_arrow_capsule_to_partitioned_table(catalog: InMemoryCatalog) -> def test_arrow_capsule_is_streamed_into_an_unpartitioned_table_only(catalog: InMemoryCatalog) -> None: data = _data([1, 2, 3], ["us", "eu", "us"]) - for name, spec, expected in ( - ("unpartitioned", UNPARTITIONED_PARTITION_SPEC, pa.RecordBatchReader), - ("partitioned", PARTITION_SPEC, pa.Table), - ): + for name, spec, expected in (("unpartitioned", UNPARTITIONED_PARTITION_SPEC, 0), ("partitioned", PARTITION_SPEC, 3)): tbl = catalog.create_table(f"default.streamed_{name}", schema=SCHEMA, partition_spec=spec) + reader, pulled = _counting_reader(data) + + tbl.transaction()._prepare_arrow_input(_ArrowStreamWrapper(reader)) - assert isinstance(tbl.transaction()._prepare_arrow_input(_ArrowStreamWrapper(data)), expected), name + assert len(pulled) == expected, name def test_append_checks_schema_before_reading_arrow_capsule(catalog: InMemoryCatalog) -> None: - pulled: list[pa.RecordBatch] = [] mismatched = pa.table({"id": ["a", "b"], "region": ["us", "eu"]}) - def batches() -> Iterator[pa.RecordBatch]: - for batch in mismatched.to_batches(max_chunksize=1): - pulled.append(batch) - yield batch - for name, spec in (("unpartitioned", UNPARTITIONED_PARTITION_SPEC), ("partitioned", PARTITION_SPEC)): tbl = catalog.create_table(f"default.schema_check_{name}", schema=SCHEMA, partition_spec=spec) + reader, pulled = _counting_reader(mismatched) with pytest.raises(ValueError, match="Mismatch in fields"): - tbl.append(_ArrowStreamWrapper(pa.RecordBatchReader.from_batches(mismatched.schema, batches()))) + tbl.append(_ArrowStreamWrapper(reader)) assert not pulled, name -# --------------------------------------------------------------------------- -# Output / producer side (issue #1655) -# --------------------------------------------------------------------------- - - -def test_scan_supports_arrow_c_stream(catalog: InMemoryCatalog) -> None: - tbl = catalog.create_table("default.stream", schema=SCHEMA) - tbl.append(_data([1, 2, 3], ["us", "eu", "us"])) - - consumed = pa.table(tbl.scan()) - - assert _rows(consumed) == _rows(tbl.scan().to_arrow()) - - def test_scan_arrow_c_stream_respects_filter_projection_and_limit(catalog: InMemoryCatalog) -> None: tbl = catalog.create_table("default.scan_stream_filtered", schema=SCHEMA) tbl.append(_data([1, 2, 3], ["us", "eu", "us"])) @@ -190,18 +151,6 @@ def test_scan_arrow_c_stream_respects_filter_projection_and_limit(catalog: InMem assert pa.table(scan.update(limit=1)).num_rows == 1 -def test_capsule_roundtrip_scan_into_append(catalog: InMemoryCatalog) -> None: - """The two halves compose: a scan (producer) can be appended into another - table (consumer) with no explicit pyarrow conversion in between.""" - src = catalog.create_table("default.roundtrip_src", schema=SCHEMA) - src.append(_data([1, 2, 3], ["us", "eu", "us"])) - dst = catalog.create_table("default.roundtrip_dst", schema=SCHEMA) - - dst.append(src.scan()) - - assert _rows(dst.scan().to_arrow()) == _rows(src.scan().to_arrow()) - - def test_scan_arrow_c_stream_casts_to_requested_schema(catalog: InMemoryCatalog) -> None: tbl = catalog.create_table("default.stream_requested_schema", schema=SCHEMA) tbl.append(_data([1, 2, 3], ["us", "eu", "us"]))