This is an automated email from the ASF dual-hosted git repository. github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/main/pr-11877-56888dc8dae55aad361604421b85e2a22d68647f in repository https://gitbox.apache.org/repos/asf/arrow-rs.git
commit 36351ef7f641e776759ea7a92372979a2527cd4d Author: Dejan Krakovic <[email protected]> AuthorDate: Wed Nov 4 17:12:55 2026 +0000 Parquet: map the FILE logical type to the arrow.parquet.file extension type (#11877) # Which issue does this PR close? - Closes #11876. # Rationale for this change #10109 added the Parquet `FILE` logical type, but not its Arrow mapping. A `FILE` group reads as a plain struct, and `ArrowWriter` cannot write the annotation, so Arrow-based writers cannot produce conforming `FILE` columns. # What changes are included in this PR? Following the Variant precedent: - A new `parquet::arrow::file_type::FileType` extension type, named `arrow.parquet.file`, with no metadata. Its storage is a struct whose fields are any subset of `uri`, `offset`, `size`, `content_type`, `checksum`, `inline`, each nullable, matching the Parquet-side validation from #10109 (string fields accept `Utf8`/`LargeUtf8`/`Utf8View`, `inline` accepts any binary type). - Read: `try_add_extension_type` / `has_extension_type` tag a `FILE` group with `FileType`. - Write: `logical_type_for_struct` returns `LogicalType::File` for a struct field with `FileType`; its gating now covers either `variant_experimental` or `file_experimental`. Sub-field ids come from the existing `PARQUET:field_id` metadata. - A `file_experimental` feature (also part of `experimental`), documented in the README and crate docs, and a CI compile check with `--no-default-features --features file_experimental`. # Are these changes tested? Yes, in `parquet/src/arrow/file_type.rs`: accepted and rejected struct shapes, an Arrow to Parquet to Arrow schema round trip (annotation and field ids), a struct without the extension staying unannotated, and `ArrowWriter` write and read round trips at the top level and as a list element. Locally: `cargo test -p parquet --all-features --lib` passes, `cargo clippy -p parquet --all-targets --all-features -- -D warnings` is clean, docs build with `-D warnings`, and `cargo check -p parquet` passes with default features, `variant_experimental` only, and `file_experimental` only. # Are there any user-facing changes? A new, experimental, opt-in `file_experimental` feature and `FileType` extension type. No change without the feature. The code, tests, and this description were drafted with an AI assistant and reviewed by me before submitting. This pull request and its description were written by Isaac. --------- Signed-off-by: Dejan Krakovic <[email protected]> Co-authored-by: dejankrak-db <[email protected]> Co-authored-by: Isaac <[email protected]> --- .github/workflows/parquet.yml | 2 + parquet/Cargo.toml | 4 +- parquet/README.md | 2 + parquet/src/arrow/file_type.rs | 384 ++++++++++++++++++++++++++++++++++ parquet/src/arrow/mod.rs | 2 + parquet/src/arrow/schema/extension.rs | 42 ++-- parquet/src/lib.rs | 10 + 7 files changed, 429 insertions(+), 17 deletions(-) diff --git a/.github/workflows/parquet.yml b/.github/workflows/parquet.yml index af1fb4ddff..7388b0b8af 100644 --- a/.github/workflows/parquet.yml +++ b/.github/workflows/parquet.yml @@ -121,6 +121,8 @@ jobs: run: cargo check -p parquet --no-default-features --features flate2 --features flate2-zlib-rs - name: Check compilation --no-default-features --features variant_experimental run: cargo check -p parquet --no-default-features --features variant_experimental + - name: Check compilation --no-default-features --features file_experimental + run: cargo check -p parquet --no-default-features --features file_experimental - name: Check compilation (parquet-variant) run: cargo check -p parquet-variant - name: Check compilation (parquet-variant-json) diff --git a/parquet/Cargo.toml b/parquet/Cargo.toml index 46999dd85c..1623708523 100644 --- a/parquet/Cargo.toml +++ b/parquet/Cargo.toml @@ -115,7 +115,7 @@ json = ["serde_json", "base64"] # Enable internal testing APIs test_common = ["arrow/test_utils"] # Experimental, unstable functionality primarily used for testing -experimental = ["variant_experimental"] +experimental = ["variant_experimental", "file_experimental"] # Enable async APIs async = ["futures", "tokio"] # Enable object_store integration @@ -136,6 +136,8 @@ flate2-rust_backend = ["flate2/rust_backend"] flate2-zlib-rs = ["flate2/zlib-rs"] # Enable parquet variant support variant_experimental = ["arrow", "parquet-variant", "parquet-variant-compute"] +# Enable parquet FILE logical type support +file_experimental = ["arrow"] # Enable geospatial support geospatial = ["parquet-geospatial"] # Alias for typo. TODO: Remove in future major version bump. diff --git a/parquet/README.md b/parquet/README.md index 8fb48856fe..382b6dbb2b 100644 --- a/parquet/README.md +++ b/parquet/README.md @@ -65,11 +65,13 @@ The `parquet` crate provides the following features which may be enabled in your - `simdutf8` (default) - Use the [`simdutf8`] crate for SIMD-accelerated UTF-8 validation - `encryption` - support for reading / writing encrypted Parquet files - `variant_experimental` - ⚠️ Experimental [Parquet Variant] support, which may change, even between minor releases. +- `file_experimental` - ⚠️ Experimental [Parquet FILE] logical type support, which may change, even between minor releases. - `geospatial` - ⚠️ Experimental geospatial support, which may change, even between minor releases. [`arrow`]: https://crates.io/crates/arrow [`simdutf8`]: https://crates.io/crates/simdutf8 [parquet variant]: https://github.com/apache/parquet-format/blob/master/VariantEncoding.md +[parquet file]: https://github.com/apache/parquet-format/blob/master/LogicalTypes.md#file ## Parquet Feature Status diff --git a/parquet/src/arrow/file_type.rs b/parquet/src/arrow/file_type.rs new file mode 100644 index 0000000000..d89f294281 --- /dev/null +++ b/parquet/src/arrow/file_type.rs @@ -0,0 +1,384 @@ +// 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. + +//! Arrow extension type for the Parquet [`FILE`] logical type. +//! +//! [`FILE`]: https://github.com/apache/parquet-format/blob/master/LogicalTypes.md#file + +use arrow_schema::extension::ExtensionType; +use arrow_schema::{ArrowError, DataType}; + +/// Arrow extension type for the Parquet [`FILE`] logical type. +/// +/// A `FILE` value is a reference to a range of bytes, stored inline or in an +/// external file. Its Arrow storage type is a struct whose fields are a subset +/// of the following, each nullable, identified by name, in any order: +/// +/// | Field | Arrow type | +/// |----------------|---------------------------------------------| +/// | `uri` | `Utf8`, `LargeUtf8`, or `Utf8View` | +/// | `offset` | `Int64` | +/// | `size` | `Int64` | +/// | `content_type` | `Utf8`, `LargeUtf8`, or `Utf8View` | +/// | `checksum` | `Utf8`, `LargeUtf8`, or `Utf8View` | +/// | `inline` | `Binary`, `LargeBinary`, or `BinaryView` | +/// +/// When reading, a `FILE`-annotated group is returned as a struct with this +/// extension type. When writing, a struct field with this extension type is +/// written as a `FILE`-annotated group. +/// +/// If the file has an embedded Arrow schema, a reader takes each field's +/// metadata from it rather than from the Parquet annotation. A `FILE`-annotated +/// group that the embedded schema describes as a plain struct is then read +/// without this extension type. To get the extension type in that case, read +/// with [`ArrowReaderOptions::with_skip_arrow_metadata`] set to `true`. +/// +/// The extension name is `arrow.parquet.file`, which is the intended name for +/// a canonical Arrow extension type; it is not yet standardized. +/// +/// [`FILE`]: https://github.com/apache/parquet-format/blob/master/LogicalTypes.md#file +/// [`ArrowReaderOptions::with_skip_arrow_metadata`]: crate::arrow::arrow_reader::ArrowReaderOptions::with_skip_arrow_metadata +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +pub struct FileType; + +impl ExtensionType for FileType { + const NAME: &'static str = "arrow.parquet.file"; + + type Metadata = &'static str; + + fn metadata(&self) -> &Self::Metadata { + &"" + } + + fn serialize_metadata(&self) -> Option<String> { + Some(String::new()) + } + + fn deserialize_metadata(metadata: Option<&str>) -> Result<Self::Metadata, ArrowError> { + match metadata { + None | Some("") => Ok(""), + Some(_) => Err(ArrowError::InvalidArgumentError( + "FileType extension type expects no metadata".to_owned(), + )), + } + } + + fn supports_data_type(&self, data_type: &DataType) -> Result<(), ArrowError> { + let DataType::Struct(fields) = data_type else { + return Err(ArrowError::InvalidArgumentError(format!( + "FileType only supports a struct, got {data_type}" + ))); + }; + for (i, field) in fields.iter().enumerate() { + let name = field.name(); + if fields[..i].iter().any(|f| f.name() == name) { + return Err(ArrowError::InvalidArgumentError(format!( + "FileType struct has duplicate field '{name}'" + ))); + } + let type_ok = match name.as_str() { + "uri" | "content_type" | "checksum" => matches!( + field.data_type(), + DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View + ), + "offset" | "size" => field.data_type() == &DataType::Int64, + "inline" => matches!( + field.data_type(), + DataType::Binary | DataType::LargeBinary | DataType::BinaryView + ), + _ => { + return Err(ArrowError::InvalidArgumentError(format!( + "FileType struct has unrecognized field '{name}'. \ + Valid fields are: uri, offset, size, content_type, checksum, inline" + ))); + } + }; + if !type_ok { + return Err(ArrowError::InvalidArgumentError(format!( + "FileType field '{name}' has unsupported type {}", + field.data_type() + ))); + } + if !field.is_nullable() { + return Err(ArrowError::InvalidArgumentError(format!( + "FileType field '{name}' must be nullable" + ))); + } + } + Ok(()) + } + + fn try_new(data_type: &DataType, _metadata: Self::Metadata) -> Result<Self, ArrowError> { + Self.supports_data_type(data_type)?; + Ok(Self) + } + + fn validate(data_type: &DataType, _metadata: Self::Metadata) -> Result<(), ArrowError> { + Self.supports_data_type(data_type) + } +} + +#[cfg(test)] +mod tests { + use std::collections::HashMap; + use std::sync::Arc; + + use arrow_array::{ + Array, ArrayRef, BinaryArray, Int64Array, ListArray, RecordBatch, StringArray, StructArray, + }; + use arrow_buffer::OffsetBuffer; + use arrow_schema::{Field, Fields, Schema}; + use bytes::Bytes; + + use super::*; + use crate::arrow::arrow_reader::ParquetRecordBatchReaderBuilder; + use crate::arrow::{ArrowSchemaConverter, ArrowWriter, PARQUET_FIELD_ID_META_KEY}; + use crate::basic::LogicalType; + + fn file_fields(first_id: Option<i32>) -> Fields { + let field = |name: &str, data_type: DataType, offset: i32| { + let field = Field::new(name, data_type, true); + match first_id { + Some(id) => field.with_metadata(HashMap::from([( + PARQUET_FIELD_ID_META_KEY.to_string(), + (id + offset).to_string(), + )])), + None => field, + } + }; + Fields::from(vec![ + field("uri", DataType::Utf8, 1), + field("offset", DataType::Int64, 2), + field("size", DataType::Int64, 3), + field("content_type", DataType::Utf8, 4), + field("checksum", DataType::Utf8, 5), + field("inline", DataType::Binary, 6), + ]) + } + + fn file_field(name: &str, fields: Fields) -> Field { + Field::new(name, DataType::Struct(fields), true).with_extension_type(FileType) + } + + #[test] + fn supports_valid_data_types() { + let cases = [ + file_fields(None), + Fields::from(vec![ + Field::new("size", DataType::Int64, true), + Field::new("uri", DataType::Utf8View, true), + ]), + Fields::from(vec![ + Field::new("uri", DataType::LargeUtf8, true), + Field::new("inline", DataType::BinaryView, true), + ]), + ]; + for fields in cases { + FileType + .supports_data_type(&DataType::Struct(fields)) + .unwrap(); + } + } + + #[test] + fn rejects_invalid_data_types() { + let cases = [ + (DataType::Utf8, "only supports a struct"), + ( + DataType::Struct(Fields::from(vec![Field::new("path", DataType::Utf8, true)])), + "unrecognized field 'path'", + ), + ( + DataType::Struct(Fields::from(vec![Field::new( + "size", + DataType::Int32, + true, + )])), + "field 'size' has unsupported type", + ), + ( + DataType::Struct(Fields::from(vec![Field::new("uri", DataType::Utf8, false)])), + "field 'uri' must be nullable", + ), + ( + DataType::Struct(Fields::from(vec![ + Field::new("uri", DataType::Utf8, true), + Field::new("uri", DataType::Utf8, true), + ])), + "duplicate field 'uri'", + ), + ]; + for (data_type, expected) in cases { + let error = FileType + .supports_data_type(&data_type) + .unwrap_err() + .to_string(); + assert!(error.contains(expected), "{data_type}: {error}"); + } + } + + #[test] + fn schema_round_trip() { + let arrow_schema = Schema::new(vec![ + Field::new("f", DataType::Struct(file_fields(Some(1))), true) + .with_metadata(HashMap::from([( + PARQUET_FIELD_ID_META_KEY.to_string(), + "1".to_string(), + )])) + .with_extension_type(FileType), + ]); + let parquet_schema = ArrowSchemaConverter::new().convert(&arrow_schema).unwrap(); + let group = &parquet_schema.root_schema().get_fields()[0]; + assert_eq!( + group.get_basic_info().logical_type_ref(), + Some(&LogicalType::File) + ); + assert_eq!(group.get_basic_info().id(), 1); + let ids: Vec<_> = group + .get_fields() + .iter() + .map(|f| f.get_basic_info().id()) + .collect(); + assert_eq!(ids, (2..=7).collect::<Vec<_>>()); + + let arrow_schema = crate::arrow::parquet_to_arrow_schema(&parquet_schema, None).unwrap(); + assert_eq!( + arrow_schema + .field(0) + .try_extension_type::<FileType>() + .unwrap(), + FileType + ); + } + + #[test] + fn struct_without_extension_is_not_annotated() { + let arrow_schema = Schema::new(vec![Field::new( + "f", + DataType::Struct(file_fields(None)), + true, + )]); + let parquet_schema = ArrowSchemaConverter::new().convert(&arrow_schema).unwrap(); + assert_eq!( + parquet_schema.root_schema().get_fields()[0] + .get_basic_info() + .logical_type_ref(), + None + ); + } + + #[test] + fn struct_with_unknown_metadata_is_not_annotated() { + let field = Field::new("f", DataType::Struct(file_fields(None)), true).with_metadata( + HashMap::from([ + ( + "ARROW:extension:name".to_string(), + FileType::NAME.to_string(), + ), + ("ARROW:extension:metadata".to_string(), "v2".to_string()), + ]), + ); + assert!(field.try_extension_type::<FileType>().is_err()); + let parquet_schema = ArrowSchemaConverter::new() + .convert(&Schema::new(vec![field])) + .unwrap(); + assert_eq!( + parquet_schema.root_schema().get_fields()[0] + .get_basic_info() + .logical_type_ref(), + None + ); + } + + fn file_values(fields: Fields) -> StructArray { + StructArray::new( + fields, + vec![ + Arc::new(StringArray::from(vec![Some("s3://b/a.png"), None])) as ArrayRef, + Arc::new(Int64Array::from(vec![Some(4), None])), + Arc::new(Int64Array::from(vec![Some(10), None])), + Arc::new(StringArray::from(vec![Some("image/png"), None])), + Arc::new(StringArray::from(vec![None::<&str>, None])), + Arc::new(BinaryArray::from(vec![None, Some(b"xyz".as_slice())])), + ], + None, + ) + } + + fn write_and_read(batch: &RecordBatch) -> (crate::schema::types::TypePtr, RecordBatch) { + let mut buffer = Vec::new(); + let mut writer = ArrowWriter::try_new(&mut buffer, batch.schema(), None).unwrap(); + writer.write(batch).unwrap(); + writer.close().unwrap(); + let builder = ParquetRecordBatchReaderBuilder::try_new(Bytes::from(buffer)).unwrap(); + let root = builder + .metadata() + .file_metadata() + .schema_descr() + .root_schema_ptr(); + let read = builder.build().unwrap().next().unwrap().unwrap(); + (root, read) + } + + #[test] + fn writer_round_trip() { + let values = file_values(file_fields(None)); + let schema = Schema::new(vec![file_field("f", values.fields().clone())]); + let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(values.clone())]).unwrap(); + + let (root, read) = write_and_read(&batch); + + assert_eq!( + root.get_fields()[0].get_basic_info().logical_type_ref(), + Some(&LogicalType::File) + ); + assert_eq!( + read.schema() + .field(0) + .try_extension_type::<FileType>() + .unwrap(), + FileType + ); + assert_eq!(read.column(0).as_ref(), &values as &dyn Array); + } + + #[test] + fn writer_round_trip_in_list() { + let values = file_values(file_fields(None)); + let element = Arc::new(file_field("element", values.fields().clone())); + let list = ListArray::new( + element, + OffsetBuffer::from_lengths([2]), + Arc::new(values), + None, + ); + let schema = Schema::new(vec![Field::new("a", list.data_type().clone(), true)]); + let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(list)]).unwrap(); + + let (root, read) = write_and_read(&batch); + + let element = &root.get_fields()[0].get_fields()[0].get_fields()[0]; + assert_eq!( + element.get_basic_info().logical_type_ref(), + Some(&LogicalType::File) + ); + let DataType::List(element) = read.schema().field(0).data_type().clone() else { + panic!("expected a list"); + }; + assert_eq!(element.try_extension_type::<FileType>().unwrap(), FileType); + } +} diff --git a/parquet/src/arrow/mod.rs b/parquet/src/arrow/mod.rs index 1ebb2321a0..bc4190389a 100644 --- a/parquet/src/arrow/mod.rs +++ b/parquet/src/arrow/mod.rs @@ -192,6 +192,8 @@ pub(crate) use array_reader::ByteArrayDecoderPlain; pub mod arrow_reader; pub mod arrow_writer; mod buffer; +#[cfg(feature = "file_experimental")] +pub mod file_type; pub(crate) use buffer::offset_buffer::OffsetBuffer; mod decoder; diff --git a/parquet/src/arrow/schema/extension.rs b/parquet/src/arrow/schema/extension.rs index 11bb97eb59..025ebe96af 100644 --- a/parquet/src/arrow/schema/extension.rs +++ b/parquet/src/arrow/schema/extension.rs @@ -53,6 +53,12 @@ pub(crate) fn try_add_extension_type( arrow_field.try_with_extension_type(parquet_variant_compute::VariantType)?; arrow_field } + #[cfg(feature = "file_experimental")] + LogicalType::File => { + let mut arrow_field = arrow_field; + arrow_field.try_with_extension_type(crate::arrow::file_type::FileType)?; + arrow_field + } #[cfg(feature = "arrow_canonical_extension_types")] LogicalType::Uuid => { let mut arrow_field = arrow_field; @@ -110,6 +116,8 @@ pub(crate) fn has_extension_type(parquet_type: &Type) -> bool { match parquet_logical_type { #[cfg(feature = "variant_experimental")] LogicalType::Variant { .. } => true, + #[cfg(feature = "file_experimental")] + LogicalType::File => true, #[cfg(feature = "arrow_canonical_extension_types")] LogicalType::Uuid => true, #[cfg(feature = "arrow_canonical_extension_types")] @@ -122,26 +130,28 @@ pub(crate) fn has_extension_type(parquet_type: &Type) -> bool { } } -/// Return the Parquet logical type to use for the specified Arrow Struct field, if any. -/// -/// The Parquet specification requires the `VARIANT` logical type annotation to -/// carry the version number (`VARIANT(1)`); readers such as Apache Spark reject -/// files whose annotation does not carry version 1. The value written is -/// [`parquet_variant::VARIANT_SPEC_VERSION`], the same version stamped into -/// every metadata header. -#[cfg(feature = "variant_experimental")] +/// Return the Parquet logical type to use for the specified Arrow Struct field, if any: +/// `VARIANT` for the Variant extension type and `FILE` for `FileType`. +#[cfg(any(feature = "variant_experimental", feature = "file_experimental"))] pub(crate) fn logical_type_for_struct(field: &Field) -> Option<LogicalType> { - use parquet_variant::VARIANT_SPEC_VERSION; - use parquet_variant_compute::VariantType; - if field.has_valid_extension_type::<VariantType>() { - // The 4-bit header version always fits the thrift `i8` field. - Some(LogicalType::variant(Some(VARIANT_SPEC_VERSION as i8))) - } else { - None + #[cfg(feature = "variant_experimental")] + if field.has_valid_extension_type::<parquet_variant_compute::VariantType>() { + // The Parquet specification requires the annotation to carry the version + // (`VARIANT(1)`), and readers such as Apache Spark reject files without it. + // Write the version stamped into every metadata header; the 4-bit header + // version always fits the thrift `i8` field. + return Some(LogicalType::variant(Some( + parquet_variant::VARIANT_SPEC_VERSION as i8, + ))); + } + #[cfg(feature = "file_experimental")] + if field.has_valid_extension_type::<crate::arrow::file_type::FileType>() { + return Some(LogicalType::File); } + None } -#[cfg(not(feature = "variant_experimental"))] +#[cfg(not(any(feature = "variant_experimental", feature = "file_experimental")))] pub(crate) fn logical_type_for_struct(_field: &Field) -> Option<LogicalType> { None } diff --git a/parquet/src/lib.rs b/parquet/src/lib.rs index 881782353e..cef5727838 100644 --- a/parquet/src/lib.rs +++ b/parquet/src/lib.rs @@ -122,6 +122,16 @@ //! //! [Variant Binary Encoding]: https://github.com/apache/parquet-format/blob/master/VariantEncoding.md //! +//! ## FILE Logical Type (`file_experimental` feature) +//! +//! The [`FileType`] Arrow extension type maps to the Parquet [FILE] logical +//! type: a `FILE`-annotated group is read as a struct with this extension +//! type, and a struct field with this extension type is written as a +//! `FILE`-annotated group. +//! +//! [`FileType`]: arrow::file_type::FileType +//! [FILE]: https://github.com/apache/parquet-format/blob/master/LogicalTypes.md#file +//! //! ## Read/Write Parquet Directly //! //! Workloads needing finer-grained control, or to avoid a dependence on arrow,
