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-11144-67f96ac9f0869f4a6f44698be1574dd585793a33
in repository https://gitbox.apache.org/repos/asf/arrow-rs.git

commit f9c8085476d0cdd77605d69d5114b2f98808106f
Author: Muhammad Hassaan <[email protected]>
AuthorDate: Mon Nov 23 19:16:07 2026 +0000

    fix(parquet): validate UTF-8 when a supplied schema reads binary as a 
string (#11144)
    
    # Which issue does this PR close?
    
    - Closes #11140.
    
    This is also the root cause of
    
[apache/datafusion#25509](https://github.com/apache/datafusion/issues/25509).
    
    # Rationale for this change
    
    The byte array and byte view decoders validate UTF-8 only for columns
    annotated as strings. A schema passed to
    `ArrowReaderOptions::with_schema` can read an unannotated `BYTE_ARRAY`
    column as `Utf8`, `LargeUtf8` or `Utf8View`, and the reader then builds
    a string array from unvalidated bytes. That panics in debug builds and
    produces an invalid array in release builds. #12161 already covers the
    dictionary reader.
    
    # What changes are included in this PR?
    
    - `ColumnValueDecoder::set_validate_utf8` is a no-op by default. The
    byte array and byte view decoders override it, and
    `make_byte_array_reader` and `make_byte_view_array_reader` turn it on
    when they build a string type.
    - `GenericRecordReader` keeps the flag and passes it to the decoder that
    each `set_page_reader` call creates.
    - The `DELTA_LENGTH_BYTE_ARRAY` decoders and the byte view
    `DELTA_BYTE_ARRAY` decoder validated their values back to back, which
    misses a character split across two values. They now also check that
    each value starts on a character boundary, as `OffsetBuffer::try_push`
    already did. That check is now `check_utf8_value_start`, shared by all
    four. It applies to columns annotated as strings too.
    - Because the flag comes from the Arrow type, `JSON` columns, which are
    read as `Utf8`, are validated as well.
    
    # Are these changes tested?
    
    Yes, in `parquet/src/arrow/arrow_reader/tests/schema.rs`, over five
    encodings: dictionary, dictionary falling back to PLAIN, PLAIN,
    `DELTA_LENGTH_BYTE_ARRAY` and `DELTA_BYTE_ARRAY`. `write_with_encodings`
    now checks the data pages' encodings exactly, using
    `page_encoding_stats_mask`.
    
    - `test_read_non_utf8_binary_as_utf8` reads two invalid inputs into
    `Utf8`, `LargeUtf8`, `Utf8View` and dictionaries of each. One input is
    invalid bytes; the other is `[b"\xC2", b"\xA2"]`, two invalid values
    that form a valid character back to back.
    - `test_read_non_utf8_binary_as_utf8_in_second_row_group` reads invalid
    data in the second of two row groups.
    - `test_read_non_utf8_json` reads a `JSON` column with invalid data.
    
    Without the per-value check, reading the split character panics as
    `Utf8` in a debug build and returns no error as `Utf8View`. If
    `set_page_reader` doesn't pass on the flag, the second row group test
    fails.
    
    `cargo test -p parquet` and `cargo test -p parquet --all-features` pass,
    `cargo clippy -p parquet --all-targets --all-features -- -D warnings` is
    clean, and `cargo fmt --all -- --check` passes.
    
    # Are there any user-facing changes?
    
    - Reading a non-string column as a string type through a supplied schema
    returns an error instead of panicking or producing an invalid array.
    - `JSON` columns with invalid UTF-8, and `DELTA_LENGTH_BYTE_ARRAY` or
    `DELTA_BYTE_ARRAY` string columns whose values split a character, now
    return an error.
    
    There are no public API changes: `ColumnValueDecoder` is in a
    `pub(crate)` module, `GenericRecordReader` in a private one, and
    `check_utf8_value_start` is `pub(crate)`.
    
    # AI disclosure
    
    Per
    
[CONTRIBUTING.md](https://github.com/apache/arrow-rs/blob/main/CONTRIBUTING.md#ai-generated-submissions):
    this PR was written with AI assistance (Claude Code). I reviewed the
    design, the verification and this description, and ran the commands
    quoted here locally.
    
    🤖 Generated with [Claude Code](https://claude.com/claude-code)
    
    ---------
    
    Co-authored-by: Claude Opus 5 <[email protected]>
    Co-authored-by: Andrew Lamb <[email protected]>
---
 parquet/src/arrow/array_reader/byte_array.rs      |  16 ++
 parquet/src/arrow/array_reader/byte_view_array.rs |  22 +-
 parquet/src/arrow/arrow_reader/tests/schema.rs    | 309 +++++++++++++++++-----
 parquet/src/arrow/buffer/offset_buffer.rs         |  12 +-
 parquet/src/arrow/record_reader/mod.rs            |  12 +-
 parquet/src/column/reader/decoder.rs              |   6 +
 parquet/src/util/utf8.rs                          |  14 +
 7 files changed, 319 insertions(+), 72 deletions(-)

diff --git a/parquet/src/arrow/array_reader/byte_array.rs 
b/parquet/src/arrow/array_reader/byte_array.rs
index 07f1593f5c..17c125e085 100644
--- a/parquet/src/arrow/array_reader/byte_array.rs
+++ b/parquet/src/arrow/array_reader/byte_array.rs
@@ -15,6 +15,7 @@ use crate::data_type::Int32Type;
 use crate::encodings::decoding::{Decoder, DeltaBitPackDecoder};
 use crate::errors::{ParquetError, Result};
 use crate::schema::types::ColumnDescPtr;
+use crate::util::utf8::check_utf8_value_start;
 use arrow_array::{
     Array, ArrayRef, BinaryArray, Decimal128Array, Decimal256Array, 
OffsetSizeTrait,
 };
@@ -40,6 +41,9 @@ pub fn make_byte_array_reader(
             .clone(),
     };
 
+    // A supplied schema can read an unannotated `BYTE_ARRAY` column as a 
string.
+    let validate_utf8 = matches!(data_type, ArrowType::Utf8 | 
ArrowType::LargeUtf8);
+
     match data_type {
         ArrowType::Binary
         | ArrowType::Utf8
@@ -49,6 +53,7 @@ pub fn make_byte_array_reader(
             if let Some(threshold) = padding_threshold {
                 reader.set_padding_threshold(threshold);
             }
+            reader.set_validate_utf8(validate_utf8);
             Ok(Box::new(ByteArrayReader::<i32>::new(
                 pages, data_type, reader,
             )))
@@ -58,6 +63,7 @@ pub fn make_byte_array_reader(
             if let Some(threshold) = padding_threshold {
                 reader.set_padding_threshold(threshold);
             }
+            reader.set_validate_utf8(validate_utf8);
             Ok(Box::new(ByteArrayReader::<i64>::new(
                 pages, data_type, reader,
             )))
@@ -184,6 +190,10 @@ impl<I: OffsetSizeTrait> ColumnValueDecoder for 
ByteArrayColumnValueDecoder<I> {
         }
     }
 
+    fn set_validate_utf8(&mut self, validate_utf8: bool) {
+        self.validate_utf8 = validate_utf8;
+    }
+
     fn set_dict(
         &mut self,
         buf: Bytes,
@@ -512,6 +522,12 @@ impl ByteArrayDecoderDeltaLength {
         self.length_offset += to_read;
 
         if self.validate_utf8 {
+            let mut start = initial_values_length;
+            for length in src_lengths {
+                let end = start + *length as usize;
+                check_utf8_value_start(&output.values[start..end])?;
+                start = end;
+            }
             output.check_valid_utf8(initial_values_length)?;
         }
         Ok(to_read)
diff --git a/parquet/src/arrow/array_reader/byte_view_array.rs 
b/parquet/src/arrow/array_reader/byte_view_array.rs
index 38c27e7928..6e0a0c3e92 100644
--- a/parquet/src/arrow/array_reader/byte_view_array.rs
+++ b/parquet/src/arrow/array_reader/byte_view_array.rs
@@ -14,7 +14,7 @@ use crate::data_type::Int32Type;
 use crate::encodings::decoding::{Decoder, DeltaBitPackDecoder};
 use crate::errors::{ParquetError, Result};
 use crate::schema::types::ColumnDescPtr;
-use crate::util::utf8::check_valid_utf8;
+use crate::util::utf8::{check_utf8_value_start, check_valid_utf8};
 use arrow_array::{ArrayRef, builder::make_view};
 use arrow_buffer::Buffer;
 use arrow_data::ByteView;
@@ -44,12 +44,16 @@ pub fn make_byte_view_array_reader(
         },
     };
 
+    // A supplied schema can read an unannotated `BYTE_ARRAY` column as a 
string.
+    let validate_utf8 = matches!(data_type, ArrowType::Utf8View);
+
     match data_type {
         ArrowType::BinaryView | ArrowType::Utf8View => {
             let mut reader = GenericRecordReader::new(column_desc, batch_size);
             if let Some(threshold) = padding_threshold {
                 reader.set_padding_threshold(threshold);
             }
+            reader.set_validate_utf8(validate_utf8);
             Ok(Box::new(ByteViewArrayReader::new(pages, data_type, reader)))
         }
 
@@ -146,6 +150,10 @@ impl ColumnValueDecoder for 
ByteViewArrayColumnValueDecoder {
         }
     }
 
+    fn set_validate_utf8(&mut self, validate_utf8: bool) {
+        self.validate_utf8 = validate_utf8;
+    }
+
     fn set_dict(
         &mut self,
         buf: Bytes,
@@ -626,8 +634,15 @@ impl ByteViewArrayDecoderDeltaLength {
             )
         }));
 
-        // Delta length encoding has continuous strings, we can validate utf8 
in one go
+        // Delta length encoding has continuous strings, so validate utf8 in 
one go
+        // once each string is known to start on a character boundary
         if self.validate_utf8 {
+            let mut start = initial_offset;
+            for length in src_lengths {
+                let end = start + *length as usize;
+                check_utf8_value_start(&self.data[start..end])?;
+                start = end;
+            }
             check_valid_utf8(&self.data[initial_offset..current_offset])?;
         }
 
@@ -711,6 +726,9 @@ impl ByteViewArrayDecoderDelta {
             let mut utf8_validation_buffer = Vec::with_capacity(4096);
 
             let v = self.decoder.read(len, |bytes| {
+                // Both buffers are validated whole, so each string must also 
start
+                // on a character boundary
+                check_utf8_value_start(bytes)?;
                 let offset = array_buffer.len();
                 let view = make_view(bytes, buffer_id, offset as u32);
                 if bytes.len() > 12 {
diff --git a/parquet/src/arrow/arrow_reader/tests/schema.rs 
b/parquet/src/arrow/arrow_reader/tests/schema.rs
index 1a8d2ed8c1..24fbdfb8ef 100644
--- a/parquet/src/arrow/arrow_reader/tests/schema.rs
+++ b/parquet/src/arrow/arrow_reader/tests/schema.rs
@@ -5,6 +5,9 @@
 //! Schema inference, supplied schemas, type conversions, and column 
projection.
 
 use super::*;
+use crate::arrow::arrow_writer::ArrowWriterOptions;
+use crate::basic::EncodingMask;
+use crate::schema::types::SchemaDescriptor;
 
 #[test]
 fn test_arrow_reader_all_columns() {
@@ -550,34 +553,102 @@ fn test_schema_error_bad_nullability() {
     )
 }
 
+/// The ways a byte array column is written, with the encodings each produces:
+/// dictionary pages (the default), dictionary pages that fall back to PLAIN
+/// part way through the column chunk, and PLAIN, DELTA_LENGTH_BYTE_ARRAY and
+/// DELTA_BYTE_ARRAY pages without a dictionary.
+fn byte_array_encodings() -> Vec<(Vec<Encoding>, WriterProperties)> {
+    let without_dictionary = |encoding| {
+        WriterProperties::builder()
+            .set_dictionary_enabled(false)
+            .set_encoding(encoding)
+            .build()
+    };
+    // A one-byte limit makes the writer abandon the dictionary after the
+    // first value.
+    let dictionary_fallback = WriterProperties::builder()
+        .set_dictionary_page_size_limit(1)
+        .set_write_batch_size(1)
+        .build();
+    vec![
+        (vec![Encoding::RLE_DICTIONARY], WriterProperties::default()),
+        (
+            vec![Encoding::RLE_DICTIONARY, Encoding::PLAIN],
+            dictionary_fallback,
+        ),
+        (vec![Encoding::PLAIN], without_dictionary(Encoding::PLAIN)),
+        (
+            vec![Encoding::DELTA_LENGTH_BYTE_ARRAY],
+            without_dictionary(Encoding::DELTA_LENGTH_BYTE_ARRAY),
+        ),
+        (
+            vec![Encoding::DELTA_BYTE_ARRAY],
+            without_dictionary(Encoding::DELTA_BYTE_ARRAY),
+        ),
+    ]
+}
+
+/// Writes `batch` with `props`, checking that the data pages of every column
+/// used exactly `encodings`.
+fn write_with_encodings(
+    batch: &RecordBatch,
+    encodings: &[Encoding],
+    props: WriterProperties,
+) -> File {
+    let file = tempfile().unwrap();
+    let mut writer =
+        ArrowWriter::try_new(file.try_clone().unwrap(), batch.schema(), 
Some(props)).unwrap();
+    writer.write(batch).unwrap();
+    writer.close().unwrap();
+
+    let builder = 
ParquetRecordBatchReaderBuilder::try_new(file.try_clone().unwrap()).unwrap();
+    for column in builder.metadata().row_group(0).columns() {
+        // `encodings()` would also list the PLAIN encoding of a dictionary 
page
+        let data_pages = column.page_encoding_stats_mask().unwrap();
+        assert_eq!(
+            *data_pages,
+            EncodingMask::new_from_encodings(encodings.iter()),
+            "{} has data pages written as {:?}, not {encodings:?}",
+            column.column_path(),
+            data_pages.encodings().collect::<Vec<_>>()
+        );
+    }
+    file
+}
+
 #[test]
 fn test_read_binary_as_utf8() {
-    let file = write_parquet_from_iter(vec![
+    let values = vec![b"one".as_ref(), b"two".as_ref(), b"three".as_ref()];
+    let batch = RecordBatch::try_from_iter(vec![
         (
             "binary_to_utf8",
-            Arc::new(BinaryArray::from(vec![
-                b"one".as_ref(),
-                b"two".as_ref(),
-                b"three".as_ref(),
-            ])) as ArrayRef,
+            Arc::new(BinaryArray::from(values.clone())) as ArrayRef,
         ),
         (
             "large_binary_to_large_utf8",
-            Arc::new(LargeBinaryArray::from(vec![
-                b"one".as_ref(),
-                b"two".as_ref(),
-                b"three".as_ref(),
-            ])) as ArrayRef,
+            Arc::new(LargeBinaryArray::from(values.clone())) as ArrayRef,
         ),
         (
             "binary_view_to_utf8_view",
-            Arc::new(BinaryViewArray::from(vec![
-                b"one".as_ref(),
-                b"two".as_ref(),
-                b"three".as_ref(),
-            ])) as ArrayRef,
+            Arc::new(BinaryViewArray::from(values.clone())) as ArrayRef,
         ),
-    ]);
+        (
+            "binary_to_dictionary_utf8",
+            Arc::new(BinaryArray::from(values.clone())) as ArrayRef,
+        ),
+        (
+            "large_binary_to_dictionary_large_utf8",
+            Arc::new(LargeBinaryArray::from(values.clone())) as ArrayRef,
+        ),
+        (
+            "binary_to_dictionary_utf8_view",
+            Arc::new(BinaryArray::from(values)) as ArrayRef,
+        ),
+    ])
+    .unwrap();
+    let dictionary = |value_type| {
+        ArrowDataType::Dictionary(Box::new(ArrowDataType::Int32), 
Box::new(value_type))
+    };
     let supplied_fields = Fields::from(vec![
         Field::new("binary_to_utf8", ArrowDataType::Utf8, false),
         Field::new(
@@ -586,40 +657,46 @@ fn test_read_binary_as_utf8() {
             false,
         ),
         Field::new("binary_view_to_utf8_view", ArrowDataType::Utf8View, false),
+        Field::new(
+            "binary_to_dictionary_utf8",
+            dictionary(ArrowDataType::Utf8),
+            false,
+        ),
+        Field::new(
+            "large_binary_to_dictionary_large_utf8",
+            dictionary(ArrowDataType::LargeUtf8),
+            false,
+        ),
+        Field::new(
+            "binary_to_dictionary_utf8_view",
+            dictionary(ArrowDataType::Utf8View),
+            false,
+        ),
     ]);
+    let supplied_schema = Arc::new(Schema::new(supplied_fields));
 
-    let options = 
ArrowReaderOptions::new().with_schema(Arc::new(Schema::new(supplied_fields)));
-    let mut arrow_reader =
-        
ParquetRecordBatchReaderBuilder::try_new_with_options(file.try_clone().unwrap(),
 options)
+    for (encodings, props) in byte_array_encodings() {
+        let file = write_with_encodings(&batch, &encodings, props);
+        let options = 
ArrowReaderOptions::new().with_schema(Arc::clone(&supplied_schema));
+        let mut arrow_reader = 
ParquetRecordBatchReaderBuilder::try_new_with_options(file, options)
             .expect("reader builder with schema")
             .build()
             .expect("reader with schema");
 
-    let batch = arrow_reader.next().unwrap().unwrap();
-    assert_eq!(batch.num_columns(), 3);
-    assert_eq!(batch.num_rows(), 3);
-    assert_eq!(
-        batch
-            .column(0)
-            .as_string::<i32>()
-            .iter()
-            .collect::<Vec<_>>(),
-        vec![Some("one"), Some("two"), Some("three")]
-    );
-
-    assert_eq!(
-        batch
-            .column(1)
-            .as_string::<i64>()
-            .iter()
-            .collect::<Vec<_>>(),
-        vec![Some("one"), Some("two"), Some("three")]
-    );
-
-    assert_eq!(
-        batch.column(2).as_string_view().iter().collect::<Vec<_>>(),
-        vec![Some("one"), Some("two"), Some("three")]
-    );
+        let read = arrow_reader.next().unwrap().unwrap();
+        assert_eq!(read.num_rows(), 3);
+        for (field, column) in 
supplied_schema.fields().iter().zip(read.columns()) {
+            assert_eq!(column.data_type(), field.data_type(), "{encodings:?}");
+            column.to_data().validate_full().unwrap();
+            let strings = arrow_cast::cast(column, 
&ArrowDataType::Utf8).unwrap();
+            assert_eq!(
+                strings.as_string::<i32>().iter().collect::<Vec<_>>(),
+                vec![Some("one"), Some("two"), Some("three")],
+                "{} written as {encodings:?}",
+                field.name()
+            );
+        }
+    }
 }
 
 fn dictionary_type(value_type: ArrowDataType) -> ArrowDataType {
@@ -852,30 +929,142 @@ fn test_plain_binary_dictionary_rejects_invalid_utf8() {
     assert!(error.to_string().contains("non UTF-8 data"), "{error}");
 }
 
+/// A supplied schema that reads a `Binary` column as a string type must still
+/// validate UTF-8.
 #[test]
-#[should_panic(expected = "Invalid UTF8 sequence at")]
 fn test_read_non_utf8_binary_as_utf8() {
-    let file = write_parquet_from_iter(vec![(
+    let invalid_values: [&[Option<&[u8]>]; 2] = [
+        // Invalid UTF-8 after an empty value and a null, so that when the 
writer
+        // abandons the dictionary after the first value, the invalid values 
are in
+        // the PLAIN pages that follow.
+        &[
+            Some(b"".as_ref()),
+            None,
+            Some(b"\xDE\x00\xFF".as_ref()),
+            Some(b"\xDE\x01\xAA".as_ref()),
+        ],
+        // Each value is invalid, but stored back to back they form a valid "¢"
+        &[Some(b"\xC2".as_ref()), Some(b"\xA2".as_ref())],
+    ];
+    let dictionary = |value_type| {
+        ArrowDataType::Dictionary(Box::new(ArrowDataType::Int32), 
Box::new(value_type))
+    };
+
+    for ((encodings, props), values) in byte_array_encodings()
+        .into_iter()
+        .flat_map(|case| invalid_values.map(|values| (case.clone(), values)))
+    {
+        let batch = RecordBatch::try_from_iter(vec![(
+            "non_utf8_binary",
+            Arc::new(BinaryArray::from_opt_vec(values.to_vec())) as ArrayRef,
+        )])
+        .unwrap();
+        let file = write_with_encodings(&batch, &encodings, props);
+        for supplied_type in [
+            ArrowDataType::Utf8,
+            ArrowDataType::LargeUtf8,
+            ArrowDataType::Utf8View,
+            dictionary(ArrowDataType::Utf8),
+            dictionary(ArrowDataType::LargeUtf8),
+            dictionary(ArrowDataType::Utf8View),
+        ] {
+            let supplied_fields = Fields::from(vec![Field::new(
+                "non_utf8_binary",
+                supplied_type.clone(),
+                batch.schema().field(0).is_nullable(),
+            )]);
+
+            let options =
+                
ArrowReaderOptions::new().with_schema(Arc::new(Schema::new(supplied_fields)));
+            let mut arrow_reader = 
ParquetRecordBatchReaderBuilder::try_new_with_options(
+                file.try_clone().unwrap(),
+                options,
+            )
+            .expect("reader builder with schema")
+            .build()
+            .expect("reader with schema");
+
+            // Not `unwrap_err`, which would print an invalid string array
+            let Err(err) = arrow_reader.next().unwrap() else {
+                panic!("{values:?} written as {encodings:?} read as 
{supplied_type}: no error");
+            };
+            // Dictionary values are validated by 
`StringArray::try_from_binary`,
+            // which reports a split character as "Split UTF-8 codepoint"
+            assert!(
+                err.to_string().contains("UTF-8"),
+                "{values:?} written as {encodings:?} read as {supplied_type}: 
unexpected error: {err}"
+            );
+        }
+    }
+}
+
+/// Each column chunk gets a new values decoder, which must validate as well.
+#[test]
+fn test_read_non_utf8_binary_as_utf8_in_second_row_group() {
+    let batch = RecordBatch::try_from_iter(vec![(
         "non_utf8_binary",
-        Arc::new(BinaryArray::from(vec![
-            b"\xDE\x00\xFF".as_ref(),
-            b"\xDE\x01\xAA".as_ref(),
-            b"\xDE\x02\xFF".as_ref(),
-        ])) as ArrayRef,
-    )]);
+        Arc::new(BinaryArray::from(vec![b"valid".as_ref(), b"\xFF".as_ref()])) 
as ArrayRef,
+    )])
+    .unwrap();
+    let props = WriterProperties::builder()
+        .set_max_row_group_row_count(Some(1))
+        .build();
+    let file = tempfile().unwrap();
+    let mut writer =
+        ArrowWriter::try_new(file.try_clone().unwrap(), batch.schema(), 
Some(props)).unwrap();
+    writer.write(&batch).unwrap();
+    writer.close().unwrap();
+
     let supplied_fields = Fields::from(vec![Field::new(
         "non_utf8_binary",
         ArrowDataType::Utf8,
         false,
     )]);
-
     let options = 
ArrowReaderOptions::new().with_schema(Arc::new(Schema::new(supplied_fields)));
-    let mut arrow_reader =
-        
ParquetRecordBatchReaderBuilder::try_new_with_options(file.try_clone().unwrap(),
 options)
-            .expect("reader builder with schema")
-            .build()
-            .expect("reader with schema");
-    arrow_reader.next().unwrap().unwrap_err();
+    let mut arrow_reader = 
ParquetRecordBatchReaderBuilder::try_new_with_options(file, options)
+        .unwrap()
+        .with_batch_size(1)
+        .build()
+        .unwrap();
+
+    let first = arrow_reader.next().unwrap().unwrap();
+    assert_eq!(first.column(0).as_string::<i32>().value(0), "valid");
+    let Err(err) = arrow_reader.next().unwrap() else {
+        panic!("the second row group was read without an error");
+    };
+    assert!(err.to_string().contains("non UTF-8 data"), "{err}");
+}
+
+/// A `JSON` column is read as `Utf8` by default, so it must be validated as
+/// UTF-8 even though its converted type is `JSON` rather than `UTF8`.
+#[test]
+fn test_read_non_utf8_json() {
+    let batch = RecordBatch::try_from_iter([(
+        "json",
+        Arc::new(BinaryArray::from(vec![b"\"\xFF\"".as_ref()])) as ArrayRef,
+    )])
+    .unwrap();
+    let schema = parse_message_type("message schema { REQUIRED BYTE_ARRAY json 
(JSON); }").unwrap();
+    let options = ArrowWriterOptions::new()
+        .with_parquet_schema(SchemaDescriptor::new(Arc::new(schema)))
+        .with_skip_arrow_metadata(true);
+    let file = tempfile().unwrap();
+    let mut writer =
+        ArrowWriter::try_new_with_options(file.try_clone().unwrap(), 
batch.schema(), options)
+            .unwrap();
+    writer.write(&batch).unwrap();
+    writer.close().unwrap();
+
+    let mut arrow_reader = ParquetRecordBatchReader::try_new(file, 
1024).unwrap();
+    assert_eq!(
+        arrow_reader.schema().field(0).data_type(),
+        &ArrowDataType::Utf8
+    );
+    let err = arrow_reader.next().unwrap().unwrap_err();
+    assert!(
+        err.to_string().contains("encountered non UTF-8 data"),
+        "unexpected error: {err}"
+    );
 }
 
 #[test]
diff --git a/parquet/src/arrow/buffer/offset_buffer.rs 
b/parquet/src/arrow/buffer/offset_buffer.rs
index 3c632f954b..ec95c8f876 100644
--- a/parquet/src/arrow/buffer/offset_buffer.rs
+++ b/parquet/src/arrow/buffer/offset_buffer.rs
@@ -5,7 +5,7 @@
 use crate::arrow::buffer::bit_util::iter_set_bits_rev;
 use crate::arrow::record_reader::buffer::ValuesBuffer;
 use crate::errors::{ParquetError, Result};
-use crate::util::utf8::check_valid_utf8;
+use crate::util::utf8::{check_utf8_value_start, check_valid_utf8};
 use arrow_array::{ArrayRef, OffsetSizeTrait, make_array};
 use arrow_buffer::{ArrowNativeType, Buffer};
 use arrow_data::ArrayDataBuilder;
@@ -52,14 +52,8 @@ impl<I: OffsetSizeTrait> OffsetBuffer<I> {
     // DELTA_BYTE_ARRAY decoders, and is otherwise not inlined into their loops
     #[inline(always)]
     pub fn try_push(&mut self, data: &[u8], validate_utf8: bool) -> Result<()> 
{
-        if validate_utf8 && let Some(&b) = data.first() {
-            // A valid code-point iff it does not start with 0b10xxxxxx
-            // Bit-magic taken from `std::str::is_char_boundary`
-            if (b as i8) < -0x40 {
-                return Err(ParquetError::General(
-                    "encountered non UTF-8 data".to_string(),
-                ));
-            }
+        if validate_utf8 {
+            check_utf8_value_start(data)?;
         }
 
         self.values.extend_from_slice(data);
diff --git a/parquet/src/arrow/record_reader/mod.rs 
b/parquet/src/arrow/record_reader/mod.rs
index 63000b6c7d..01537b9478 100644
--- a/parquet/src/arrow/record_reader/mod.rs
+++ b/parquet/src/arrow/record_reader/mod.rs
@@ -66,6 +66,9 @@ pub struct GenericRecordReader<V, CV> {
     /// copied, and item-level nulls are padded. The companion `compact_bitmap`
     /// has the same compact length and becomes the leaf null bitmap.
     padding_threshold: Option<i16>,
+    /// Kept here because [`Self::set_page_reader`] creates a new values 
decoder for
+    /// every column chunk.
+    validate_utf8: bool,
     /// Compact bitmap accumulated during selective padding. Each bit
     /// corresponds to an item-level entry (def >= threshold): set when the
     /// value is real (def >= max_def), unset for item-level nulls. Used both
@@ -101,13 +104,15 @@ where
             values_written: 0,
             padding_threshold: None,
             compact_bitmap: None,
+            validate_utf8: false,
         }
     }
 
     /// Set the current page reader.
     pub fn set_page_reader(&mut self, page_reader: Box<dyn PageReader>) -> 
Result<()> {
         let descr = &self.column_desc;
-        let values_decoder = CV::new(descr);
+        let mut values_decoder = CV::new(descr);
+        values_decoder.set_validate_utf8(self.validate_utf8);
 
         let def_level_decoder = (descr.max_def_level() != 0).then(|| {
             DefinitionLevelBufferDecoder::new(descr.max_def_level(), 
packed_null_mask(descr))
@@ -217,6 +222,11 @@ where
         self.padding_threshold = Some(threshold);
     }
 
+    /// Validate decoded values as UTF-8 even if the column is not annotated 
as a string.
+    pub fn set_validate_utf8(&mut self, validate_utf8: bool) {
+        self.validate_utf8 = validate_utf8;
+    }
+
     /// Returns the number of values in the values buffer.
     /// When padding_threshold is None, this equals `num_values` (full 
padding).
     /// When padding_threshold is set, this is the item_count (selective 
padding).
diff --git a/parquet/src/column/reader/decoder.rs 
b/parquet/src/column/reader/decoder.rs
index 0ea8020a17..be8750dc74 100644
--- a/parquet/src/column/reader/decoder.rs
+++ b/parquet/src/column/reader/decoder.rs
@@ -74,6 +74,12 @@ pub trait ColumnValueDecoder {
     /// Create a new [`ColumnValueDecoder`]
     fn new(col: &ColumnDescPtr) -> Self;
 
+    /// Set whether decoded values are validated as UTF-8.
+    ///
+    /// The Arrow type being built decides this, not the Parquet annotation: a
+    /// supplied schema can read an unannotated `BYTE_ARRAY` column as a 
string.
+    fn set_validate_utf8(&mut self, _validate_utf8: bool) {}
+
     /// Set the current dictionary page
     fn set_dict(
         &mut self,
diff --git a/parquet/src/util/utf8.rs b/parquet/src/util/utf8.rs
index 00bfd47fc5..9e8526b0d0 100644
--- a/parquet/src/util/utf8.rs
+++ b/parquet/src/util/utf8.rs
@@ -42,3 +42,17 @@ pub fn check_valid_utf8(val: &[u8]) -> Result<()> {
         Err(e) => Err(general_err!("encountered non UTF-8 data: {}", e)),
     }
 }
+
+/// Check that `value` does not start in the middle of a UTF-8 character.
+///
+/// [`check_valid_utf8`] over values stored back to back misses a character
+/// split across two of them, so each value's start must be checked as well.
+#[inline(always)]
+pub(crate) fn check_utf8_value_start(value: &[u8]) -> Result<()> {
+    match value.first() {
+        // A continuation byte has the form 0b10xxxxxx, bit majic from 
`str::is_char_boundary`
+        // see 
https://github.com/rust-lang/rust/blob/1.100.0/library/core/src/num/mod.rs#L1232-L1235
+        Some(&b) if (b as i8) < -0x40 => Err(general_err!("encountered non 
UTF-8 data")),
+        _ => Ok(()),
+    }
+}

Reply via email to