This is an automated email from the ASF dual-hosted git repository.
github-merge-queue[bot] pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/iceberg-rust.git
The following commit(s) were added to refs/heads/main by this push:
new 641f59049 feat(python): read manifests and manifest lists as pyarrow
RecordBatchReaders (#3652)
641f59049 is described below
commit 641f59049e0aefad0c60e19915ecdb54933e002f
Author: Matt Butrovich <[email protected]>
AuthorDate: Wed Nov 18 19:05:07 2026 +0000
feat(python): read manifests and manifest lists as pyarrow
RecordBatchReaders (#3652)
* feat(python): read manifests and manifest lists as pyarrow
RecordBatchReaders
* docs(python): document raised errors and input release for the Arrow
readers
* Address review feedback on the Arrow manifest readers
- Drop the unused manifest_length, partition_spec_id, and
min_sequence_number arguments from read_manifest_entries_as_arrow.
- Share decoding, projection, and stop-after-error between the two
readers through a private ProjectingReader.
- Restore the original schema wording in the reader docs.
- Check for multiple batches instead of the batch size constant in the
Python test.
Co-authored-by: Copilot App <[email protected]>
* Remove the empty partition workaround now that arrow-avro decodes empty
records
arrow-avro 60 decodes records with no fields (apache/arrow-rs#10771), so the
entry reader no longer projects out the empty partition of unpartitioned
manifests. It now reads the header from its own reader instead of a separate
borrowing one.
Co-authored-by: Copilot App <[email protected]>
* Document that the Arrow manifest readers take decrypted bytes
* Rename the Arrow manifest bindings to *_as_arrow_reader
Co-authored-by: Copilot App <[email protected]>
---------
Co-authored-by: Kevin Liu <[email protected]>
Co-authored-by: Copilot App <[email protected]>
---
bindings/python/src/manifest.rs | 96 ++++-
bindings/python/tests/test_manifest.py | 255 +++++++++++++
crates/iceberg/public-api.txt | 16 +-
crates/iceberg/src/arrow/manifest.rs | 653 ++++++++++++++++++++++-----------
crates/iceberg/src/arrow/mod.rs | 4 +-
5 files changed, 812 insertions(+), 212 deletions(-)
diff --git a/bindings/python/src/manifest.rs b/bindings/python/src/manifest.rs
index 15b80c3e3..4ff912b4b 100644
--- a/bindings/python/src/manifest.rs
+++ b/bindings/python/src/manifest.rs
@@ -17,10 +17,17 @@
use std::sync::Arc;
+use arrow::array::RecordBatch;
+use arrow::datatypes::SchemaRef;
+use arrow::error::ArrowError;
+use arrow::pyarrow::IntoPyArrow;
+use arrow::record_batch::{RecordBatchIterator, RecordBatchReader};
use iceberg::spec::{
- FieldSummary, FormatVersion, Manifest, ManifestEntry, ManifestFile,
ManifestList,
+ FieldSummary, FormatVersion, Manifest, ManifestContentType, ManifestEntry,
ManifestFile,
+ ManifestList,
};
use pyo3::prelude::*;
+use pyo3::pybacked::PyBackedBytes;
use crate::data_file::PyDataFile;
use crate::error::to_py_err;
@@ -226,11 +233,98 @@ pub fn read_manifest_list(bs: &[u8]) ->
PyResult<PyManifestList> {
})
}
+/// Reads the entries of a manifest as a `pyarrow.RecordBatchReader`.
+///
+/// The other arguments come from the manifest's entry in the manifest list,
+/// which the entries inherit snapshot IDs, sequence numbers, and first row IDs
+/// from. `bs` must be decrypted if the manifest list entry has key metadata.
+/// Raises `ValueError` for an invalid manifest header, which includes
+/// encrypted bytes. An error while
+/// reading raises `pyarrow.ArrowInvalid`, which subclasses `ValueError`. The
+/// reader holds a reference to `bs` until it's closed or collected, and the
+/// next call into `pyiceberg_core` releases it.
+#[pyfunction]
+#[pyo3(signature = (
+ bs,
+ *,
+ manifest_path,
+ content,
+ sequence_number,
+ added_snapshot_id,
+ first_row_id = None,
+))]
+pub fn read_manifest_entries_as_arrow_reader(
+ py: Python<'_>,
+ bs: PyBackedBytes,
+ manifest_path: String,
+ content: i32,
+ sequence_number: i64,
+ added_snapshot_id: i64,
+ first_row_id: Option<u64>,
+) -> PyResult<Bound<'_, PyAny>> {
+ // Inheritance reads only the fields set from the arguments.
+ let manifest_file = ManifestFile {
+ manifest_path,
+ manifest_length: 0,
+ partition_spec_id: 0,
+ content: ManifestContentType::try_from(content).map_err(to_py_err)?,
+ sequence_number,
+ min_sequence_number: 0,
+ added_snapshot_id,
+ added_files_count: None,
+ existing_files_count: None,
+ deleted_files_count: None,
+ added_rows_count: None,
+ existing_rows_count: None,
+ deleted_rows_count: None,
+ partitions: None,
+ key_metadata: None,
+ first_row_id,
+ };
+ let reader = iceberg::arrow::read_manifest_entries(bs,
&manifest_file).map_err(to_py_err)?;
+ into_pyarrow_reader(py, reader.schema(), reader)
+}
+
+/// Reads the entries of a manifest list as a `pyarrow.RecordBatchReader`.
+///
+/// `bs` must be decrypted if the snapshot has an encryption key ID. Raises
+/// `ValueError` for an invalid manifest list header, which includes encrypted
+/// bytes. An error while
+/// reading raises `pyarrow.ArrowInvalid`, which subclasses `ValueError`. The
+/// reader holds a reference to `bs` until it's closed or collected, and the
+/// next call into `pyiceberg_core` releases it.
+#[pyfunction]
+pub fn read_manifest_list_as_arrow_reader(
+ py: Python<'_>,
+ bs: PyBackedBytes,
+) -> PyResult<Bound<'_, PyAny>> {
+ let reader = iceberg::arrow::read_manifest_list(bs).map_err(to_py_err)?;
+ into_pyarrow_reader(py, reader.schema(), reader)
+}
+
+/// Exports `batches` through the Arrow C stream interface.
+fn into_pyarrow_reader<'py>(
+ py: Python<'py>,
+ schema: SchemaRef,
+ batches: impl Iterator<Item = iceberg::Result<RecordBatch>> + Send +
'static,
+) -> PyResult<Bound<'py, PyAny>> {
+ let batches =
+ batches.map(|batch| batch.map_err(|err|
ArrowError::ExternalError(Box::new(err))));
+ let reader: Box<dyn RecordBatchReader + Send> =
+ Box::new(RecordBatchIterator::new(batches, schema));
+ reader.into_pyarrow(py)
+}
+
pub fn register_module(py: Python<'_>, m: &Bound<'_, PyModule>) ->
PyResult<()> {
let this = PyModule::new(py, "manifest")?;
this.add_function(wrap_pyfunction!(read_manifest_entries, &this)?)?;
this.add_function(wrap_pyfunction!(read_manifest_list, &this)?)?;
+ this.add_function(wrap_pyfunction!(
+ read_manifest_entries_as_arrow_reader,
+ &this
+ )?)?;
+ this.add_function(wrap_pyfunction!(read_manifest_list_as_arrow_reader,
&this)?)?;
m.add_submodule(&this)?;
py.import("sys")?
diff --git a/bindings/python/tests/test_manifest.py
b/bindings/python/tests/test_manifest.py
index 147b81fcc..3ef94fabd 100644
--- a/bindings/python/tests/test_manifest.py
+++ b/bindings/python/tests/test_manifest.py
@@ -15,9 +15,12 @@
# specific language governing permissions and limitations
# under the License.
+import struct
+import sys
from pathlib import Path
from typing import Any
+import pyarrow as pa
import pytest
from pyiceberg.io import FileIO
from pyiceberg.io.pyarrow import PyArrowFileIO
@@ -25,12 +28,20 @@ from pyiceberg.manifest import (
DataFile,
DataFileContent,
FileFormat,
+ ManifestContent,
ManifestEntry,
ManifestEntryStatus,
ManifestFile,
_manifests,
+ read_manifest_list,
+ write_manifest,
write_manifest_list,
)
+from pyiceberg.partitioning import PartitionField, PartitionSpec
+from pyiceberg.schema import Schema
+from pyiceberg.transforms import IdentityTransform
+from pyiceberg.typedef import Record
+from pyiceberg.types import LongType, NestedField, StringType
@pytest.fixture(autouse=True)
@@ -235,3 +246,247 @@ def
test_manifest_file_without_partition_summaries(tmp_path: Path) -> None:
manifest_file = manifest.read_manifest_list(bs).entries()[0]
assert manifest_file.partitions is None
+
+
+SNAPSHOT_ID = 25
+
+
+def _write_manifest(tmp_path: Path, num_files: int) -> tuple[bytes,
ManifestFile]:
+ """Writes a v2 manifest whose entries inherit their sequence numbers."""
+ schema = Schema(
+ NestedField(1, "id", LongType(), required=False),
+ NestedField(2, "name", StringType(), required=False),
+ )
+ spec = PartitionSpec(
+ PartitionField(
+ source_id=1, field_id=1000, transform=IdentityTransform(),
name="id"
+ ),
+ spec_id=0,
+ )
+ path = str(tmp_path / "manifest.avro")
+ io = PyArrowFileIO()
+ with write_manifest(
+ format_version=2,
+ spec=spec,
+ schema=schema,
+ output_file=io.new_output(path),
+ snapshot_id=SNAPSHOT_ID,
+ avro_compression="deflate",
+ ) as writer:
+ for i in range(num_files):
+ writer.add(
+ ManifestEntry.from_args(
+ status=ManifestEntryStatus.ADDED,
+ snapshot_id=SNAPSHOT_ID,
+ data_file=DataFile.from_args(
+ content=DataFileContent.DATA,
+ file_path=f"s3://bucket/data/{i}.parquet",
+ file_format=FileFormat.PARQUET,
+ partition=Record(i),
+ record_count=10 + i,
+ file_size_in_bytes=100,
+ column_sizes={1: 8, 2: 16},
+ value_counts={1: 10 + i, 2: 10 + i},
+ null_value_counts={1: 0, 2: i},
+ nan_value_counts={},
+ lower_bounds={1: struct.pack("<q", i)},
+ upper_bounds={1: struct.pack("<q", i)},
+ split_offsets=[4],
+ sort_order_id=0,
+ ),
+ )
+ )
+ manifest_file = ManifestFile.from_args(
+ manifest_path=path,
+ manifest_length=writer.to_manifest_file().manifest_length,
+ partition_spec_id=0,
+ content=ManifestContent.DATA,
+ sequence_number=5,
+ min_sequence_number=5,
+ added_snapshot_id=SNAPSHOT_ID,
+ )
+ return io.new_input(path).open().read(), manifest_file
+
+
+def _read_entries(
+ bs: bytes, manifest_file: ManifestFile, first_row_id: int | None = None
+) -> pa.RecordBatchReader:
+ from pyiceberg_core import manifest
+
+ return manifest.read_manifest_entries_as_arrow_reader(
+ bs,
+ manifest_path=manifest_file.manifest_path,
+ content=manifest_file.content.value,
+ sequence_number=manifest_file.sequence_number,
+ added_snapshot_id=manifest_file.added_snapshot_id,
+ first_row_id=first_row_id,
+ )
+
+
+def test_read_manifest_entries_as_arrow_reader_matches_pyiceberg(
+ tmp_path: Path,
+) -> None:
+ bs, manifest_file = _write_manifest(tmp_path, 3)
+ reader = _read_entries(bs, manifest_file)
+ assert isinstance(reader, pa.RecordBatchReader)
+
+ rows = reader.read_all().to_pylist()
+ expected = manifest_file.fetch_manifest_entry(
+ PyArrowFileIO(), discard_deleted=False
+ )
+ assert [
+ {
+ "status": row["status"],
+ "snapshot_id": row["snapshot_id"],
+ "sequence_number": row["sequence_number"],
+ "file_sequence_number": row["file_sequence_number"],
+ "file_path": row["data_file"]["file_path"],
+ "partition": row["data_file"]["partition"]["id"],
+ "record_count": row["data_file"]["record_count"],
+ "null_value_counts": dict(row["data_file"]["null_value_counts"]),
+ "lower_bounds": dict(row["data_file"]["lower_bounds"]),
+ }
+ for row in rows
+ ] == [
+ {
+ "status": entry.status.value,
+ "snapshot_id": entry.snapshot_id,
+ "sequence_number": entry.sequence_number,
+ "file_sequence_number": entry.file_sequence_number,
+ "file_path": entry.data_file.file_path,
+ "partition": entry.data_file.partition[0],
+ "record_count": entry.data_file.record_count,
+ "null_value_counts": entry.data_file.null_value_counts,
+ "lower_bounds": entry.data_file.lower_bounds,
+ }
+ for entry in expected
+ ]
+
+
+def test_read_manifest_entries_as_arrow_reader_yields_multiple_batches(
+ tmp_path: Path,
+) -> None:
+ bs, manifest_file = _write_manifest(tmp_path, 2500)
+ batches = list(_read_entries(bs, manifest_file))
+ assert len(batches) > 1
+ assert sum(batch.num_rows for batch in batches) == 2500
+
+
+def test_read_manifest_entries_as_arrow_reader_releases_input_on_close(
+ tmp_path: Path,
+) -> None:
+ from pyiceberg_core import transform
+
+ bs, manifest_file = _write_manifest(tmp_path, 3)
+ refcount = sys.getrefcount(bs)
+ reader = _read_entries(bs, manifest_file)
+ assert sys.getrefcount(bs) == refcount + 1
+
+ # pyarrow releases the stream without PyO3 attached to the interpreter, so
+ # PyO3 defers the decref to its next call.
+ reader.close()
+ transform.identity(pa.array([1]))
+ assert sys.getrefcount(bs) == refcount
+
+
+def test_read_manifest_entries_as_arrow_reader_batches_outlive_reader(
+ tmp_path: Path,
+) -> None:
+ bs, manifest_file = _write_manifest(tmp_path, 3)
+ reader = _read_entries(bs, manifest_file)
+ batch = reader.read_next_batch()
+ reader.close()
+ del reader, bs
+
+ assert batch.column("data_file").field("file_path").to_pylist() == [
+ f"s3://bucket/data/{i}.parquet" for i in range(3)
+ ]
+
+
+def test_read_manifest_entries_as_arrow_reader_raises_while_reading(
+ tmp_path: Path,
+) -> None:
+ bs, manifest_file = _write_manifest(tmp_path, 3)
+ # Assigning first row IDs to the second entry overflows i64.
+ reader = _read_entries(bs, manifest_file, first_row_id=2**63 - 15)
+
+ with pytest.raises(pa.ArrowInvalid, match="row ID overflow"):
+ reader.read_next_batch()
+
+
[email protected](
+ "payload", [b"", b"not-an-avro-file",
b"Obj\x01truncated-after-the-avro-magic"]
+)
+def test_read_manifest_entries_as_arrow_reader_raises_on_invalid_avro(
+ tmp_path: Path, payload: bytes
+) -> None:
+ _, manifest_file = _write_manifest(tmp_path, 1)
+ with pytest.raises(ValueError):
+ _read_entries(payload, manifest_file)
+
+
[email protected]("format_version", [1, 2])
+def test_read_manifest_list_as_arrow_reader_matches_pyiceberg(
+ tmp_path: Path, format_version: int
+) -> None:
+ from pyiceberg_core import manifest
+
+ path = str(tmp_path / "snap.avro")
+ io = PyArrowFileIO()
+ with write_manifest_list(
+ format_version=format_version,
+ output_file=io.new_output(path),
+ snapshot_id=SNAPSHOT_ID,
+ parent_snapshot_id=None,
+ sequence_number=7,
+ avro_compression="deflate",
+ ) as writer:
+ writer.add_manifests(
+ [
+ ManifestFile.from_args(
+ manifest_path=f"s3://bucket/metadata/{i}.avro",
+ manifest_length=1024,
+ partition_spec_id=0,
+ added_snapshot_id=SNAPSHOT_ID,
+ sequence_number=-1,
+ min_sequence_number=-1,
+ added_files_count=i,
+ existing_files_count=0,
+ deleted_files_count=0,
+ added_rows_count=10 * i,
+ existing_rows_count=0,
+ deleted_rows_count=0,
+ )
+ for i in range(2)
+ ]
+ )
+
+ reader = manifest.read_manifest_list_as_arrow_reader(
+ io.new_input(path).open().read()
+ )
+ assert isinstance(reader, pa.RecordBatchReader)
+ rows = reader.read_all().to_pylist()
+ expected = list(read_manifest_list(io.new_input(path)))
+ fields = [
+ "manifest_path",
+ "sequence_number",
+ "min_sequence_number",
+ "added_snapshot_id",
+ "added_files_count",
+ "added_rows_count",
+ ]
+ assert [{f: row[f] for f in fields} for row in rows] == [
+ {f: getattr(manifest_file, f) for f in fields} for manifest_file in
expected
+ ]
+
+
[email protected](
+ "payload", [b"", b"not-an-avro-file",
b"Obj\x01truncated-after-the-avro-magic"]
+)
+def test_read_manifest_list_as_arrow_reader_raises_on_invalid_avro(
+ payload: bytes,
+) -> None:
+ from pyiceberg_core import manifest
+
+ with pytest.raises(ValueError):
+ manifest.read_manifest_list_as_arrow_reader(payload)
diff --git a/crates/iceberg/public-api.txt b/crates/iceberg/public-api.txt
index 968e39c39..6dd6bd5f3 100644
--- a/crates/iceberg/public-api.txt
+++ b/crates/iceberg/public-api.txt
@@ -96,6 +96,18 @@ impl serde_core::ser::Serialize for
iceberg::arrow::ArrowReaderOptions
pub fn iceberg::arrow::ArrowReaderOptions::serialize<__S>(&self, __serializer:
__S) -> core::result::Result<<__S as serde_core::ser::Serializer>::Ok, <__S as
serde_core::ser::Serializer>::Error> where __S: serde_core::ser::Serializer
impl<'de> serde_core::de::Deserialize<'de> for
iceberg::arrow::ArrowReaderOptions where iceberg::arrow::ArrowReaderOptions:
core::default::Default
pub fn iceberg::arrow::ArrowReaderOptions::deserialize<__D>(__deserializer:
__D) -> core::result::Result<Self, <__D as
serde_core::de::Deserializer>::Error> where __D:
serde_core::de::Deserializer<'de>
+pub struct iceberg::arrow::ManifestEntryBatchReader<B:
core::convert::AsRef<[u8]>>
+impl<B: core::convert::AsRef<[u8]>> iceberg::arrow::ManifestEntryBatchReader<B>
+pub fn iceberg::arrow::ManifestEntryBatchReader<B>::schema(&self) ->
arrow_schema::schema::SchemaRef
+impl<B: core::convert::AsRef<[u8]>> core::iter::traits::iterator::Iterator for
iceberg::arrow::ManifestEntryBatchReader<B>
+pub type iceberg::arrow::ManifestEntryBatchReader<B>::Item =
core::result::Result<arrow_array::record_batch::RecordBatch, iceberg::Error>
+pub fn iceberg::arrow::ManifestEntryBatchReader<B>::next(&mut self) ->
core::option::Option<Self::Item>
+pub struct iceberg::arrow::ManifestListBatchReader<B:
core::convert::AsRef<[u8]>>
+impl<B: core::convert::AsRef<[u8]>> iceberg::arrow::ManifestListBatchReader<B>
+pub fn iceberg::arrow::ManifestListBatchReader<B>::schema(&self) ->
arrow_schema::schema::SchemaRef
+impl<B: core::convert::AsRef<[u8]>> core::iter::traits::iterator::Iterator for
iceberg::arrow::ManifestListBatchReader<B>
+pub type iceberg::arrow::ManifestListBatchReader<B>::Item =
core::result::Result<arrow_array::record_batch::RecordBatch, iceberg::Error>
+pub fn iceberg::arrow::ManifestListBatchReader<B>::next(&mut self) ->
core::option::Option<Self::Item>
pub struct iceberg::arrow::ParquetReadOptions
impl iceberg::arrow::ParquetReadOptions
pub fn iceberg::arrow::ParquetReadOptions::metadata_size_hint(&self) -> usize
@@ -171,8 +183,8 @@ pub fn
iceberg::arrow::arrow_schema_to_schema_auto_assign_ids(schema: &arrow_sch
pub fn iceberg::arrow::arrow_struct_to_literal(struct_array:
&arrow_array::array::ArrayRef, ty: &iceberg::spec::StructType) ->
iceberg::Result<alloc::vec::Vec<core::option::Option<iceberg::spec::Literal>>>
pub fn iceberg::arrow::arrow_type_to_type(ty:
&arrow_schema::datatype::DataType) -> iceberg::Result<iceberg::spec::Type>
pub fn iceberg::arrow::datum_to_arrow_type_with_ree(datum:
&iceberg::spec::Datum) -> arrow_schema::datatype::DataType
-pub fn iceberg::arrow::read_manifest_entries(bytes: &[u8], manifest_file:
&iceberg::spec::ManifestFile) ->
iceberg::Result<arrow_array::record_batch::RecordBatch>
-pub fn iceberg::arrow::read_manifest_list(bytes: &[u8]) ->
iceberg::Result<arrow_array::record_batch::RecordBatch>
+pub fn iceberg::arrow::read_manifest_entries<B:
core::convert::AsRef<[u8]>>(bytes: B, manifest_file:
&iceberg::spec::ManifestFile) ->
iceberg::Result<iceberg::arrow::ManifestEntryBatchReader<B>>
+pub fn iceberg::arrow::read_manifest_list<B:
core::convert::AsRef<[u8]>>(bytes: B) ->
iceberg::Result<iceberg::arrow::ManifestListBatchReader<B>>
pub fn iceberg::arrow::schema_to_arrow_schema(schema: &iceberg::spec::Schema)
-> iceberg::Result<arrow_schema::schema::Schema>
pub fn iceberg::arrow::strip_metadata_from_schema(schema:
&arrow_schema::schema::Schema) -> iceberg::Result<arrow_schema::schema::Schema>
pub fn iceberg::arrow::type_to_arrow_type(ty: &iceberg::spec::Type) ->
iceberg::Result<arrow_schema::datatype::DataType>
diff --git a/crates/iceberg/src/arrow/manifest.rs
b/crates/iceberg/src/arrow/manifest.rs
index 08bd9ed4c..d71aff52a 100644
--- a/crates/iceberg/src/arrow/manifest.rs
+++ b/crates/iceberg/src/arrow/manifest.rs
@@ -18,6 +18,7 @@
//! Reading manifests and manifest lists into Arrow.
use std::collections::HashMap;
+use std::io::Cursor;
use std::sync::Arc;
use arrow_arith::boolean::{and, is_null};
@@ -29,10 +30,9 @@ use arrow_array::{
StructArray, new_null_array,
};
use arrow_avro::reader::{Reader, ReaderBuilder};
-use arrow_avro::schema::AvroSchema;
use arrow_cast::{CastOptions, cast_with_options};
use arrow_ord::cmp::eq;
-use arrow_schema::{ArrowError, DataType, Field, Fields, TimeUnit};
+use arrow_schema::{ArrowError, DataType, Field, Fields, SchemaRef, TimeUnit};
use arrow_select::zip::zip;
use parquet::arrow::PARQUET_FIELD_ID_META_KEY;
use serde_json::Value as JsonValue;
@@ -40,16 +40,19 @@ use serde_json::Value as JsonValue;
use crate::arrow::schema_to_arrow_schema;
use crate::error::invalid_data;
use crate::spec::{
- DATA_FILE_CONTENT_FIELD_ID, DATA_FILE_FIELD_ID,
DATA_FILE_PARTITION_FIELD_ID,
- FILE_SEQUENCE_NUMBER_FIELD_ID, FormatVersion, MANIFEST_CONTENT_FIELD_ID,
- MANIFEST_SEQUENCE_NUMBER_FIELD_ID, MIN_SEQUENCE_NUMBER_FIELD_ID,
ManifestContentType,
- ManifestFile, ManifestMetadata, ManifestStatus, SEQUENCE_NUMBER_FIELD_ID,
Schema,
- manifest_entry_fields, manifest_file_fields,
+ DATA_FILE_CONTENT_FIELD_ID, FILE_SEQUENCE_NUMBER_FIELD_ID, FormatVersion,
+ MANIFEST_CONTENT_FIELD_ID, MANIFEST_SEQUENCE_NUMBER_FIELD_ID,
MIN_SEQUENCE_NUMBER_FIELD_ID,
+ ManifestContentType, ManifestFile, ManifestMetadata, ManifestStatus,
SEQUENCE_NUMBER_FIELD_ID,
+ Schema, manifest_entry_fields, manifest_file_fields,
};
use crate::{Error, Result};
-/// Reads the entries of a manifest file into a [`RecordBatch`] with one row
-/// per entry.
+/// Rows per batch. A row's size grows with the table's column count through
+/// the column stats maps. With stats on every column of a 100-column table of
+/// longs, 1024 rows take about 9 MB.
+const BATCH_SIZE: usize = 1024;
+
+/// Reads the entries of a manifest file as batches with one row per entry.
///
/// `bytes` is the manifest file and `manifest_file` is its entry in the
/// manifest list. The schema is the spec's `manifest_entry` struct for the
@@ -63,6 +66,17 @@ use crate::{Error, Result};
/// Lower and upper bounds keep the binary single-value serialization they were
/// written with.
///
+/// If `manifest_file.key_metadata` is set, the manifest is encrypted and
+/// `bytes` must be decrypted first.
+/// [`Table::manifest_reader`](crate::table::Table::manifest_reader) returns a
+/// reader that decrypts.
+///
+/// # Errors
+///
+/// Returns an error if the manifest's header can't be read or names an
+/// unsupported format version. Encrypted bytes fail at the header. Errors in
+/// the entries come from the reader, which yields no batches after one.
+///
/// # Example
///
/// ```
@@ -92,73 +106,111 @@ use crate::{Error, Result};
/// first_row_id: None,
/// };
///
-/// let batch = read_manifest_entries(&bytes, &manifest_file)?;
-/// assert_eq!(batch.num_rows(), 2);
+/// let mut rows = 0;
+/// for batch in read_manifest_entries(&bytes, &manifest_file)? {
+/// rows += batch?.num_rows();
+/// }
+/// assert_eq!(rows, 2);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
-pub fn read_manifest_entries(bytes: &[u8], manifest_file: &ManifestFile) ->
Result<RecordBatch> {
- // usize::MAX decodes the whole manifest into one batch. First row ID
- // inheritance is a running sum over every entry in the file, and an empty
- // manifest still returns its schema. arrow-avro sizes its buffers
- // independently of the batch size, so this doesn't preallocate.
- let builder = || ReaderBuilder::new().with_batch_size(usize::MAX);
- let mut reader = builder().build(bytes).map_err(invalid_manifest)?;
- let header = reader.avro_header();
- let metadata: HashMap<String, Vec<u8>> = header
- .metadata()
- .map(|(key, value)| (String::from_utf8_lossy(key).into_owned(),
value.to_vec()))
- .collect();
- let metadata = ManifestMetadata::parse(&metadata)?;
- let mut avro_schema: JsonValue = serde_json::from_slice(
- header
- .get("avro.schema")
- .ok_or_else(|| invalid_data!("manifest has no avro.schema"))?,
- )?;
- let partition_type = metadata
- .partition_spec()
- .partition_type(metadata.schema())?;
- let schema = Arc::new(schema_to_arrow_schema(
- &Schema::builder()
- .with_fields(manifest_entry_fields(&partition_type))
- .build()?,
- )?);
-
- // TODO(#3257): arrow-avro 59 can't decode a record with no fields, which
- // is the partition of every unpartitioned manifest, so project it out and
- // build it in `missing_field`. arrow-avro 60 fixes this
- // (apache/arrow-rs#10771).
- if remove_empty_partition(&mut avro_schema) {
- reader = builder()
- .with_reader_schema(AvroSchema::new(avro_schema.to_string()))
- .build(bytes)
+pub fn read_manifest_entries<B: AsRef<[u8]>>(
+ bytes: B,
+ manifest_file: &ManifestFile,
+) -> Result<ManifestEntryBatchReader<B>> {
+ ManifestEntryBatchReader::try_new(bytes, manifest_file, BATCH_SIZE)
+}
+
+/// Batches of the entries of a manifest file, returned by
+/// [`read_manifest_entries`].
+pub struct ManifestEntryBatchReader<B: AsRef<[u8]>> {
+ inner: ProjectingReader<B>,
+ inheritance: Inheritance,
+}
+
+/// The values that a manifest's entries inherit from the manifest list.
+struct Inheritance {
+ manifest_path: String,
+ added_snapshot_id: i64,
+ sequence_number: i64,
+ content: ManifestContentType,
+ /// The first row ID of the next entry that inherits one, which advances
+ /// across batches. `None` for a manifest without a first row ID.
+ next_row_id: Option<i64>,
+}
+
+impl<B: AsRef<[u8]>> ManifestEntryBatchReader<B> {
+ fn try_new(bytes: B, manifest_file: &ManifestFile, batch_size: usize) ->
Result<Self> {
+ let reader = ReaderBuilder::new()
+ .with_batch_size(batch_size)
+ .build(Cursor::new(bytes))
.map_err(invalid_manifest)?;
+ let header = reader.avro_header();
+ let metadata: HashMap<String, Vec<u8>> = header
+ .metadata()
+ .map(|(key, value)| (String::from_utf8_lossy(key).into_owned(),
value.to_vec()))
+ .collect();
+ let metadata = ManifestMetadata::parse(&metadata)?;
+ let avro_schema: JsonValue = serde_json::from_slice(
+ header
+ .get("avro.schema")
+ .ok_or_else(|| invalid_data!("manifest has no avro.schema"))?,
+ )?;
+ let partition_type = metadata
+ .partition_spec()
+ .partition_type(metadata.schema())?;
+ let schema = Arc::new(schema_to_arrow_schema(
+ &Schema::builder()
+ .with_fields(manifest_entry_fields(&partition_type))
+ .build()?,
+ )?);
+
+ // v1 manifests have no content or sequence number columns, which v2+
+ // readers read as 0. A v2+ manifest may lack file_sequence_number
(Java
+ // wrote none before 1.1.0), which reads as null and is inherited.
+ let zero_defaults: &[i32] = match metadata.format_version() {
+ FormatVersion::V1 => &[
+ DATA_FILE_CONTENT_FIELD_ID,
+ SEQUENCE_NUMBER_FIELD_ID,
+ FILE_SEQUENCE_NUMBER_FIELD_ID,
+ ],
+ _ => &[DATA_FILE_CONTENT_FIELD_ID],
+ };
+ Ok(Self {
+ inner: ProjectingReader {
+ reader,
+ schema,
+ avro_schema,
+ zero_defaults,
+ invalid: invalid_manifest,
+ finished: false,
+ },
+ inheritance: Inheritance {
+ manifest_path: manifest_file.manifest_path.clone(),
+ added_snapshot_id: manifest_file.added_snapshot_id,
+ sequence_number: manifest_file.sequence_number,
+ content: manifest_file.content,
+ next_row_id:
manifest_file.first_row_id.map(i64::try_from).transpose()?,
+ },
+ })
}
- let Some(batch) = only_batch(reader, invalid_manifest)? else {
- return Ok(RecordBatch::new_empty(schema));
- };
- // v1 manifests have no content or sequence number columns, which v2+
- // readers read as 0. A v2+ manifest may lack file_sequence_number (Java
- // wrote none before 1.1.0), which reads as null and is inherited.
- let zero_defaults: &[i32] = match metadata.format_version() {
- FormatVersion::V1 => &[
- DATA_FILE_CONTENT_FIELD_ID,
- SEQUENCE_NUMBER_FIELD_ID,
- FILE_SEQUENCE_NUMBER_FIELD_ID,
- ],
- _ => &[DATA_FILE_CONTENT_FIELD_ID],
- };
- let entries = project_struct(
- &StructArray::from(batch),
- &avro_schema,
- schema.fields(),
- zero_defaults,
- )?;
- Ok(RecordBatch::from(inherit(entries, manifest_file)?))
+ /// Returns the schema of every batch.
+ pub fn schema(&self) -> SchemaRef {
+ self.inner.schema.clone()
+ }
}
-/// Reads the entries of a manifest list into a [`RecordBatch`] with one row
-/// per manifest.
+impl<B: AsRef<[u8]>> Iterator for ManifestEntryBatchReader<B> {
+ type Item = Result<RecordBatch>;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ let inheritance = &mut self.inheritance;
+ self.inner
+ .next_batch(|entries| inherit(entries, inheritance))
+ }
+}
+
+/// Reads the entries of a manifest list as batches with one row per manifest.
///
/// The schema is the spec's `manifest_file` struct for the latest format
/// version, with field IDs in the Arrow field metadata, so manifest lists of
@@ -169,6 +221,17 @@ pub fn read_manifest_entries(bytes: &[u8], manifest_file:
&ManifestFile) -> Resu
/// v2+ defaults. Partition summary bounds keep the binary single-value
/// serialization they were written with.
///
+/// If the snapshot has an `encryption_key_id`, the manifest list is encrypted
+/// and `bytes` must be decrypted first.
+/// [`Table::manifest_list_reader`](crate::table::Table::manifest_list_reader)
+/// returns a reader that decrypts.
+///
+/// # Errors
+///
+/// Returns an error if the manifest list's header can't be read or names an
+/// unsupported format version. Encrypted bytes fail at the header. Errors in
+/// the entries come from the reader, which yields no batches after one.
+///
/// # Example
///
/// ```
@@ -178,103 +241,119 @@ pub fn read_manifest_entries(bytes: &[u8],
manifest_file: &ManifestFile) -> Resu
/// env!("CARGO_MANIFEST_DIR"),
/// "/testdata/manifests_lists/manifest-list-v2-2.avro"
/// ))?;
-/// let batch = read_manifest_list(&bytes)?;
-/// assert_eq!(batch.num_rows(), 1);
+/// let mut rows = 0;
+/// for batch in read_manifest_list(&bytes)? {
+/// rows += batch?.num_rows();
+/// }
+/// assert_eq!(rows, 1);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
-pub fn read_manifest_list(bytes: &[u8]) -> Result<RecordBatch> {
- // usize::MAX decodes the whole manifest list into one batch, which
- // `only_batch` checks.
- let reader = ReaderBuilder::new()
- .with_batch_size(usize::MAX)
- .build(bytes)
- .map_err(invalid_manifest_list)?;
- let header = reader.avro_header();
- let avro_schema: JsonValue = serde_json::from_slice(
- header
- .get("avro.schema")
- .ok_or_else(|| invalid_data!("manifest list has no avro.schema"))?,
- )?;
- // The spec doesn't define this key, but Java, PyIceberg, and iceberg-rust
- // all write it, and rejecting an unknown version keeps a newer manifest
- // list from reading as an older one.
- let format_version = match header.get("format-version") {
- Some(bytes) =>
serde_json::from_slice::<FormatVersion>(bytes).map_err(|err| {
- invalid_data!("failed to parse format version in manifest list
metadata")
- .with_source(err)
- })?,
- None => FormatVersion::V1,
- };
- let schema = Arc::new(schema_to_arrow_schema(
- &Schema::builder()
- .with_fields(manifest_file_fields())
- .build()?,
- )?);
- let Some(batch) = only_batch(reader, invalid_manifest_list)? else {
- return Ok(RecordBatch::new_empty(schema));
- };
- // v1 manifest lists have no content or sequence number columns, which v2+
- // readers read as 0.
- let zero_defaults: &[i32] = match format_version {
- FormatVersion::V1 => &[
- MANIFEST_CONTENT_FIELD_ID,
- MANIFEST_SEQUENCE_NUMBER_FIELD_ID,
- MIN_SEQUENCE_NUMBER_FIELD_ID,
- ],
- _ => &[],
- };
- let manifests = project_struct(
- &StructArray::from(batch),
- &avro_schema,
- schema.fields(),
- zero_defaults,
- )?;
- Ok(RecordBatch::from(manifests))
+pub fn read_manifest_list<B: AsRef<[u8]>>(bytes: B) ->
Result<ManifestListBatchReader<B>> {
+ ManifestListBatchReader::try_new(bytes, BATCH_SIZE)
}
-/// Returns the only batch that `reader` decodes, or `None` for a file without
-/// records.
-fn only_batch(
- mut reader: Reader<&[u8]>,
- invalid: fn(ArrowError) -> Error,
-) -> Result<Option<RecordBatch>> {
- let Some(batch) = reader.next() else {
- return Ok(None);
- };
- let batch = batch.map_err(invalid)?;
- // Taking only the first batch relies on arrow-avro filling it to the batch
- // size, so fail instead of dropping records if that changes.
- if reader.next().is_some() {
- return Err(invalid_data!(
- "arrow-avro split the file into more than one batch"
- ));
- }
- Ok(Some(batch))
+/// Batches of the entries of a manifest list, returned by
+/// [`read_manifest_list`].
+pub struct ManifestListBatchReader<B: AsRef<[u8]>> {
+ inner: ProjectingReader<B>,
}
-/// Removes `data_file.partition` from a manifest's Avro schema if it has no
-/// fields, and returns whether it did.
-fn remove_empty_partition(avro_schema: &mut JsonValue) -> bool {
- let has_field_id = |field: &JsonValue, id: i32| field["field-id"].as_i64()
== Some(id.into());
- let Some(data_file_fields) = avro_schema["fields"]
- .as_array_mut()
- .and_then(|fields| {
- fields
- .iter_mut()
- .find(|field| has_field_id(field, DATA_FILE_FIELD_ID))
+impl<B: AsRef<[u8]>> ManifestListBatchReader<B> {
+ fn try_new(bytes: B, batch_size: usize) -> Result<Self> {
+ let reader = ReaderBuilder::new()
+ .with_batch_size(batch_size)
+ .build(Cursor::new(bytes))
+ .map_err(invalid_manifest_list)?;
+ let header = reader.avro_header();
+ let avro_schema: JsonValue = serde_json::from_slice(
+ header
+ .get("avro.schema")
+ .ok_or_else(|| invalid_data!("manifest list has no
avro.schema"))?,
+ )?;
+ // The spec doesn't define this key, but Java, PyIceberg, and
iceberg-rust
+ // all write it, and rejecting an unknown version keeps a newer
manifest
+ // list from reading as an older one.
+ let format_version = match header.get("format-version") {
+ Some(bytes) =>
serde_json::from_slice::<FormatVersion>(bytes).map_err(|err| {
+ invalid_data!("failed to parse format version in manifest list
metadata")
+ .with_source(err)
+ })?,
+ None => FormatVersion::V1,
+ };
+ let schema = Arc::new(schema_to_arrow_schema(
+ &Schema::builder()
+ .with_fields(manifest_file_fields())
+ .build()?,
+ )?);
+ // v1 manifest lists have no content or sequence number columns, which
v2+
+ // readers read as 0.
+ let zero_defaults: &[i32] = match format_version {
+ FormatVersion::V1 => &[
+ MANIFEST_CONTENT_FIELD_ID,
+ MANIFEST_SEQUENCE_NUMBER_FIELD_ID,
+ MIN_SEQUENCE_NUMBER_FIELD_ID,
+ ],
+ _ => &[],
+ };
+ Ok(Self {
+ inner: ProjectingReader {
+ reader,
+ schema,
+ avro_schema,
+ zero_defaults,
+ invalid: invalid_manifest_list,
+ finished: false,
+ },
})
- .and_then(|data_file| data_file["type"]["fields"].as_array_mut())
- else {
- return false;
- };
- let len = data_file_fields.len();
- data_file_fields.retain(|field| {
- !(has_field_id(field, DATA_FILE_PARTITION_FIELD_ID)
- && field["type"]["fields"]
- .as_array()
- .is_some_and(Vec::is_empty))
- });
- data_file_fields.len() != len
+ }
+
+ /// Returns the schema of every batch.
+ pub fn schema(&self) -> SchemaRef {
+ self.inner.schema.clone()
+ }
+}
+
+impl<B: AsRef<[u8]>> Iterator for ManifestListBatchReader<B> {
+ type Item = Result<RecordBatch>;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ self.inner.next_batch(Ok)
+ }
+}
+
+/// Decodes an Avro file in batches and projects them onto `schema`.
+struct ProjectingReader<B: AsRef<[u8]>> {
+ reader: Reader<Cursor<B>>,
+ schema: SchemaRef,
+ avro_schema: JsonValue,
+ zero_defaults: &'static [i32],
+ invalid: fn(ArrowError) -> Error,
+ /// Set after an error. First row ID inheritance can stop partway through
+ /// a batch, so the batches after an error would get the wrong row IDs.
+ finished: bool,
+}
+
+impl<B: AsRef<[u8]>> ProjectingReader<B> {
+ /// Returns the next batch with `finish` applied to its projected rows.
+ fn next_batch(
+ &mut self,
+ finish: impl FnOnce(StructArray) -> Result<StructArray>,
+ ) -> Option<Result<RecordBatch>> {
+ if self.finished {
+ return None;
+ }
+ let batch = self.reader.next()?.map_err(self.invalid).and_then(|batch|
{
+ let rows = project_struct(
+ &StructArray::from(batch),
+ &self.avro_schema,
+ self.schema.fields(),
+ self.zero_defaults,
+ )?;
+ Ok(RecordBatch::from(finish(rows)?))
+ });
+ self.finished = batch.is_err();
+ Some(batch)
+ }
}
fn invalid_manifest(err: ArrowError) -> Error {
@@ -350,9 +429,6 @@ fn missing_field(field: &Field, len: usize, zero_defaults:
&[i32]) -> Result<Arr
DataType::Int32 if zero => Ok(Arc::new(Int32Array::from_value(0,
len))),
DataType::Int64 if zero => Ok(Arc::new(Int64Array::from_value(0,
len))),
_ if field.is_nullable() => Ok(new_null_array(field.data_type(), len)),
- DataType::Struct(fields) if fields.is_empty() => {
- Ok(Arc::new(StructArray::new_empty_fields(len, None)))
- }
_ => Err(invalid_data!(
"Avro file has no required field {} with field ID {id}",
field.name()
@@ -452,7 +528,7 @@ fn project(
/// Fills in the values that the spec says entries inherit from the manifest
/// list.
-fn inherit(entries: StructArray, manifest_file: &ManifestFile) ->
Result<StructArray> {
+fn inherit(entries: StructArray, inheritance: &mut Inheritance) ->
Result<StructArray> {
let (fields, mut columns, nulls) = entries.into_parts();
let index = |name: &str| fields.find(name).unwrap().0;
let (status, snapshot_id, sequence_number, file_sequence_number,
data_file) = (
@@ -463,22 +539,18 @@ fn inherit(entries: StructArray, manifest_file:
&ManifestFile) -> Result<StructA
index("data_file"),
);
- columns[snapshot_id] =
- fill_nulls(&columns[snapshot_id], None,
manifest_file.added_snapshot_id)?;
+ columns[snapshot_id] = fill_nulls(&columns[snapshot_id], None,
inheritance.added_snapshot_id)?;
if columns[sequence_number].null_count() > 0 ||
columns[file_sequence_number].null_count() > 0 {
let added = eq(
&columns[status],
&Int32Array::new_scalar(ManifestStatus::Added as i32),
)?;
for column in [sequence_number, file_sequence_number] {
- columns[column] = fill_nulls(
- &columns[column],
- Some(&added),
- manifest_file.sequence_number,
- )?;
+ columns[column] =
+ fill_nulls(&columns[column], Some(&added),
inheritance.sequence_number)?;
}
}
- if manifest_file.content == ManifestContentType::Data {
+ if inheritance.content == ManifestContentType::Data {
let (data_file_fields, mut data_file_columns, data_file_nulls) =
columns[data_file].as_struct().clone().into_parts();
let index = |name: &str| data_file_fields.find(name).unwrap().0;
@@ -487,7 +559,7 @@ fn inherit(entries: StructArray, manifest_file:
&ManifestFile) -> Result<StructA
data_file_columns[first_row_id].as_primitive(),
columns[status].as_primitive(),
data_file_columns[index("record_count")].as_primitive(),
- manifest_file,
+ inheritance,
)?;
columns[data_file] = Arc::new(StructArray::new(
data_file_fields,
@@ -521,15 +593,14 @@ fn inherit_first_row_ids(
first_row_ids: &Int64Array,
status: &Int32Array,
record_counts: &Int64Array,
- manifest_file: &ManifestFile,
+ inheritance: &mut Inheritance,
) -> Result<ArrayRef> {
- let Some(manifest_first_row_id) = manifest_file.first_row_id else {
+ let Some(next_row_id) = inheritance.next_row_id.as_mut() else {
return Ok(new_null_array(&DataType::Int64, first_row_ids.len()));
};
if first_row_ids.null_count() == 0 {
return Ok(Arc::new(first_row_ids.clone()));
}
- let mut next_row_id = i64::try_from(manifest_first_row_id)?;
let mut builder = Int64Builder::with_capacity(first_row_ids.len());
for ((first_row_id, &status), &record_count) in first_row_ids
.iter()
@@ -541,14 +612,14 @@ fn inherit_first_row_ids(
if record_count < 0 {
return Err(invalid_data!(
"negative record_count {record_count} assigning first
row IDs in {}",
- manifest_file.manifest_path
+ inheritance.manifest_path
));
}
- builder.append_value(next_row_id);
- next_row_id =
next_row_id.checked_add(record_count).ok_or_else(|| {
+ builder.append_value(*next_row_id);
+ *next_row_id =
next_row_id.checked_add(record_count).ok_or_else(|| {
invalid_data!(
"row ID overflow assigning first row IDs in {}",
- manifest_file.manifest_path
+ inheritance.manifest_path
)
})?;
}
@@ -573,6 +644,8 @@ mod tests {
Time64MicrosecondArray, TimestampMicrosecondArray,
TimestampNanosecondArray,
};
use arrow_buffer::{NullBuffer, OffsetBuffer};
+ use arrow_schema::SchemaRef;
+ use arrow_select::concat::concat_batches;
use super::*;
use crate::ErrorKind;
@@ -671,6 +744,50 @@ mod tests {
(bytes, manifest_file)
}
+ fn concat(
+ schema: SchemaRef,
+ batches: impl Iterator<Item = Result<RecordBatch>>,
+ ) -> Result<RecordBatch> {
+ let batches = batches.collect::<Result<Vec<_>>>()?;
+ Ok(concat_batches(&schema, &batches)?)
+ }
+
+ fn read_entries(bytes: &[u8], manifest_file: &ManifestFile) ->
Result<RecordBatch> {
+ let reader = read_manifest_entries(bytes, manifest_file)?;
+ concat(reader.schema(), reader)
+ }
+
+ fn read_list(bytes: &[u8]) -> Result<RecordBatch> {
+ let reader = read_manifest_list(bytes)?;
+ concat(reader.schema(), reader)
+ }
+
+ /// Checks that reading in batches of 1 to 3 rows gives nonempty batches of
+ /// the reader's schema that concatenate to the file read as one batch.
+ fn assert_batches_match_whole<I: Iterator<Item = Result<RecordBatch>>>(
+ read: impl Fn(usize) -> (SchemaRef, I),
+ ) {
+ let (schema, batches) = read(usize::MAX);
+ let whole = concat(schema.clone(), batches).unwrap();
+ for batch_size in 1..=3 {
+ let (batch_schema, batches) = read(batch_size);
+ assert_eq!(batch_schema, schema);
+ let batches: Vec<_> = batches.map(Result::unwrap).collect();
+ for batch in &batches {
+ assert_eq!(batch.schema(), schema, "batch size {batch_size}");
+ assert!(
+ (1..=batch_size).contains(&batch.num_rows()),
+ "batch size {batch_size}"
+ );
+ }
+ assert_eq!(
+ concat_batches(&schema, &batches).unwrap(),
+ whole,
+ "batch size {batch_size}"
+ );
+ }
+ }
+
fn column(batch: &RecordBatch, name: &str) -> ArrayRef {
batch.column_by_name(name).unwrap().clone()
}
@@ -843,7 +960,7 @@ mod tests {
let spec = partition_spec(&[("i", Transform::Identity), ("s",
Transform::Truncate(2))]);
let (bytes, manifest_file) =
write_manifest(spec, Some(1), |b| b.build_v2_data(), |_| {}).await;
- let batch = read_manifest_entries(&bytes, &manifest_file).unwrap();
+ let batch = read_entries(&bytes, &manifest_file).unwrap();
assert_eq!(batch.num_rows(), 0);
let long = || Type::Primitive(PrimitiveType::Long);
@@ -957,7 +1074,7 @@ mod tests {
},
)
.await;
- let batch = read_manifest_entries(&bytes, &manifest_file).unwrap();
+ let batch = read_entries(&bytes, &manifest_file).unwrap();
assert_eq!(batch.num_rows(), 2);
assert_eq!(
@@ -1050,7 +1167,7 @@ mod tests {
},
)
.await;
- let batch = read_manifest_entries(&bytes, &manifest_file).unwrap();
+ let batch = read_entries(&bytes, &manifest_file).unwrap();
let column = |name: &str| data_file_column(&batch, name);
assert_eq!(
@@ -1139,7 +1256,7 @@ mod tests {
},
)
.await;
- let batch = read_manifest_entries(&bytes, &manifest_file).unwrap();
+ let batch = read_entries(&bytes, &manifest_file).unwrap();
let partition = data_file_column(&batch, "partition");
let partition = partition.as_struct();
@@ -1215,7 +1332,7 @@ mod tests {
// The v1 default must win over inheritance, so give the manifest list
// entry a sequence number that inheritance would use.
manifest_file.sequence_number = 9;
- let batch = read_manifest_entries(&bytes, &manifest_file).unwrap();
+ let batch = read_entries(&bytes, &manifest_file).unwrap();
assert_eq!(
data_file_column(&batch, "content").as_ref(),
@@ -1272,7 +1389,7 @@ mod tests {
);
manifest_file.added_snapshot_id = 42;
manifest_file.sequence_number = 7;
- let batch = read_manifest_entries(&bytes, &manifest_file).unwrap();
+ let batch = read_entries(&bytes, &manifest_file).unwrap();
assert_eq!(
column(&batch, "snapshot_id").as_ref(),
@@ -1322,7 +1439,7 @@ mod tests {
},
);
manifest_file.sequence_number = 7;
- let batch = read_manifest_entries(&bytes, &manifest_file).unwrap();
+ let batch = read_entries(&bytes, &manifest_file).unwrap();
assert_eq!(
column(&batch, "file_sequence_number").as_ref(),
@@ -1370,7 +1487,7 @@ mod tests {
async fn test_first_row_id_inheritance() {
let (bytes, mut manifest_file) = first_row_id_manifest().await;
manifest_file.first_row_id = Some(100);
- let batch = read_manifest_entries(&bytes, &manifest_file).unwrap();
+ let batch = read_entries(&bytes, &manifest_file).unwrap();
// Deleted entries don't take row IDs, and entries with a first_row_id
keep it.
assert_eq!(
data_file_column(&batch, "first_row_id").as_ref(),
@@ -1378,16 +1495,25 @@ mod tests {
);
manifest_file.first_row_id = None;
- let batch = read_manifest_entries(&bytes, &manifest_file).unwrap();
+ let batch = read_entries(&bytes, &manifest_file).unwrap();
assert_eq!(data_file_column(&batch, "first_row_id").null_count(), 5);
manifest_file.first_row_id = Some(i64::MAX as u64 - 5);
- let err = read_manifest_entries(&bytes, &manifest_file).unwrap_err();
+ let err = read_entries(&bytes, &manifest_file).unwrap_err();
assert_eq!(err.kind(), ErrorKind::DataInvalid);
// A negative record_count would assign overlapping row IDs.
- let bytes = rewrite_manifest(
- &bytes,
+ let bytes = negate_record_count(&bytes, 10);
+ manifest_file.first_row_id = Some(100);
+ let err = read_entries(&bytes, &manifest_file).unwrap_err();
+ assert_eq!(err.kind(), ErrorKind::DataInvalid);
+ }
+
+ /// Negates the `record_count` of the data files whose count is
+ /// `record_count`.
+ fn negate_record_count(bytes: &[u8], record_count: i64) -> Vec<u8> {
+ rewrite_manifest(
+ bytes,
Codec::Null,
|_| {},
|record| {
@@ -1400,21 +1526,92 @@ mod tests {
panic!("manifest entry has no data_file record");
};
for (name, value) in data_file {
- if name == "record_count" && *value == AvroValue::Long(10)
{
- *value = AvroValue::Long(-10);
+ if name == "record_count" && *value ==
AvroValue::Long(record_count) {
+ *value = AvroValue::Long(-record_count);
}
}
},
- );
- manifest_file.first_row_id = Some(100);
- let err = read_manifest_entries(&bytes, &manifest_file).unwrap_err();
+ )
+ }
+
+ #[tokio::test]
+ async fn test_manifest_batches_match_whole_manifest() {
+ let (first_row_id_bytes, mut first_row_id_manifest_file) =
first_row_id_manifest().await;
+ first_row_id_manifest_file.first_row_id = Some(100);
+ let v1_files = (0..3).map(|i| {
+ data_file(DataContentType::Data,
&format!("s3://b/data/{i}.parquet"))
+ .build()
+ .unwrap()
+ });
+ let v1 = write_manifest(
+ partition_spec(&[]),
+ Some(1),
+ |b| b.build_v1(),
+ |writer| v1_files.for_each(|file| writer.add_file(file,
-1).unwrap()),
+ )
+ .await;
+ let empty = write_manifest(
+ partition_spec(&[("i", Transform::Identity)]),
+ Some(1),
+ |b| b.build_v2_data(),
+ |_| {},
+ )
+ .await;
+ let pyiceberg_bytes = std::fs::read(format!(
+ "{}/testdata/manifests/pyiceberg-v2-data.avro",
+ env!("CARGO_MANIFEST_DIR")
+ ))
+ .unwrap();
+ let pyiceberg_manifest_file = ManifestFile {
+ sequence_number: 1,
+ ..listed_manifest("s3://b/metadata/0.avro",
ManifestContentType::Data)
+ };
+
+ for (bytes, manifest_file) in [
+ (first_row_id_bytes, first_row_id_manifest_file),
+ v1,
+ empty,
+ (pyiceberg_bytes, pyiceberg_manifest_file),
+ ] {
+ assert_batches_match_whole(|batch_size| {
+ let reader =
+ ManifestEntryBatchReader::try_new(&bytes, &manifest_file,
batch_size).unwrap();
+ (reader.schema(), reader)
+ });
+ }
+ }
+
+ #[tokio::test]
+ async fn test_unknown_manifest_format_version_is_an_error() {
+ let (bytes, manifest_file) = first_row_id_manifest().await;
+ let bytes = set_avro_metadata(&bytes, "format-version", Some("4"));
+ let Err(err) = read_manifest_entries(&bytes, &manifest_file) else {
+ panic!("a v4 manifest read as an older version");
+ };
assert_eq!(err.kind(), ErrorKind::DataInvalid);
}
+ #[tokio::test]
+ async fn test_manifest_error_ends_the_batches() {
+ let (bytes, mut manifest_file) = first_row_id_manifest().await;
+ manifest_file.first_row_id = Some(100);
+ // The last of the five entries fails first row ID inheritance, so the
+ // third batch of two is an error.
+ let bytes = negate_record_count(&bytes, 2);
+ let mut reader = ManifestEntryBatchReader::try_new(&bytes,
&manifest_file, 2).unwrap();
+ assert_eq!(reader.next().unwrap().unwrap().num_rows(), 2);
+ assert_eq!(reader.next().unwrap().unwrap().num_rows(), 2);
+ assert_eq!(
+ reader.next().unwrap().unwrap_err().kind(),
+ ErrorKind::DataInvalid
+ );
+ assert!(reader.next().is_none());
+ }
+
#[tokio::test]
async fn test_compressed_manifests() {
let (bytes, manifest_file) = first_row_id_manifest().await;
- let expected = read_manifest_entries(&bytes, &manifest_file).unwrap();
+ let expected = read_entries(&bytes, &manifest_file).unwrap();
for codec in [
Codec::Deflate(DeflateSettings::default()),
Codec::Snappy,
@@ -1422,7 +1619,7 @@ mod tests {
] {
let bytes = rewrite_manifest(&bytes, codec, |_| {}, |_| {});
assert_eq!(
- read_manifest_entries(&bytes, &manifest_file).unwrap(),
+ read_entries(&bytes, &manifest_file).unwrap(),
expected,
"{codec:?}"
);
@@ -1448,7 +1645,7 @@ mod tests {
("file_path", "path"),
("i_identity", "renamed_partition"),
]);
- let batch = read_manifest_entries(&bytes, &manifest_file).unwrap();
+ let batch = read_entries(&bytes, &manifest_file).unwrap();
assert_eq!(
data_file_column(&batch, "file_path").as_ref(),
@@ -1486,7 +1683,7 @@ mod tests {
},
|_| {},
);
- let err = read_manifest_entries(&bytes, &manifest_file).unwrap_err();
+ let err = read_entries(&bytes, &manifest_file).unwrap_err();
assert_eq!(err.kind(), ErrorKind::DataInvalid);
}
@@ -1516,7 +1713,7 @@ mod tests {
key_metadata: None,
first_row_id: None,
};
- let batch = read_manifest_entries(&bytes, &manifest_file).unwrap();
+ let batch = read_entries(&bytes, &manifest_file).unwrap();
assert_eq!(batch.num_rows(), manifest.entries().len());
let paths = data_file_column(&batch, "file_path");
@@ -1587,7 +1784,7 @@ mod tests {
#[tokio::test]
async fn test_schema_is_spec_manifest_file() {
let bytes = write_manifest_list(FormatVersion::V3, vec![]).await;
- let batch = read_manifest_list(&bytes).unwrap();
+ let batch = read_list(&bytes).unwrap();
assert_eq!(batch.num_rows(), 0);
let long = || Type::Primitive(PrimitiveType::Long);
@@ -1656,7 +1853,7 @@ mod tests {
..listed_manifest("s3://b/metadata/deletes.avro",
ManifestContentType::Deletes)
};
let bytes = write_manifest_list(FormatVersion::V3, vec![data,
existing_deletes]).await;
- let batch = read_manifest_list(&bytes).unwrap();
+ let batch = read_list(&bytes).unwrap();
let schema = batch.schema();
let DataType::List(summary) =
schema.field_with_name("partitions").unwrap().data_type()
@@ -1725,7 +1922,7 @@ mod tests {
// A manifest list without a format version reads as v1.
let without_format_version = set_avro_metadata(&bytes,
"format-version", None);
for bytes in [bytes, without_format_version] {
- let batch = read_manifest_list(&bytes).unwrap();
+ let batch = read_list(&bytes).unwrap();
assert_eq!(
column(&batch, "content").as_ref(),
@@ -1767,7 +1964,7 @@ mod tests {
("added_files_count", "added_data_files_count"),
("contains_null", "has_null"),
]);
- let batch = read_manifest_list(&bytes).unwrap();
+ let batch = read_list(&bytes).unwrap();
assert_eq!(
column(&batch, "manifest_path").as_ref(),
@@ -1791,7 +1988,7 @@ mod tests {
#[tokio::test]
async fn test_invalid_manifest_list_is_an_error() {
- let err = read_manifest_list(&[]).unwrap_err();
+ let err = read_list(&[]).unwrap_err();
assert_eq!(err.kind(), ErrorKind::DataInvalid);
let bytes = write_manifest_list(FormatVersion::V2,
vec![listed_manifest(
@@ -1836,11 +2033,30 @@ mod tests {
without_sequence_number,
unknown_format_version,
] {
- let err = read_manifest_list(&bytes).unwrap_err();
+ let err = read_list(&bytes).unwrap_err();
assert_eq!(err.kind(), ErrorKind::DataInvalid);
}
}
+ #[test]
+ fn test_encrypted_bytes_are_an_error() {
+ // An AES GCM stream, which starts with AGS1 instead of Avro's magic.
+ let bytes = std::fs::read(format!(
+ "{}/testdata/manifests_lists/manifest-list-v3-encrypted.avro",
+ env!("CARGO_MANIFEST_DIR")
+ ))
+ .unwrap();
+ let manifest_file = listed_manifest("s3://b/metadata/0.avro",
ManifestContentType::Data);
+ let Err(err) = read_manifest_entries(&bytes, &manifest_file) else {
+ panic!("an encrypted manifest read as plaintext");
+ };
+ assert_eq!(err.kind(), ErrorKind::DataInvalid);
+ let Err(err) = read_manifest_list(&bytes) else {
+ panic!("an encrypted manifest list read as plaintext");
+ };
+ assert_eq!(err.kind(), ErrorKind::DataInvalid);
+ }
+
#[test]
fn test_manifest_lists_written_by_java() {
// Written by Java 1.4.0, with the v1 file count names, and 1.5.0.
@@ -1852,7 +2068,7 @@ mod tests {
.unwrap();
let manifest_list =
ManifestList::parse_with_version(&bytes,
FormatVersion::V2).unwrap();
- let batch = read_manifest_list(&bytes).unwrap();
+ let batch = read_list(&bytes).unwrap();
assert_eq!(batch.num_rows(), manifest_list.entries().len(),
"{name}");
let paths = column(&batch, "manifest_path");
@@ -1894,4 +2110,25 @@ mod tests {
}
}
}
+
+ #[tokio::test]
+ async fn test_manifest_list_batches_match_whole_list() {
+ for version in [FormatVersion::V1, FormatVersion::V2,
FormatVersion::V3] {
+ for len in [0, 3] {
+ let manifests = (0..len)
+ .map(|i| {
+ listed_manifest(
+ &format!("s3://b/metadata/{i}.avro"),
+ ManifestContentType::Data,
+ )
+ })
+ .collect();
+ let bytes = write_manifest_list(version, manifests).await;
+ assert_batches_match_whole(|batch_size| {
+ let reader = ManifestListBatchReader::try_new(&bytes,
batch_size).unwrap();
+ (reader.schema(), reader)
+ });
+ }
+ }
+ }
}
diff --git a/crates/iceberg/src/arrow/mod.rs b/crates/iceberg/src/arrow/mod.rs
index d8343ef1e..25a84a0c6 100644
--- a/crates/iceberg/src/arrow/mod.rs
+++ b/crates/iceberg/src/arrow/mod.rs
@@ -29,7 +29,9 @@ pub(crate) mod delete_filter;
mod int96;
mod manifest;
-pub use manifest::{read_manifest_entries, read_manifest_list};
+pub use manifest::{
+ ManifestEntryBatchReader, ManifestListBatchReader, read_manifest_entries,
read_manifest_list,
+};
mod reader;
/// RecordBatch projection utilities
pub mod record_batch_projector;