Skip to main content

parquet/arrow/arrow_writer/
mod.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18//! Contains writer which writes arrow data into parquet data.
19
20use crate::column::chunker::ContentDefinedChunker;
21
22use bytes::Bytes;
23use std::io::Write;
24use std::slice::Iter;
25use std::sync::{Arc, Mutex};
26use std::vec::IntoIter;
27
28use arrow_array::cast::AsArray;
29use arrow_array::{ArrayRef, Int32Array, RecordBatch, RecordBatchWriter};
30use arrow_array::{PrimitiveArray, types::*};
31use arrow_schema::{
32    ArrowError, DataType as ArrowDataType, Field, IntervalUnit, SchemaRef, TimeUnit,
33};
34
35use super::schema::{add_encoded_arrow_schema_to_metadata, decimal_length_from_precision};
36
37use crate::arrow::ArrowSchemaConverter;
38use crate::arrow::arrow_writer::byte_array::ByteArrayEncoder;
39use crate::basic::PageType;
40use crate::column::page::{CompressedPage, PageWriteSpec, PageWriter};
41use crate::column::page_encryption::PageEncryptor;
42use crate::column::writer::encoder::ColumnValueEncoder;
43use crate::column::writer::{
44    ColumnCloseResult, ColumnWriter, GenericColumnWriter, get_column_writer,
45};
46use crate::data_type::{ByteArray, FixedLenByteArray};
47use std::collections::HashSet;
48type DistinctValuesSet = HashSet<u64>;
49#[cfg(feature = "encryption")]
50use crate::encryption::encrypt::FileEncryptor;
51use crate::errors::{ParquetError, Result};
52use crate::file::metadata::{KeyValue, ParquetMetaData, RowGroupMetaData};
53use crate::file::properties::{WriterProperties, WriterPropertiesPtr};
54use crate::file::writer::{SerializedFileWriter, SerializedRowGroupWriter};
55use crate::parquet_thrift::{ThriftCompactOutputProtocol, WriteThrift};
56use crate::schema::types::{ColumnDescPtr, SchemaDescPtr, SchemaDescriptor};
57use levels::{ArrayLevels, calculate_array_levels};
58
59mod byte_array;
60mod levels;
61
62#[doc(inline)]
63pub use crate::column::page_store::{
64    InMemoryPageStore, InMemoryPageStoreFactory, PageKey, PageStore, PageStoreArgs,
65    PageStoreFactory,
66};
67
68/// Encodes [`RecordBatch`] to parquet
69///
70/// Writes Arrow `RecordBatch`es to a Parquet writer. Multiple [`RecordBatch`] will be encoded
71/// to the same row group, up to `max_row_group_size` rows. Any remaining rows will be
72/// flushed on close, leading the final row group in the output file to potentially
73/// contain fewer than `max_row_group_size` rows
74///
75/// # Example: Writing `RecordBatch`es
76/// ```
77/// # use std::sync::Arc;
78/// # use bytes::Bytes;
79/// # use arrow_array::{ArrayRef, Int64Array};
80/// # use arrow_array::RecordBatch;
81/// # use parquet::arrow::arrow_writer::ArrowWriter;
82/// # use parquet::arrow::arrow_reader::ParquetRecordBatchReader;
83/// let col = Arc::new(Int64Array::from_iter_values([1, 2, 3])) as ArrayRef;
84/// let to_write = RecordBatch::try_from_iter([("col", col)]).unwrap();
85///
86/// let mut buffer = Vec::new();
87/// let mut writer = ArrowWriter::try_new(&mut buffer, to_write.schema(), None).unwrap();
88/// writer.write(&to_write).unwrap();
89/// writer.close().unwrap();
90///
91/// let mut reader = ParquetRecordBatchReader::try_new(Bytes::from(buffer), 1024).unwrap();
92/// let read = reader.next().unwrap().unwrap();
93///
94/// assert_eq!(to_write, read);
95/// ```
96///
97/// # Memory Usage and Limiting
98///
99/// The nature of Parquet requires buffering of an entire row group before it can
100/// be flushed to the underlying writer. Data is mostly buffered in its encoded
101/// form, reducing memory usage. However, some data such as dictionary keys,
102/// large strings or very nested data may still result in non-trivial memory
103/// usage.
104///
105/// See Also:
106/// * [`ArrowWriter::memory_size`]: the current memory usage of the writer.
107/// * [`ArrowWriter::in_progress_size`]: Estimated size of the buffered row group,
108///
109/// Call [`Self::flush`] to trigger an early flush of a row group based on a
110/// memory threshold and/or global memory pressure. However,  smaller row groups
111/// result in higher metadata overheads, and thus may worsen compression ratios
112/// and query performance.
113///
114/// ```no_run
115/// # use std::io::Write;
116/// # use arrow_array::RecordBatch;
117/// # use parquet::arrow::ArrowWriter;
118/// # let mut writer: ArrowWriter<Vec<u8>> = todo!();
119/// # let batch: RecordBatch = todo!();
120/// writer.write(&batch).unwrap();
121/// // Trigger an early flush if anticipated size exceeds 1_000_000
122/// if writer.in_progress_size() > 1_000_000 {
123///     writer.flush().unwrap();
124/// }
125/// ```
126///
127/// ## Type Support
128///
129/// The writer supports writing all Arrow [`DataType`]s that have a direct mapping to
130/// Parquet types including  [`StructArray`] and [`ListArray`].
131///
132/// The following are not supported:
133///
134/// * [`IntervalMonthDayNanoArray`]: Parquet does not [support nanosecond intervals].
135///
136/// [`DataType`]: https://docs.rs/arrow/latest/arrow/datatypes/enum.DataType.html
137/// [`StructArray`]: https://docs.rs/arrow/latest/arrow/array/struct.StructArray.html
138/// [`ListArray`]: https://docs.rs/arrow/latest/arrow/array/type.ListArray.html
139/// [`IntervalMonthDayNanoArray`]: https://docs.rs/arrow/latest/arrow/array/type.IntervalMonthDayNanoArray.html
140/// [support nanosecond intervals]: https://github.com/apache/parquet-format/blob/master/LogicalTypes.md#interval
141///
142/// ## Type Compatibility
143/// The writer can write Arrow [`RecordBatch`]s that are logically equivalent. This means that for
144/// a  given column, the writer can accept multiple Arrow [`DataType`]s that contain the same
145/// value type.
146///
147/// For example, the following [`DataType`]s are all logically equivalent and can be written
148/// to the same column:
149/// * String, LargeString, StringView
150/// * Binary, LargeBinary, BinaryView
151///
152/// The writer can will also accept both native and dictionary encoded arrays if the dictionaries
153/// contain compatible values.
154/// ```
155/// # use std::sync::Arc;
156/// # use arrow_array::{DictionaryArray, LargeStringArray, RecordBatch, StringArray, UInt8Array};
157/// # use arrow_schema::{DataType, Field, Schema};
158/// # use parquet::arrow::arrow_writer::ArrowWriter;
159/// let record_batch1 = RecordBatch::try_new(
160///    Arc::new(Schema::new(vec![Field::new("col", DataType::LargeUtf8, false)])),
161///    vec![Arc::new(LargeStringArray::from_iter_values(vec!["a", "b"]))]
162///  )
163/// .unwrap();
164///
165/// let mut buffer = Vec::new();
166/// let mut writer = ArrowWriter::try_new(&mut buffer, record_batch1.schema(), None).unwrap();
167/// writer.write(&record_batch1).unwrap();
168///
169/// let record_batch2 = RecordBatch::try_new(
170///     Arc::new(Schema::new(vec![Field::new(
171///         "col",
172///         DataType::Dictionary(Box::new(DataType::UInt8), Box::new(DataType::Utf8)),
173///          false,
174///     )])),
175///     vec![Arc::new(DictionaryArray::new(
176///          UInt8Array::from_iter_values(vec![0, 1]),
177///          Arc::new(StringArray::from_iter_values(vec!["b", "c"])),
178///      ))],
179///  )
180///  .unwrap();
181///  writer.write(&record_batch2).unwrap();
182///  writer.close();
183/// ```
184pub struct ArrowWriter<W: Write> {
185    /// Underlying Parquet writer
186    writer: SerializedFileWriter<W>,
187
188    /// The in-progress row group if any
189    in_progress: Option<ArrowRowGroupWriter>,
190
191    /// A copy of the Arrow schema.
192    ///
193    /// The schema is used to verify that each record batch written has the correct schema
194    arrow_schema: SchemaRef,
195
196    /// Creates new [`ArrowRowGroupWriter`] instances as required
197    row_group_writer_factory: ArrowRowGroupWriterFactory,
198
199    /// The maximum number of rows to write to each row group, or None for unlimited
200    max_row_group_row_count: Option<usize>,
201
202    /// The maximum size in bytes for a row group, or None for unlimited
203    max_row_group_bytes: Option<usize>,
204
205    /// CDC chunkers persisted across row groups (one per leaf column).
206    cdc_chunkers: Option<Vec<ContentDefinedChunker>>,
207}
208
209impl<W: Write + Send> std::fmt::Debug for ArrowWriter<W> {
210    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
211        let buffered_memory = self.in_progress_size();
212        f.debug_struct("ArrowWriter")
213            .field("writer", &self.writer)
214            .field("in_progress_size", &format_args!("{buffered_memory} bytes"))
215            .field("in_progress_rows", &self.in_progress_rows())
216            .field("arrow_schema", &self.arrow_schema)
217            .field("max_row_group_row_count", &self.max_row_group_row_count)
218            .field("max_row_group_bytes", &self.max_row_group_bytes)
219            .finish()
220    }
221}
222
223impl<W: Write + Send> ArrowWriter<W> {
224    /// Try to create a new Arrow writer
225    ///
226    /// The writer will fail if:
227    ///  * a `SerializedFileWriter` cannot be created from the ParquetWriter
228    ///  * the Arrow schema contains unsupported datatypes such as Unions
229    pub fn try_new(
230        writer: W,
231        arrow_schema: SchemaRef,
232        props: Option<WriterProperties>,
233    ) -> Result<Self> {
234        let options = ArrowWriterOptions::new().with_properties(props.unwrap_or_default());
235        Self::try_new_with_options(writer, arrow_schema, options)
236    }
237
238    /// Try to create a new Arrow writer with [`ArrowWriterOptions`].
239    ///
240    /// The writer will fail if:
241    ///  * a `SerializedFileWriter` cannot be created from the ParquetWriter
242    ///  * the Arrow schema contains unsupported datatypes such as Unions
243    pub fn try_new_with_options(
244        writer: W,
245        arrow_schema: SchemaRef,
246        options: ArrowWriterOptions,
247    ) -> Result<Self> {
248        let mut props = options.properties;
249
250        let schema = if let Some(parquet_schema) = options.schema_descr {
251            parquet_schema.clone()
252        } else {
253            let mut converter = ArrowSchemaConverter::new().with_coerce_types(props.coerce_types());
254            if let Some(schema_root) = &options.schema_root {
255                converter = converter.schema_root(schema_root);
256            }
257
258            converter.convert(&arrow_schema)?
259        };
260
261        if !options.skip_arrow_metadata {
262            // add serialized arrow schema
263            add_encoded_arrow_schema_to_metadata(&arrow_schema, &mut props);
264        }
265
266        let max_row_group_row_count = props.max_row_group_row_count();
267        let max_row_group_bytes = props.max_row_group_bytes();
268
269        let props_ptr = Arc::new(props);
270        let file_writer =
271            SerializedFileWriter::new(writer, schema.root_schema_ptr(), Arc::clone(&props_ptr))?;
272
273        let mut row_group_writer_factory =
274            ArrowRowGroupWriterFactory::new(&file_writer, arrow_schema.clone());
275        if let Some(page_store_factory) = options.page_store_factory {
276            row_group_writer_factory =
277                row_group_writer_factory.with_page_store_factory(page_store_factory);
278        }
279
280        let cdc_chunkers = props_ptr
281            .content_defined_chunking()
282            .map(|opts| {
283                file_writer
284                    .schema_descr()
285                    .columns()
286                    .iter()
287                    .map(|desc| ContentDefinedChunker::new(desc, opts))
288                    .collect::<Result<Vec<_>>>()
289            })
290            .transpose()?;
291
292        Ok(Self {
293            writer: file_writer,
294            in_progress: None,
295            arrow_schema,
296            row_group_writer_factory,
297            max_row_group_row_count,
298            max_row_group_bytes,
299            cdc_chunkers,
300        })
301    }
302
303    /// Returns metadata for any flushed row groups
304    pub fn flushed_row_groups(&self) -> &[RowGroupMetaData] {
305        self.writer.flushed_row_groups()
306    }
307
308    /// Estimated memory usage, in bytes, of this `ArrowWriter`
309    ///
310    /// This estimate is formed bu summing the values of
311    /// [`ArrowColumnWriter::memory_size`] all in progress columns.
312    pub fn memory_size(&self) -> usize {
313        match &self.in_progress {
314            Some(in_progress) => in_progress.writers.iter().map(|x| x.memory_size()).sum(),
315            None => 0,
316        }
317    }
318
319    /// Anticipated encoded size of the in progress row group.
320    ///
321    /// This estimate the row group size after being completely encoded is,
322    /// formed by summing the values of
323    /// [`ArrowColumnWriter::get_estimated_total_bytes`] for all in progress
324    /// columns.
325    pub fn in_progress_size(&self) -> usize {
326        match &self.in_progress {
327            Some(in_progress) => in_progress
328                .writers
329                .iter()
330                .map(|x| x.get_estimated_total_bytes())
331                .sum(),
332            None => 0,
333        }
334    }
335
336    /// Returns the number of rows buffered in the in progress row group
337    pub fn in_progress_rows(&self) -> usize {
338        self.in_progress
339            .as_ref()
340            .map(|x| x.buffered_rows)
341            .unwrap_or_default()
342    }
343
344    /// Returns the number of bytes written by this instance
345    pub fn bytes_written(&self) -> usize {
346        self.writer.bytes_written()
347    }
348
349    /// Encodes the provided [`RecordBatch`]
350    ///
351    /// If this would cause the current row group to exceed [`WriterProperties::max_row_group_row_count`]
352    /// rows or [`WriterProperties::max_row_group_bytes`] bytes, the contents of `batch` will be
353    /// written to one or more row groups such that limits are respected.
354    ///
355    /// If both limits are `None`, all data is written to a single row group.
356    /// If one limit is set, that limit is respected.
357    /// If both limits are set, the lower bound (whichever triggers first) is respected.
358    ///
359    /// This will fail if the `batch`'s schema does not match the writer's schema,
360    /// or if a logical null is reachable at a position the writer schema declares
361    /// non-nullable.
362    pub fn write(&mut self, batch: &RecordBatch) -> Result<()> {
363        if batch.num_rows() == 0 {
364            return Ok(());
365        }
366
367        // Rows not yet handed to a row group writer. Splitting iterates here instead of
368        // recursing, so a small row group limit over a large batch cannot exhaust the stack.
369        let mut remaining = batch.clone();
370
371        loop {
372            let in_progress = match &mut self.in_progress {
373                Some(in_progress) => in_progress,
374                x => x.insert(
375                    self.row_group_writer_factory
376                        .create_row_group_writer(self.writer.flushed_row_groups().len())?,
377                ),
378            };
379            let buffered_rows = in_progress.buffered_rows;
380
381            // Leading rows of `remaining` that still fit in the current row group, when the
382            // rest has to go to a later one.
383            let mut split_at = match self.max_row_group_row_count {
384                Some(max_rows) if buffered_rows + remaining.num_rows() > max_rows => {
385                    Some(max_rows - buffered_rows)
386                }
387                _ => None,
388            };
389
390            // Check byte limit: if we have buffered data, use measured average row size
391            // to split batch proactively before exceeding byte limit. Both limits apply to
392            // the same rows, so measure against whatever the row limit already trimmed
393            // `remaining` down to; otherwise the row limit would always win.
394            let candidate_rows = split_at.unwrap_or_else(|| remaining.num_rows());
395
396            if self.max_row_group_bytes.is_some() && buffered_rows == 0 {
397                // There is no row size to extrapolate from yet: write a single row first,
398                // so that the byte limit also applies to the rest of the batch instead of
399                // letting a batch larger than the limit fill the row group on its own.
400                if candidate_rows > 1 {
401                    split_at = Some(1);
402                }
403            } else if let Some(max_bytes) = self.max_row_group_bytes {
404                let current_bytes = in_progress.get_estimated_total_bytes();
405
406                if current_bytes >= max_bytes {
407                    self.flush()?;
408                    continue;
409                }
410
411                let avg_row_bytes = current_bytes / buffered_rows;
412                if let Some(rows_that_fit) = (max_bytes - current_bytes).checked_div(avg_row_bytes)
413                {
414                    // At this point, `current_bytes < max_bytes` (checked above)
415                    if candidate_rows > rows_that_fit {
416                        if rows_that_fit > 0 {
417                            split_at = Some(rows_that_fit);
418                        } else {
419                            self.flush()?;
420                            continue;
421                        }
422                    }
423                }
424            }
425
426            let rest = split_at.map(|to_write| {
427                let rest = remaining.slice(to_write, remaining.num_rows() - to_write);
428                remaining = remaining.slice(0, to_write);
429                rest
430            });
431
432            let in_progress = self.in_progress.as_mut().unwrap();
433            match self.cdc_chunkers.as_mut() {
434                Some(chunkers) => in_progress.write_with_chunkers(&remaining, chunkers)?,
435                None => in_progress.write(&remaining)?,
436            }
437
438            let should_flush = self
439                .max_row_group_row_count
440                .is_some_and(|max| in_progress.buffered_rows >= max)
441                || self
442                    .max_row_group_bytes
443                    .is_some_and(|max| in_progress.get_estimated_total_bytes() >= max);
444
445            if should_flush {
446                self.flush()?
447            }
448
449            match rest {
450                Some(rest) => remaining = rest,
451                None => return Ok(()),
452            }
453        }
454    }
455
456    /// Writes the given buf bytes to the internal buffer.
457    ///
458    /// It's safe to use this method to write data to the underlying writer,
459    /// because it will ensure that the buffering and byte‐counting layers are used.
460    pub fn write_all(&mut self, buf: &[u8]) -> std::io::Result<()> {
461        self.writer.write_all(buf)
462    }
463
464    /// Flushes underlying writer
465    pub fn sync(&mut self) -> std::io::Result<()> {
466        self.writer.flush()
467    }
468
469    /// Flushes all buffered rows into a new row group
470    ///
471    /// Note the underlying writer is not flushed with this call.
472    /// If this is a desired behavior, please call [`ArrowWriter::sync`].
473    pub fn flush(&mut self) -> Result<()> {
474        let Some(in_progress) = self.in_progress.take() else {
475            return Ok(());
476        };
477
478        let mut row_group_writer = self.writer.next_row_group()?;
479        for chunk in in_progress.close()? {
480            chunk.append_to_row_group(&mut row_group_writer)?;
481        }
482        row_group_writer.close()?;
483        Ok(())
484    }
485
486    /// Additional [`KeyValue`] metadata to be written in addition to those from [`WriterProperties`]
487    ///
488    /// This method provide a way to append kv_metadata after write RecordBatch
489    pub fn append_key_value_metadata(&mut self, kv_metadata: KeyValue) {
490        self.writer.append_key_value_metadata(kv_metadata)
491    }
492
493    /// Returns a reference to the underlying writer.
494    pub fn inner(&self) -> &W {
495        self.writer.inner()
496    }
497
498    /// Returns a mutable reference to the underlying writer.
499    ///
500    /// **Warning**: if you write directly to this writer, you will skip
501    /// the `TrackedWrite` buffering and byte‐counting layers. That’ll cause
502    /// the file footer’s recorded offsets and sizes to diverge from reality,
503    /// resulting in an unreadable or corrupted Parquet file.
504    ///
505    /// If you want to write safely to the underlying writer, use [`Self::write_all`].
506    pub fn inner_mut(&mut self) -> &mut W {
507        self.writer.inner_mut()
508    }
509
510    /// Flushes any outstanding data and returns the underlying writer.
511    pub fn into_inner(mut self) -> Result<W> {
512        self.flush()?;
513        self.writer.into_inner()
514    }
515
516    /// Close and finalize the underlying Parquet writer
517    ///
518    /// Unlike [`Self::close`] this does not consume self
519    ///
520    /// Attempting to write after calling finish will result in an error
521    pub fn finish(&mut self) -> Result<ParquetMetaData> {
522        self.flush()?;
523        self.writer.finish()
524    }
525
526    /// Close and finalize the underlying Parquet writer
527    pub fn close(mut self) -> Result<ParquetMetaData> {
528        self.finish()
529    }
530
531    /// Converts this writer into a lower-level [`SerializedFileWriter`] and [`ArrowRowGroupWriterFactory`].
532    ///
533    /// Flushes any outstanding data before returning.
534    ///
535    /// This can be useful to provide more control over how files are written, for example
536    /// to write columns in parallel. See the example on [`ArrowColumnWriter`].
537    pub fn into_serialized_writer(
538        mut self,
539    ) -> Result<(SerializedFileWriter<W>, ArrowRowGroupWriterFactory)> {
540        self.flush()?;
541        Ok((self.writer, self.row_group_writer_factory))
542    }
543}
544
545impl<W: Write + Send> RecordBatchWriter for ArrowWriter<W> {
546    fn write(&mut self, batch: &RecordBatch) -> Result<(), ArrowError> {
547        self.write(batch).map_err(|e| e.into())
548    }
549
550    fn close(self) -> std::result::Result<(), ArrowError> {
551        self.close()?;
552        Ok(())
553    }
554}
555
556/// Arrow-specific configuration settings for writing parquet files.
557///
558/// See [`ArrowWriter`] for how to configure the writer.
559#[derive(Debug, Clone, Default)]
560pub struct ArrowWriterOptions {
561    properties: WriterProperties,
562    skip_arrow_metadata: bool,
563    schema_root: Option<String>,
564    schema_descr: Option<SchemaDescriptor>,
565    page_store_factory: Option<Arc<dyn PageStoreFactory>>,
566}
567
568impl ArrowWriterOptions {
569    /// Creates a new [`ArrowWriterOptions`] with the default settings.
570    pub fn new() -> Self {
571        Self::default()
572    }
573
574    /// Sets the [`WriterProperties`] for writing parquet files.
575    pub fn with_properties(self, properties: WriterProperties) -> Self {
576        Self { properties, ..self }
577    }
578
579    /// Sets the [`PageStoreFactory`] used to buffer completed pages while a row
580    /// group is being written.
581    ///
582    /// The default implementation ([`InMemoryPageStore`]) buffers all completed
583    /// pages on the heap until the row group is flushed, so peak write memory
584    /// grows with the row group size. Using this API, pages can be spilled to a
585    /// file or object storage instead, reducing peak write memory substantially
586    /// at the expense of an extra write to and read from secondary storage.
587    ///
588    /// # Example: spilling pages to a temp file
589    ///
590    /// A simple spilling backend uses one temp file per column chunk; `put`
591    /// appends the page and `take` reads it back.
592    ///
593    /// ```
594    /// # use std::fs::File;
595    /// # use std::io::{Read, Seek, SeekFrom, Write};
596    /// # use std::sync::Arc;
597    /// # use bytes::Bytes;
598    /// # use arrow_array::{ArrayRef, Int64Array, RecordBatch};
599    /// # use parquet::arrow::arrow_writer::{
600    /// #     ArrowWriter, ArrowWriterOptions, PageKey, PageStore, PageStoreArgs, PageStoreFactory,
601    /// # };
602    /// # use parquet::arrow::arrow_reader::ParquetRecordBatchReader;
603    /// # use parquet::errors::Result;
604    /// struct TempFilePageStore {
605    ///     file: File,
606    ///     /// Total size of the file
607    ///     end: u64,
608    ///     /// Location of pages: (offset, len)
609    ///     locs: Vec<(u64, usize)>,
610    /// }
611    ///
612    /// impl PageStore for TempFilePageStore {
613    ///     fn put(&mut self, value: Bytes) -> Result<PageKey> {
614    ///         // Append to the end of the file
615    ///         self.file.seek(SeekFrom::Start(self.end))?;
616    ///         self.file.write_all(&value)?;
617    ///         let key = PageKey::new(self.locs.len() as u64);
618    ///         self.locs.push((self.end, value.len()));
619    ///         self.end += value.len() as u64;
620    ///         Ok(key)
621    ///     }
622    ///
623    ///     fn take(&mut self, key: PageKey) -> Result<Bytes> {
624    ///         let (offset, len) = self.locs[key.get() as usize];
625    ///         let mut buf = vec![0u8; len];
626    ///         self.file.seek(SeekFrom::Start(offset))?;
627    ///         self.file.read_exact(&mut buf)?;
628    ///         Ok(Bytes::from(buf))
629    ///     }
630    /// }
631    ///
632    /// /// Factory for creating [`TempFilePageStore`]
633    /// #[derive(Debug)]
634    /// struct TempFilePageStoreFactory;
635    ///
636    /// impl PageStoreFactory for TempFilePageStoreFactory {
637    ///     fn create(&self, args: &PageStoreArgs<'_>) -> Result<Box<dyn PageStore>> {
638    ///         // `args` exposes the column index and descriptor (physical/logical
639    ///         // type, path), so a real backend might choose to spill only large columns.
640    ///         let _ = (args.column_index(), args.column_descriptor());
641    ///         Ok(Box::new(TempFilePageStore {
642    ///             file: tempfile::tempfile()?, // temp file is cleaned on drop
643    ///             end: 0,
644    ///             locs: Vec::new(),
645    ///         }))
646    ///     }
647    /// }
648    /// // write 1000 integers
649    /// let col = Arc::new(Int64Array::from_iter_values(0..1000)) as ArrayRef;
650    /// let to_write = RecordBatch::try_from_iter([("col", col)]).unwrap();
651    ///
652    /// let options =
653    ///     ArrowWriterOptions::new().with_page_store_factory(Arc::new(TempFilePageStoreFactory));
654    /// let mut buffer = Vec::new();
655    /// let mut writer =
656    ///     ArrowWriter::try_new_with_options(&mut buffer, to_write.schema(), options).unwrap();
657    /// writer.write(&to_write).unwrap();
658    /// writer.close().unwrap();
659    ///
660    /// // buffer now holds valid Parquet data, which can be read as normal:
661    /// let mut reader = ParquetRecordBatchReader::try_new(Bytes::from(buffer), 1024).unwrap();
662    /// assert_eq!(to_write, reader.next().unwrap().unwrap());
663    /// ```
664    pub fn with_page_store_factory(self, page_store_factory: Arc<dyn PageStoreFactory>) -> Self {
665        Self {
666            page_store_factory: Some(page_store_factory),
667            ..self
668        }
669    }
670
671    /// Skip encoding the embedded arrow metadata (defaults to `false`)
672    ///
673    /// Parquet files generated by the [`ArrowWriter`] contain embedded arrow schema
674    /// by default.
675    ///
676    /// Set `skip_arrow_metadata` to true, to skip encoding the embedded metadata.
677    pub fn with_skip_arrow_metadata(self, skip_arrow_metadata: bool) -> Self {
678        Self {
679            skip_arrow_metadata,
680            ..self
681        }
682    }
683
684    /// Set the name of the root parquet schema element (defaults to `"arrow_schema"`)
685    pub fn with_schema_root(self, schema_root: String) -> Self {
686        Self {
687            schema_root: Some(schema_root),
688            ..self
689        }
690    }
691
692    /// Explicitly specify the Parquet schema to be used
693    ///
694    /// If omitted (the default), the [`ArrowSchemaConverter`] is used to compute the
695    /// Parquet [`SchemaDescriptor`]. This may be used When the [`SchemaDescriptor`] is
696    /// already known or must be calculated using custom logic.
697    pub fn with_parquet_schema(self, schema_descr: SchemaDescriptor) -> Self {
698        Self {
699            schema_descr: Some(schema_descr),
700            ..self
701        }
702    }
703}
704
705/// A single column chunk produced by [`ArrowColumnWriter`].
706///
707/// Holds the serialized page blobs (each page's header ‖ compressed data, in
708/// write order) in a [`PageStore`], plus the handles needed to read them back,
709/// in order, when the chunk is spliced into the output file.
710struct ArrowColumnChunkData {
711    length: usize,
712    store: Box<dyn PageStore>,
713    keys: Vec<PageKey>,
714    /// Handles to the dictionary page's blobs (header then data) in the store.
715    ///
716    /// A dictionary page is produced at most once and bounded by
717    /// `dict_page_size_limit`, but it must be written *first* in the chunk even
718    /// though the data pages reach the writer before it (see
719    /// [`PageWriter::defers_dictionary_ordering`]). Its header and data are `put`
720    /// into the store like any other page — which keeps the store uniform, and
721    /// lets an oversized dictionary page spill — and their handles are held apart
722    /// so they can be emitted ahead of the data pages at splice.
723    /// Empty for non-dictionary columns.
724    dictionary_keys: Vec<PageKey>,
725    /// Serialized length of the dictionary page (0 if there is none), recorded
726    /// so the data pages can be shifted past it when offsets are rewritten to a
727    /// dictionary-first layout at splice.
728    dictionary_len: usize,
729}
730
731impl ArrowColumnChunkData {
732    fn new(store: Box<dyn PageStore>) -> Self {
733        Self {
734            length: 0,
735            store,
736            keys: Vec::new(),
737            dictionary_keys: Vec::new(),
738            dictionary_len: 0,
739        }
740    }
741
742    /// Append a data-page blob to the store, recording its handle in write
743    /// order.
744    fn push(&mut self, value: Bytes) -> Result<()> {
745        let key = self.store.put(value)?;
746        self.keys.push(key);
747        Ok(())
748    }
749
750    /// Store a dictionary-page blob (header or data) in the page store,
751    /// recording its handle (emitted first at splice) and accumulating its
752    /// serialized length.
753    fn push_dictionary(&mut self, value: Bytes) -> Result<()> {
754        self.dictionary_len += value.len();
755        let key = self.store.put(value)?;
756        self.dictionary_keys.push(key);
757        Ok(())
758    }
759
760    /// Bytes this chunk currently holds on the heap: whatever the store keeps
761    /// resident (zero for a spilling backend).
762    fn memory_size(&self) -> usize {
763        self.store.memory_size()
764    }
765}
766
767/// A streaming iterator over one column chunk's buffered page blobs, in final
768/// file order: the dictionary page (if any) first, then the data pages.
769///
770/// Each blob is taken back out of the [`PageStore`] *as it is
771/// consumed* and released immediately afterwards, so splicing a chunk into the
772/// output file never materializes more than a single page in memory at a time.
773/// This is what keeps the splice phase within the memory bound for a spilling
774/// backend (an in-memory store already holds the bytes, so it is unaffected).
775struct StreamingColumnChunkPages {
776    store: Box<dyn PageStore>,
777    /// Page handles in final file order: the dictionary page first (if any),
778    /// then the data pages.
779    keys: IntoIter<PageKey>,
780}
781
782impl StreamingColumnChunkPages {
783    fn new(data: ArrowColumnChunkData) -> Self {
784        // The dictionary page must be emitted first, ahead of the data pages,
785        // even though it was the last page produced.
786        let keys = if data.dictionary_keys.is_empty() {
787            data.keys
788        } else {
789            let mut keys = Vec::with_capacity(data.dictionary_keys.len() + data.keys.len());
790            keys.extend(data.dictionary_keys);
791            keys.extend(data.keys);
792            keys
793        };
794        Self {
795            store: data.store,
796            keys: keys.into_iter(),
797        }
798    }
799}
800
801impl Iterator for StreamingColumnChunkPages {
802    type Item = Result<Bytes>;
803
804    fn next(&mut self) -> Option<Self::Item> {
805        let key = self.keys.next()?;
806        Some(self.store.take(key))
807    }
808}
809
810/// A shared [`ArrowColumnChunkData`]
811///
812/// This allows it to be owned by [`ArrowPageWriter`] whilst allowing access via
813/// [`ArrowRowGroupWriter`] on flush, without requiring self-referential borrows
814type SharedColumnChunk = Arc<Mutex<ArrowColumnChunkData>>;
815
816struct ArrowPageWriter {
817    buffer: SharedColumnChunk,
818    #[cfg(feature = "encryption")]
819    page_encryptor: Option<PageEncryptor>,
820}
821
822impl ArrowPageWriter {
823    /// Create a page writer that buffers completed pages in `store`.
824    fn new(store: Box<dyn PageStore>) -> Self {
825        Self {
826            buffer: Arc::new(Mutex::new(ArrowColumnChunkData::new(store))),
827            #[cfg(feature = "encryption")]
828            page_encryptor: None,
829        }
830    }
831
832    #[cfg(feature = "encryption")]
833    pub fn with_encryptor(mut self, page_encryptor: Option<PageEncryptor>) -> Self {
834        self.page_encryptor = page_encryptor;
835        self
836    }
837
838    #[cfg(feature = "encryption")]
839    fn page_encryptor_mut(&mut self) -> Option<&mut PageEncryptor> {
840        self.page_encryptor.as_mut()
841    }
842
843    // Mirrors the signature of the encryption-enabled version above, so that the
844    // callers do not need a `cfg` of their own.
845    #[cfg(not(feature = "encryption"))]
846    #[expect(
847        clippy::needless_pass_by_ref_mut,
848        reason = "mirrors the encryption-enabled signature"
849    )]
850    fn page_encryptor_mut(&mut self) -> Option<&mut PageEncryptor> {
851        None
852    }
853}
854
855impl PageWriter for ArrowPageWriter {
856    fn write_page(&mut self, page: CompressedPage) -> Result<PageWriteSpec> {
857        let page = match self.page_encryptor_mut() {
858            Some(page_encryptor) => page_encryptor.encrypt_compressed_page(page)?,
859            None => page,
860        };
861
862        let page_header = page.to_thrift_header()?;
863        let header = {
864            let mut header = Vec::with_capacity(1024);
865
866            match self.page_encryptor_mut() {
867                Some(page_encryptor) => {
868                    page_encryptor.encrypt_page_header(&page_header, &mut header)?;
869                    if page.compressed_page().is_data_page() {
870                        page_encryptor.increment_page();
871                    }
872                }
873                None => {
874                    let mut protocol = ThriftCompactOutputProtocol::new(&mut header);
875                    page_header.write_thrift(&mut protocol)?;
876                }
877            }
878
879            Bytes::from(header)
880        };
881
882        let mut buf = self.buffer.try_lock().unwrap();
883
884        let data = page.compressed_page().buffer().clone();
885        let compressed_size = data.len() + header.len();
886
887        let mut spec = PageWriteSpec::new();
888        spec.page_type = page.page_type();
889        spec.num_values = page.num_values();
890        spec.uncompressed_size = page.uncompressed_size() + header.len();
891        spec.offset = buf.length as u64;
892        spec.compressed_size = compressed_size;
893        spec.bytes_written = compressed_size as u64;
894
895        buf.length += compressed_size;
896        if spec.page_type == PageType::DICTIONARY_PAGE {
897            // Recorded apart from the data pages so it is emitted first at
898            // splice — see `ArrowColumnChunkData::dictionary_keys`.
899            buf.push_dictionary(header)?;
900            buf.push_dictionary(data)?;
901        } else {
902            buf.push(header)?;
903            buf.push(data)?;
904        }
905
906        Ok(spec)
907    }
908
909    fn defers_dictionary_ordering(&self) -> bool {
910        // The Arrow chunk is buffered in full and spliced at row-group flush, so
911        // data pages may be accepted before the dictionary page and reordered
912        // then. This lets `GenericColumnWriter` stream dictionary-column data
913        // pages straight through instead of buffering them in memory.
914        true
915    }
916
917    fn buffered_memory_size(&self) -> usize {
918        // Only what is actually resident: a spilling store reports ~0 here even
919        // though the chunk's bytes have all passed through it.
920        self.buffer.try_lock().unwrap().memory_size()
921    }
922
923    fn close(&mut self) -> Result<()> {
924        Ok(())
925    }
926}
927
928/// A leaf column that can be encoded by [`ArrowColumnWriter`]
929#[derive(Debug)]
930pub struct ArrowLeafColumn(ArrayLevels);
931
932/// Computes the [`ArrowLeafColumn`] for a potentially nested [`ArrayRef`]
933///
934/// This function can be used to encode individual columns in parallel.
935/// See example on [`ArrowColumnWriter`]. A reachable logical null in a
936/// non-nullable `field` returns an error when the leaf is written.
937pub fn compute_leaves(field: &Field, array: &ArrayRef) -> Result<Vec<ArrowLeafColumn>> {
938    let levels = calculate_array_levels(array, field)?;
939    Ok(levels.into_iter().map(ArrowLeafColumn).collect())
940}
941
942/// The data for a single column chunk, see [`ArrowColumnWriter`]
943pub struct ArrowColumnChunk {
944    data: ArrowColumnChunkData,
945    close: ColumnCloseResult,
946}
947
948impl std::fmt::Debug for ArrowColumnChunk {
949    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
950        f.debug_struct("ArrowColumnChunk")
951            .field("length", &self.data.length)
952            .finish_non_exhaustive()
953    }
954}
955
956impl ArrowColumnChunk {
957    /// Returns the [`ColumnCloseResult`] produced when the chunk was closed.
958    ///
959    /// Exposes encoding information, collected statistics, and the optional
960    /// [`ColumnIndexMetaData`](crate::file::page_index::column_index::ColumnIndexMetaData)
961    /// / [`OffsetIndexMetaData`](crate::file::page_index::offset_index::OffsetIndexMetaData)
962    /// gathered for the column chunk.
963    pub fn close(&self) -> &ColumnCloseResult {
964        &self.close
965    }
966
967    /// Returns a mutable reference to the [`ColumnCloseResult`].
968    ///
969    /// This allows callers to mutate the close result before the chunk is
970    /// appended to a row group — for example, clearing `column_index` or
971    /// `bloom_filter` based on a dynamic rule that inspects the encodings and
972    /// collected page statistics.
973    pub fn close_mut(&mut self) -> &mut ColumnCloseResult {
974        &mut self.close
975    }
976
977    /// Splices this column's buffered pages into the row group, streaming them
978    /// back out of the [`PageStore`] one page at a time.
979    pub fn append_to_row_group<W: Write + Send>(
980        self,
981        writer: &mut SerializedRowGroupWriter<'_, W>,
982    ) -> Result<()> {
983        let ArrowColumnChunk { data, close } = self;
984
985        // The dictionary page is produced *after* the data pages on this path (so
986        // they can stream straight through) but must be written *first*, so move
987        // it ahead of the data pages in the recorded offsets before the splice.
988        let close = close.update_dictionary_location(data.dictionary_len)?;
989
990        let pages = StreamingColumnChunkPages::new(data);
991        writer.append_column_from_pages(pages, close)
992    }
993}
994
995/// Encodes [`ArrowLeafColumn`] to [`ArrowColumnChunk`]
996///
997/// `ArrowColumnWriter` instances can be created using an [`ArrowRowGroupWriterFactory`];
998///
999/// Note: This is a low-level interface for applications that require
1000/// fine-grained control of encoding (e.g. encoding using multiple threads),
1001/// see [`ArrowWriter`] for a higher-level interface
1002///
1003/// # Example: Encoding two Arrow Array's in Parallel
1004/// ```
1005/// // The arrow schema
1006/// # use std::sync::Arc;
1007/// # use arrow_array::*;
1008/// # use arrow_schema::*;
1009/// # use parquet::arrow::ArrowSchemaConverter;
1010/// # use parquet::arrow::arrow_writer::{compute_leaves, ArrowColumnChunk, ArrowLeafColumn, ArrowRowGroupWriterFactory};
1011/// # use parquet::file::properties::WriterProperties;
1012/// # use parquet::file::writer::{SerializedFileWriter, SerializedRowGroupWriter};
1013/// #
1014/// let schema = Arc::new(Schema::new(vec![
1015///     Field::new("i32", DataType::Int32, false),
1016///     Field::new("f32", DataType::Float32, false),
1017/// ]));
1018///
1019/// // Compute the parquet schema
1020/// let props = Arc::new(WriterProperties::default());
1021/// let parquet_schema = ArrowSchemaConverter::new()
1022///   .with_coerce_types(props.coerce_types())
1023///   .convert(&schema)
1024///   .unwrap();
1025///
1026/// // Create parquet writer
1027/// let root_schema = parquet_schema.root_schema_ptr();
1028/// // write to memory in the example, but this could be a File
1029/// let mut out = Vec::with_capacity(1024);
1030/// let mut writer = SerializedFileWriter::new(&mut out, root_schema, props.clone())
1031///   .unwrap();
1032///
1033/// // Create a factory for building Arrow column writers
1034/// let row_group_factory = ArrowRowGroupWriterFactory::new(&writer, Arc::clone(&schema));
1035/// // Create column writers for the 0th row group
1036/// let col_writers = row_group_factory.create_column_writers(0).unwrap();
1037///
1038/// // Spawn a worker thread for each column
1039/// //
1040/// // Note: This is for demonstration purposes, a thread-pool e.g. rayon or tokio, would be better.
1041/// // The `map` produces an iterator of type `tuple of (thread handle, send channel)`.
1042/// let mut workers: Vec<_> = col_writers
1043///     .into_iter()
1044///     .map(|mut col_writer| {
1045///         let (send, recv) = std::sync::mpsc::channel::<ArrowLeafColumn>();
1046///         let handle = std::thread::spawn(move || {
1047///             // receive Arrays to encode via the channel
1048///             for col in recv {
1049///                 col_writer.write(&col)?;
1050///             }
1051///             // once the input is complete, close the writer
1052///             // to return the newly created ArrowColumnChunk
1053///             col_writer.close()
1054///         });
1055///         (handle, send)
1056///     })
1057///     .collect();
1058///
1059/// // Start row group
1060/// let mut row_group_writer: SerializedRowGroupWriter<'_, _> = writer
1061///   .next_row_group()
1062///   .unwrap();
1063///
1064/// // Create some example input columns to encode
1065/// let to_write = vec![
1066///     Arc::new(Int32Array::from_iter_values([1, 2, 3])) as _,
1067///     Arc::new(Float32Array::from_iter_values([1., 45., -1.])) as _,
1068/// ];
1069///
1070/// // Send the input columns to the workers
1071/// let mut worker_iter = workers.iter_mut();
1072/// for (arr, field) in to_write.iter().zip(&schema.fields) {
1073///     for leaves in compute_leaves(field, arr).unwrap() {
1074///         worker_iter.next().unwrap().1.send(leaves).unwrap();
1075///     }
1076/// }
1077///
1078/// // Wait for the workers to complete encoding, and append
1079/// // the resulting column chunks to the row group (and the file)
1080/// for (handle, send) in workers {
1081///     drop(send); // Drop send side to signal termination
1082///     // wait for the worker to send the completed chunk
1083///     let chunk: ArrowColumnChunk = handle.join().unwrap().unwrap();
1084///     chunk.append_to_row_group(&mut row_group_writer).unwrap();
1085/// }
1086/// // Close the row group which writes to the underlying file
1087/// row_group_writer.close().unwrap();
1088///
1089/// let metadata = writer.close().unwrap();
1090/// assert_eq!(metadata.file_metadata().num_rows(), 3);
1091/// ```
1092pub struct ArrowColumnWriter {
1093    writer: ArrowColumnWriterImpl,
1094    chunk: SharedColumnChunk,
1095    /// Non-null value hashes accumulated across all writes for this column's row group.
1096    /// `None` when tracking is disabled via [`WriterProperties::write_row_group_number_distinct_values`].
1097    distinct_values_seen: Option<DistinctValuesSet>,
1098}
1099
1100impl std::fmt::Debug for ArrowColumnWriter {
1101    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1102        f.debug_struct("ArrowColumnWriter").finish_non_exhaustive()
1103    }
1104}
1105
1106enum ArrowColumnWriterImpl {
1107    ByteArray(GenericColumnWriter<'static, ByteArrayEncoder>),
1108    Column(ColumnWriter<'static>),
1109}
1110
1111impl ArrowColumnWriter {
1112    /// Write an [`ArrowLeafColumn`]
1113    pub fn write(&mut self, col: &ArrowLeafColumn) -> Result<()> {
1114        col.0.validate()?;
1115        self.write_internal(&col.0)
1116    }
1117
1118    /// Write with content-defined chunking, inserting page flushes at chunk boundaries.
1119    fn write_with_chunker(
1120        &mut self,
1121        col: &ArrowLeafColumn,
1122        chunker: &mut ContentDefinedChunker,
1123    ) -> Result<()> {
1124        let levels = &col.0;
1125        levels.validate()?;
1126        let chunks = chunker.get_arrow_chunks(
1127            levels.def_level_data().as_ref(),
1128            levels.rep_level_data().as_ref(),
1129            levels.array(),
1130        )?;
1131
1132        let num_chunks = chunks.len();
1133        for (i, chunk) in chunks.iter().enumerate() {
1134            let chunk_levels = levels.slice_for_chunk(chunk);
1135            self.write_internal(&chunk_levels)?;
1136
1137            // Add a page break after each chunk except the last
1138            if i + 1 < num_chunks {
1139                match &mut self.writer {
1140                    ArrowColumnWriterImpl::Column(c) => c.add_data_page()?,
1141                    ArrowColumnWriterImpl::ByteArray(c) => c.add_data_page()?,
1142                }
1143            }
1144        }
1145        Ok(())
1146    }
1147
1148    fn write_internal(&mut self, levels: &ArrayLevels) -> Result<()> {
1149        if let Some(seen) = &mut self.distinct_values_seen {
1150            let array = levels.array();
1151            let non_null = levels.non_null_indices();
1152            match array.as_any_dictionary_opt() {
1153                Some(dict) => {
1154                    // Hash referenced values, not key indices: keys can map to different
1155                    // values across batches, and unreferenced values must not count toward NDV.
1156                    let values = dict.values();
1157                    let keys = dict.normalized_keys();
1158                    let referenced_value_indices: Vec<usize> = non_null
1159                        .iter()
1160                        .map(|&pos| keys[pos])
1161                        .filter(|&val_idx| values.is_valid(val_idx))
1162                        .collect();
1163                    update_distinct_values_seen(values.as_ref(), &referenced_value_indices, seen);
1164                }
1165                // For plain arrays, hash the actual values directly.
1166                None => update_distinct_values_seen(array.as_ref(), non_null, seen),
1167            }
1168        }
1169
1170        match &mut self.writer {
1171            ArrowColumnWriterImpl::Column(c) => {
1172                let leaf = levels.array();
1173                match leaf.as_any_dictionary_opt() {
1174                    Some(dictionary) => {
1175                        let materialized =
1176                            arrow_select::take::take(dictionary.values(), dictionary.keys(), None)?;
1177                        write_leaf(c, &materialized, levels)?
1178                    }
1179                    None => write_leaf(c, leaf, levels)?,
1180                };
1181            }
1182            ArrowColumnWriterImpl::ByteArray(c) => {
1183                write_primitive(c, levels.array().as_ref(), levels)?;
1184            }
1185        }
1186        Ok(())
1187    }
1188
1189    /// Close this column returning the written [`ArrowColumnChunk`]
1190    ///
1191    /// # Errors
1192    ///
1193    /// Returns an error if the column could not be finalised, or if another thread
1194    /// panicked while holding the column chunk. The caller cannot cause either.
1195    pub fn close(self) -> Result<ArrowColumnChunk> {
1196        let distinct_count = self
1197            .distinct_values_seen
1198            .as_ref()
1199            .filter(|s| !s.is_empty())
1200            .map(|s| s.len() as u64);
1201        let close = match self.writer {
1202            ArrowColumnWriterImpl::ByteArray(mut c) => {
1203                if let Some(count) = distinct_count {
1204                    c.set_distinct_count_override(count);
1205                }
1206                c.close()?
1207            }
1208            ArrowColumnWriterImpl::Column(mut c) => {
1209                if let Some(count) = distinct_count {
1210                    c.set_distinct_count_override(count);
1211                }
1212                c.close()?
1213            }
1214        };
1215        // Closing the writer above dropped the only other handle on the chunk.
1216        let chunk = Arc::try_unwrap(self.chunk)
1217            .map_err(|_| general_err!("Internal Error: the column chunk is still shared"))?;
1218        let data = chunk
1219            .into_inner()
1220            .map_err(|_| general_err!("The column chunk lock is poisoned"))?;
1221        Ok(ArrowColumnChunk { data, close })
1222    }
1223
1224    /// Returns the estimated total memory usage by the writer.
1225    ///
1226    /// This  [`Self::get_estimated_total_bytes`] this is an estimate
1227    /// of the current memory usage and not it's anticipated encoded size.
1228    ///
1229    /// This includes:
1230    /// 1. Data buffered in encoded form
1231    /// 2. Data buffered in un-encoded form (e.g. `usize` dictionary keys)
1232    ///
1233    /// This value should be greater than or equal to [`Self::get_estimated_total_bytes`]
1234    pub fn memory_size(&self) -> usize {
1235        match &self.writer {
1236            ArrowColumnWriterImpl::ByteArray(c) => c.memory_size(),
1237            ArrowColumnWriterImpl::Column(c) => c.memory_size(),
1238        }
1239    }
1240
1241    /// Returns the estimated total encoded bytes for this column writer.
1242    ///
1243    /// This includes:
1244    /// 1. Data buffered in encoded form
1245    /// 2. An estimate of how large the data buffered in un-encoded form would be once encoded
1246    ///
1247    /// This value should be less than or equal to [`Self::memory_size`]
1248    pub fn get_estimated_total_bytes(&self) -> usize {
1249        match &self.writer {
1250            ArrowColumnWriterImpl::ByteArray(c) => c.get_estimated_total_bytes() as _,
1251            ArrowColumnWriterImpl::Column(c) => c.get_estimated_total_bytes() as _,
1252        }
1253    }
1254}
1255
1256/// Encodes [`RecordBatch`] to a parquet row group
1257///
1258/// Note: this structure is created by [`ArrowRowGroupWriterFactory`] internally used to
1259/// create [`ArrowRowGroupWriter`]s, but it is not exposed publicly.
1260///
1261/// See the example on [`ArrowColumnWriter`] for how to encode columns in parallel
1262#[derive(Debug)]
1263struct ArrowRowGroupWriter {
1264    writers: Vec<ArrowColumnWriter>,
1265    schema: SchemaRef,
1266    buffered_rows: usize,
1267}
1268
1269impl ArrowRowGroupWriter {
1270    fn new(writers: Vec<ArrowColumnWriter>, arrow: &SchemaRef) -> Self {
1271        Self {
1272            writers,
1273            schema: arrow.clone(),
1274            buffered_rows: 0,
1275        }
1276    }
1277
1278    fn write(&mut self, batch: &RecordBatch) -> Result<()> {
1279        self.buffered_rows += batch.num_rows();
1280        let mut writers = self.writers.iter_mut();
1281        for (field, column) in self.schema.fields().iter().zip(batch.columns()) {
1282            for leaf in compute_leaves(field.as_ref(), column)? {
1283                writers.next().unwrap().write(&leaf)?;
1284            }
1285        }
1286        Ok(())
1287    }
1288
1289    fn write_with_chunkers(
1290        &mut self,
1291        batch: &RecordBatch,
1292        chunkers: &mut [ContentDefinedChunker],
1293    ) -> Result<()> {
1294        self.buffered_rows += batch.num_rows();
1295        let mut writers = self.writers.iter_mut();
1296        let mut chunkers = chunkers.iter_mut();
1297        for (field, column) in self.schema.fields().iter().zip(batch.columns()) {
1298            for leaf in compute_leaves(field.as_ref(), column)? {
1299                writers
1300                    .next()
1301                    .unwrap()
1302                    .write_with_chunker(&leaf, chunkers.next().unwrap())?;
1303            }
1304        }
1305        Ok(())
1306    }
1307
1308    /// Returns the estimated total encoded bytes for this row group
1309    fn get_estimated_total_bytes(&self) -> usize {
1310        self.writers
1311            .iter()
1312            .map(|x| x.get_estimated_total_bytes())
1313            .sum()
1314    }
1315
1316    fn close(self) -> Result<Vec<ArrowColumnChunk>> {
1317        self.writers
1318            .into_iter()
1319            .map(|writer| writer.close())
1320            .collect()
1321    }
1322}
1323
1324/// Factory that creates new column writers for each row group in the Parquet file.
1325///
1326/// You can create this structure via an [`ArrowWriter::into_serialized_writer`].
1327/// See the example on [`ArrowColumnWriter`] for how to encode columns in parallel
1328#[derive(Debug)]
1329pub struct ArrowRowGroupWriterFactory {
1330    schema: SchemaDescPtr,
1331    arrow_schema: SchemaRef,
1332    props: WriterPropertiesPtr,
1333    page_store_factory: Arc<dyn PageStoreFactory>,
1334    #[cfg(feature = "encryption")]
1335    file_encryptor: Option<Arc<FileEncryptor>>,
1336}
1337
1338impl ArrowRowGroupWriterFactory {
1339    /// Create a new [`ArrowRowGroupWriterFactory`] for the provided file writer and Arrow schema
1340    pub fn new<W: Write + Send>(
1341        file_writer: &SerializedFileWriter<W>,
1342        arrow_schema: SchemaRef,
1343    ) -> Self {
1344        let schema = Arc::clone(file_writer.schema_descr_ptr());
1345        let props = Arc::clone(file_writer.properties());
1346        Self {
1347            schema,
1348            arrow_schema,
1349            props,
1350            page_store_factory: Arc::new(InMemoryPageStoreFactory),
1351            #[cfg(feature = "encryption")]
1352            file_encryptor: file_writer.file_encryptor(),
1353        }
1354    }
1355
1356    /// Set the [`PageStoreFactory`] used to allocate the buffer for each column
1357    /// chunk, e.g. to spill completed pages to a temp file or object storage
1358    /// instead of the heap. Defaults to [`InMemoryPageStoreFactory`].
1359    pub fn with_page_store_factory(
1360        mut self,
1361        page_store_factory: Arc<dyn PageStoreFactory>,
1362    ) -> Self {
1363        self.page_store_factory = page_store_factory;
1364        self
1365    }
1366
1367    fn create_row_group_writer(&self, row_group_index: usize) -> Result<ArrowRowGroupWriter> {
1368        let writers = self.create_column_writers(row_group_index)?;
1369        Ok(ArrowRowGroupWriter::new(writers, &self.arrow_schema))
1370    }
1371
1372    /// Create column writers for a new row group, with the given row group index
1373    pub fn create_column_writers(&self, row_group_index: usize) -> Result<Vec<ArrowColumnWriter>> {
1374        let mut writers = Vec::with_capacity(self.arrow_schema.fields.len());
1375        let mut leaves = self.schema.columns().iter();
1376        let column_factory = self.column_writer_factory(row_group_index);
1377        for field in &self.arrow_schema.fields {
1378            column_factory.get_arrow_column_writer(
1379                field.data_type(),
1380                &self.props,
1381                &mut leaves,
1382                &mut writers,
1383            )?;
1384        }
1385        Ok(writers)
1386    }
1387
1388    #[cfg(feature = "encryption")]
1389    fn column_writer_factory(&self, row_group_idx: usize) -> ArrowColumnWriterFactory {
1390        ArrowColumnWriterFactory::new()
1391            .with_page_store_factory(self.page_store_factory.clone())
1392            .with_file_encryptor(row_group_idx, self.file_encryptor.clone())
1393    }
1394
1395    #[cfg(not(feature = "encryption"))]
1396    fn column_writer_factory(&self, _row_group_idx: usize) -> ArrowColumnWriterFactory {
1397        ArrowColumnWriterFactory::new().with_page_store_factory(self.page_store_factory.clone())
1398    }
1399}
1400
1401/// Creates [`ArrowColumnWriter`] instances
1402struct ArrowColumnWriterFactory {
1403    /// Allocates the per-column-chunk [`PageStore`] backing each page writer.
1404    page_store_factory: Arc<dyn PageStoreFactory>,
1405    #[cfg(feature = "encryption")]
1406    row_group_index: usize,
1407    #[cfg(feature = "encryption")]
1408    file_encryptor: Option<Arc<FileEncryptor>>,
1409}
1410
1411impl ArrowColumnWriterFactory {
1412    pub fn new() -> Self {
1413        Self {
1414            page_store_factory: Arc::new(InMemoryPageStoreFactory),
1415            #[cfg(feature = "encryption")]
1416            row_group_index: 0,
1417            #[cfg(feature = "encryption")]
1418            file_encryptor: None,
1419        }
1420    }
1421
1422    /// Use `page_store_factory` to allocate the buffer for each column chunk.
1423    pub fn with_page_store_factory(
1424        mut self,
1425        page_store_factory: Arc<dyn PageStoreFactory>,
1426    ) -> Self {
1427        self.page_store_factory = page_store_factory;
1428        self
1429    }
1430
1431    #[cfg(feature = "encryption")]
1432    pub fn with_file_encryptor(
1433        mut self,
1434        row_group_index: usize,
1435        file_encryptor: Option<Arc<FileEncryptor>>,
1436    ) -> Self {
1437        self.row_group_index = row_group_index;
1438        self.file_encryptor = file_encryptor;
1439        self
1440    }
1441
1442    #[cfg(feature = "encryption")]
1443    fn create_page_writer(
1444        &self,
1445        column_descriptor: &ColumnDescPtr,
1446        column_index: usize,
1447    ) -> Result<Box<ArrowPageWriter>> {
1448        let column_path = column_descriptor.path().string();
1449        let page_encryptor = PageEncryptor::create_if_column_encrypted(
1450            self.file_encryptor.as_ref(),
1451            self.row_group_index,
1452            column_index,
1453            &column_path,
1454        )?;
1455        let args = PageStoreArgs::new(column_index, column_descriptor);
1456        let store = self.page_store_factory.create(&args)?;
1457        Ok(Box::new(
1458            ArrowPageWriter::new(store).with_encryptor(page_encryptor),
1459        ))
1460    }
1461
1462    #[cfg(not(feature = "encryption"))]
1463    fn create_page_writer(
1464        &self,
1465        column_descriptor: &ColumnDescPtr,
1466        column_index: usize,
1467    ) -> Result<Box<ArrowPageWriter>> {
1468        let args = PageStoreArgs::new(column_index, column_descriptor);
1469        let store = self.page_store_factory.create(&args)?;
1470        Ok(Box::new(ArrowPageWriter::new(store)))
1471    }
1472
1473    /// Gets an [`ArrowColumnWriter`] for the given `data_type`, appending the
1474    /// output ColumnDesc to `leaves` and the column writers to `out`
1475    fn get_arrow_column_writer(
1476        &self,
1477        data_type: &ArrowDataType,
1478        props: &WriterPropertiesPtr,
1479        leaves: &mut Iter<'_, ColumnDescPtr>,
1480        out: &mut Vec<ArrowColumnWriter>,
1481    ) -> Result<()> {
1482        let write_distinct_values = props.write_row_group_number_distinct_values();
1483
1484        // Instantiate writers for normal columns
1485        let col = |desc: &ColumnDescPtr| -> Result<ArrowColumnWriter> {
1486            let page_writer = self.create_page_writer(desc, out.len())?;
1487            let chunk = page_writer.buffer.clone();
1488            let writer = get_column_writer(desc.clone(), props.clone(), page_writer);
1489            Ok(ArrowColumnWriter {
1490                chunk,
1491                writer: ArrowColumnWriterImpl::Column(writer),
1492                distinct_values_seen: write_distinct_values.then(HashSet::new),
1493            })
1494        };
1495
1496        // Instantiate writers for byte arrays (e.g. Utf8,  Binary, etc)
1497        let bytes = |desc: &ColumnDescPtr| -> Result<ArrowColumnWriter> {
1498            let page_writer = self.create_page_writer(desc, out.len())?;
1499            let chunk = page_writer.buffer.clone();
1500            let writer = GenericColumnWriter::new(desc.clone(), props.clone(), page_writer);
1501            Ok(ArrowColumnWriter {
1502                chunk,
1503                writer: ArrowColumnWriterImpl::ByteArray(writer),
1504                distinct_values_seen: write_distinct_values.then(HashSet::new),
1505            })
1506        };
1507
1508        match data_type {
1509            _ if data_type.is_primitive() => out.push(col(leaves.next().unwrap())?),
1510            ArrowDataType::FixedSizeBinary(_) | ArrowDataType::Boolean | ArrowDataType::Null => {
1511                out.push(col(leaves.next().unwrap())?)
1512            }
1513            ArrowDataType::LargeBinary
1514            | ArrowDataType::Binary
1515            | ArrowDataType::Utf8
1516            | ArrowDataType::LargeUtf8
1517            | ArrowDataType::BinaryView
1518            | ArrowDataType::Utf8View => out.push(bytes(leaves.next().unwrap())?),
1519            ArrowDataType::List(f)
1520            | ArrowDataType::LargeList(f)
1521            | ArrowDataType::FixedSizeList(f, _)
1522            | ArrowDataType::ListView(f)
1523            | ArrowDataType::LargeListView(f) => {
1524                self.get_arrow_column_writer(f.data_type(), props, leaves, out)?
1525            }
1526            ArrowDataType::Struct(fields) => {
1527                for field in fields {
1528                    self.get_arrow_column_writer(field.data_type(), props, leaves, out)?
1529                }
1530            }
1531            ArrowDataType::Map(f, _) => match f.data_type() {
1532                ArrowDataType::Struct(f) => {
1533                    self.get_arrow_column_writer(f[0].data_type(), props, leaves, out)?;
1534                    self.get_arrow_column_writer(f[1].data_type(), props, leaves, out)?
1535                }
1536                _ => unreachable!("invalid map type"),
1537            },
1538            ArrowDataType::Dictionary(_, value_type) => match value_type.as_ref() {
1539                ArrowDataType::Utf8
1540                | ArrowDataType::LargeUtf8
1541                | ArrowDataType::Binary
1542                | ArrowDataType::LargeBinary => out.push(bytes(leaves.next().unwrap())?),
1543                ArrowDataType::Utf8View | ArrowDataType::BinaryView => {
1544                    out.push(bytes(leaves.next().unwrap())?)
1545                }
1546                _ => self.get_arrow_column_writer(value_type, props, leaves, out)?,
1547            },
1548            ArrowDataType::RunEndEncoded(_, value_field) => {
1549                self.get_arrow_column_writer(value_field.data_type(), props, leaves, out)?
1550            }
1551            _ => {
1552                return Err(ParquetError::NYI(format!(
1553                    "Attempting to write an Arrow type {data_type} to parquet that is not yet implemented"
1554                )));
1555            }
1556        }
1557        Ok(())
1558    }
1559}
1560
1561fn write_leaf(
1562    writer: &mut ColumnWriter<'_>,
1563    column: &dyn arrow_array::Array,
1564    levels: &ArrayLevels,
1565) -> Result<usize> {
1566    let indices = levels.non_null_indices();
1567
1568    match writer {
1569        // Note: this should match the contents of arrow_to_parquet_type
1570        ColumnWriter::Int32ColumnWriter(typed) => {
1571            match column.data_type() {
1572                ArrowDataType::Null => {
1573                    let array = Int32Array::new_null(column.len());
1574                    write_primitive(typed, array.values(), levels)
1575                }
1576                ArrowDataType::Int8 => {
1577                    let array: Int32Array = column.as_primitive::<Int8Type>().unary(|x| x as i32);
1578                    write_primitive(typed, array.values(), levels)
1579                }
1580                ArrowDataType::Int16 => {
1581                    let array: Int32Array = column.as_primitive::<Int16Type>().unary(|x| x as i32);
1582                    write_primitive(typed, array.values(), levels)
1583                }
1584                ArrowDataType::Int32 => {
1585                    write_primitive(typed, column.as_primitive::<Int32Type>().values(), levels)
1586                }
1587                ArrowDataType::UInt8 => {
1588                    let array: Int32Array = column.as_primitive::<UInt8Type>().unary(|x| x as i32);
1589                    write_primitive(typed, array.values(), levels)
1590                }
1591                ArrowDataType::UInt16 => {
1592                    let array: Int32Array = column.as_primitive::<UInt16Type>().unary(|x| x as i32);
1593                    write_primitive(typed, array.values(), levels)
1594                }
1595                ArrowDataType::UInt32 => {
1596                    // follow C++ implementation and use overflow/reinterpret cast from  u32 to i32 which will map
1597                    // `(i32::MAX as u32)..u32::MAX` to `i32::MIN..0`
1598                    let array = column.as_primitive::<UInt32Type>();
1599                    write_primitive(typed, array.values().inner().typed_data(), levels)
1600                }
1601                ArrowDataType::Date32 => {
1602                    let array = column.as_primitive::<Date32Type>();
1603                    write_primitive(typed, array.values(), levels)
1604                }
1605                ArrowDataType::Time32(TimeUnit::Second) => {
1606                    let array = column.as_primitive::<Time32SecondType>();
1607                    write_primitive(typed, array.values(), levels)
1608                }
1609                ArrowDataType::Time32(TimeUnit::Millisecond) => {
1610                    let array = column.as_primitive::<Time32MillisecondType>();
1611                    write_primitive(typed, array.values(), levels)
1612                }
1613                ArrowDataType::Date64 => {
1614                    // If the column is a Date64, we truncate it
1615                    let array: Int32Array = column
1616                        .as_primitive::<Date64Type>()
1617                        .unary(|x| (x / 86_400_000) as _);
1618
1619                    write_primitive(typed, array.values(), levels)
1620                }
1621                ArrowDataType::Decimal32(_, _) => {
1622                    let array = column
1623                        .as_primitive::<Decimal32Type>()
1624                        .unary::<_, Int32Type>(|v| v);
1625                    write_primitive(typed, array.values(), levels)
1626                }
1627                ArrowDataType::Decimal64(_, _) => {
1628                    // use the int32 to represent the decimal with low precision
1629                    let array = column
1630                        .as_primitive::<Decimal64Type>()
1631                        .unary::<_, Int32Type>(|v| v as i32);
1632                    write_primitive(typed, array.values(), levels)
1633                }
1634                ArrowDataType::Decimal128(_, _) => {
1635                    // use the int32 to represent the decimal with low precision
1636                    let array = column
1637                        .as_primitive::<Decimal128Type>()
1638                        .unary::<_, Int32Type>(|v| v as i32);
1639                    write_primitive(typed, array.values(), levels)
1640                }
1641                ArrowDataType::Decimal256(_, _) => {
1642                    // use the int32 to represent the decimal with low precision
1643                    let array = column
1644                        .as_primitive::<Decimal256Type>()
1645                        .unary::<_, Int32Type>(|v| v.as_i128() as i32);
1646                    write_primitive(typed, array.values(), levels)
1647                }
1648                d => Err(ParquetError::General(format!("Cannot coerce {d} to I32"))),
1649            }
1650        }
1651        ColumnWriter::BoolColumnWriter(typed) => {
1652            let array = column.as_boolean();
1653            let values = get_bool_array_slice(array, indices.iter().copied());
1654            typed.write_batch_internal(
1655                values.as_slice(),
1656                None,
1657                levels.def_level_data().as_ref(),
1658                levels.rep_level_data().as_ref(),
1659                None,
1660                None,
1661                None,
1662            )
1663        }
1664        ColumnWriter::Int64ColumnWriter(typed) => {
1665            match column.data_type() {
1666                ArrowDataType::Date64 => {
1667                    let array = column
1668                        .as_primitive::<Date64Type>()
1669                        .reinterpret_cast::<Int64Type>();
1670
1671                    write_primitive(typed, array.values(), levels)
1672                }
1673                ArrowDataType::Int64 => {
1674                    let array = column.as_primitive::<Int64Type>();
1675                    write_primitive(typed, array.values(), levels)
1676                }
1677                ArrowDataType::UInt64 => {
1678                    let values = column.as_primitive::<UInt64Type>().values();
1679                    // follow C++ implementation and use overflow/reinterpret cast from  u64 to i64 which will map
1680                    // `(i64::MAX as u64)..u64::MAX` to `i64::MIN..0`
1681                    let array = values.inner().typed_data::<i64>();
1682                    write_primitive(typed, array, levels)
1683                }
1684                ArrowDataType::Time64(TimeUnit::Microsecond) => {
1685                    let array = column.as_primitive::<Time64MicrosecondType>();
1686                    write_primitive(typed, array.values(), levels)
1687                }
1688                ArrowDataType::Time64(TimeUnit::Nanosecond) => {
1689                    let array = column.as_primitive::<Time64NanosecondType>();
1690                    write_primitive(typed, array.values(), levels)
1691                }
1692                ArrowDataType::Timestamp(unit, _) => match unit {
1693                    TimeUnit::Second => {
1694                        let array = column.as_primitive::<TimestampSecondType>();
1695                        write_primitive(typed, array.values(), levels)
1696                    }
1697                    TimeUnit::Millisecond => {
1698                        let array = column.as_primitive::<TimestampMillisecondType>();
1699                        write_primitive(typed, array.values(), levels)
1700                    }
1701                    TimeUnit::Microsecond => {
1702                        let array = column.as_primitive::<TimestampMicrosecondType>();
1703                        write_primitive(typed, array.values(), levels)
1704                    }
1705                    TimeUnit::Nanosecond => {
1706                        let array = column.as_primitive::<TimestampNanosecondType>();
1707                        write_primitive(typed, array.values(), levels)
1708                    }
1709                },
1710                ArrowDataType::Duration(unit) => match unit {
1711                    TimeUnit::Second => {
1712                        let array = column.as_primitive::<DurationSecondType>();
1713                        write_primitive(typed, array.values(), levels)
1714                    }
1715                    TimeUnit::Millisecond => {
1716                        let array = column.as_primitive::<DurationMillisecondType>();
1717                        write_primitive(typed, array.values(), levels)
1718                    }
1719                    TimeUnit::Microsecond => {
1720                        let array = column.as_primitive::<DurationMicrosecondType>();
1721                        write_primitive(typed, array.values(), levels)
1722                    }
1723                    TimeUnit::Nanosecond => {
1724                        let array = column.as_primitive::<DurationNanosecondType>();
1725                        write_primitive(typed, array.values(), levels)
1726                    }
1727                },
1728                ArrowDataType::Decimal64(_, _) => {
1729                    let array = column
1730                        .as_primitive::<Decimal64Type>()
1731                        .reinterpret_cast::<Int64Type>();
1732                    write_primitive(typed, array.values(), levels)
1733                }
1734                ArrowDataType::Decimal128(_, _) => {
1735                    // use the int64 to represent the decimal with low precision
1736                    let array = column
1737                        .as_primitive::<Decimal128Type>()
1738                        .unary::<_, Int64Type>(|v| v as i64);
1739                    write_primitive(typed, array.values(), levels)
1740                }
1741                ArrowDataType::Decimal256(_, _) => {
1742                    // use the int64 to represent the decimal with low precision
1743                    let array = column
1744                        .as_primitive::<Decimal256Type>()
1745                        .unary::<_, Int64Type>(|v| v.as_i128() as i64);
1746                    write_primitive(typed, array.values(), levels)
1747                }
1748                d => Err(ParquetError::General(format!("Cannot coerce {d} to I64"))),
1749            }
1750        }
1751        ColumnWriter::Int96ColumnWriter(_typed) => {
1752            unreachable!("Currently unreachable because data type not supported")
1753        }
1754        ColumnWriter::FloatColumnWriter(typed) => {
1755            let array = column.as_primitive::<Float32Type>();
1756            write_primitive(typed, array.values(), levels)
1757        }
1758        ColumnWriter::DoubleColumnWriter(typed) => {
1759            let array = column.as_primitive::<Float64Type>();
1760            write_primitive(typed, array.values(), levels)
1761        }
1762        ColumnWriter::ByteArrayColumnWriter(_) => {
1763            unreachable!("should use ByteArrayWriter")
1764        }
1765        ColumnWriter::FixedLenByteArrayColumnWriter(typed) => {
1766            let bytes = match column.data_type() {
1767                ArrowDataType::Interval(interval_unit) => match interval_unit {
1768                    IntervalUnit::YearMonth => {
1769                        let array = column.as_primitive::<IntervalYearMonthType>();
1770                        get_interval_ym_array_slice(array, indices.iter().copied())
1771                    }
1772                    IntervalUnit::DayTime => {
1773                        let array = column.as_primitive::<IntervalDayTimeType>();
1774                        get_interval_dt_array_slice(array, indices.iter().copied())
1775                    }
1776                    IntervalUnit::MonthDayNano => {
1777                        return Err(ParquetError::NYI(format!(
1778                            "Attempting to write an Arrow interval type {interval_unit:?} to parquet that is not yet implemented"
1779                        )));
1780                    }
1781                },
1782                ArrowDataType::FixedSizeBinary(_) => {
1783                    let array = column.as_fixed_size_binary();
1784                    get_fsb_array_slice(array, indices.iter().copied())
1785                }
1786                ArrowDataType::Decimal32(_, _) => {
1787                    let array = column.as_primitive::<Decimal32Type>();
1788                    get_decimal_array_slice(array, indices.iter().copied())
1789                }
1790                ArrowDataType::Decimal64(_, _) => {
1791                    let array = column.as_primitive::<Decimal64Type>();
1792                    get_decimal_array_slice(array, indices.iter().copied())
1793                }
1794                ArrowDataType::Decimal128(_, _) => {
1795                    let array = column.as_primitive::<Decimal128Type>();
1796                    get_decimal_array_slice(array, indices.iter().copied())
1797                }
1798                ArrowDataType::Decimal256(_, _) => {
1799                    let array = column.as_primitive::<Decimal256Type>();
1800                    get_decimal_array_slice(array, indices.iter().copied())
1801                }
1802                ArrowDataType::Float16 => {
1803                    let array = column.as_primitive::<Float16Type>();
1804                    get_float_16_array_slice(array, indices.iter().copied())
1805                }
1806                _ => {
1807                    return Err(ParquetError::NYI(
1808                        "Attempting to write an Arrow type that is not yet implemented".to_string(),
1809                    ));
1810                }
1811            };
1812            typed.write_batch_internal(
1813                bytes.as_slice(),
1814                None,
1815                levels.def_level_data().as_ref(),
1816                levels.rep_level_data().as_ref(),
1817                None,
1818                None,
1819                None,
1820            )
1821        }
1822    }
1823}
1824
1825fn write_primitive<E: ColumnValueEncoder>(
1826    writer: &mut GenericColumnWriter<E>,
1827    values: &E::Values,
1828    levels: &ArrayLevels,
1829) -> Result<usize> {
1830    writer.write_batch_internal(
1831        values,
1832        Some(levels.non_null_indices()),
1833        levels.def_level_data().as_ref(),
1834        levels.rep_level_data().as_ref(),
1835        None,
1836        None,
1837        None,
1838    )
1839}
1840
1841fn get_bool_array_slice(
1842    array: &arrow_array::BooleanArray,
1843    indices: impl ExactSizeIterator<Item = usize>,
1844) -> Vec<bool> {
1845    let mut values = Vec::with_capacity(indices.len());
1846    for i in indices {
1847        values.push(array.value(i))
1848    }
1849    values
1850}
1851
1852/// Returns 12-byte values representing 3 values of months, days and milliseconds (4-bytes each).
1853/// An Arrow YearMonth interval only stores months, thus only the first 4 bytes are populated.
1854fn get_interval_ym_array_slice(
1855    array: &arrow_array::IntervalYearMonthArray,
1856    indices: impl ExactSizeIterator<Item = usize>,
1857) -> Vec<FixedLenByteArray> {
1858    chunk_array_slice(12, indices, move |i, chunk| {
1859        let value = array.value(i);
1860        chunk[0..4].copy_from_slice(&value.to_le_bytes());
1861    })
1862}
1863
1864/// Returns 12-byte values representing 3 values of months, days and milliseconds (4-bytes each).
1865/// An Arrow DayTime interval only stores days and millis, thus the first 4 bytes are not populated.
1866fn get_interval_dt_array_slice(
1867    array: &arrow_array::IntervalDayTimeArray,
1868    indices: impl ExactSizeIterator<Item = usize>,
1869) -> Vec<FixedLenByteArray> {
1870    chunk_array_slice(12, indices, move |i, chunk| {
1871        let value = array.value(i);
1872        chunk[4..8].copy_from_slice(&value.days.to_le_bytes());
1873        chunk[8..12].copy_from_slice(&value.milliseconds.to_le_bytes());
1874    })
1875}
1876
1877trait NativeDecimalType: DecimalType {
1878    type NativeBytes: AsRef<[u8]>;
1879
1880    fn to_be_bytes(value: Self::Native) -> Self::NativeBytes;
1881}
1882impl NativeDecimalType for Decimal32Type {
1883    type NativeBytes = [u8; Self::BYTE_LENGTH];
1884
1885    fn to_be_bytes(value: Self::Native) -> Self::NativeBytes {
1886        value.to_be_bytes()
1887    }
1888}
1889impl NativeDecimalType for Decimal64Type {
1890    type NativeBytes = [u8; Self::BYTE_LENGTH];
1891
1892    fn to_be_bytes(value: Self::Native) -> Self::NativeBytes {
1893        value.to_be_bytes()
1894    }
1895}
1896impl NativeDecimalType for Decimal128Type {
1897    type NativeBytes = [u8; Self::BYTE_LENGTH];
1898
1899    fn to_be_bytes(value: Self::Native) -> Self::NativeBytes {
1900        value.to_be_bytes()
1901    }
1902}
1903impl NativeDecimalType for Decimal256Type {
1904    type NativeBytes = [u8; Self::BYTE_LENGTH];
1905
1906    fn to_be_bytes(value: Self::Native) -> Self::NativeBytes {
1907        value.to_be_bytes()
1908    }
1909}
1910
1911fn get_decimal_array_slice<T: NativeDecimalType>(
1912    array: &PrimitiveArray<T>,
1913    indices: impl ExactSizeIterator<Item = usize>,
1914) -> Vec<FixedLenByteArray> {
1915    let chunk_size = decimal_length_from_precision(array.precision());
1916    assert!(chunk_size <= T::BYTE_LENGTH);
1917
1918    if chunk_size == T::BYTE_LENGTH {
1919        // Special-case that allows inlining memcpy.
1920        chunk_array_slice(chunk_size, indices, move |i, chunk| {
1921            let as_be_bytes = T::to_be_bytes(array.value(i));
1922            chunk.copy_from_slice(as_be_bytes.as_ref());
1923        })
1924    } else {
1925        chunk_array_slice(chunk_size, indices, move |i, chunk| {
1926            let as_be_bytes = T::to_be_bytes(array.value(i));
1927            let resized_value = &as_be_bytes.as_ref()[(T::BYTE_LENGTH - chunk.len())..];
1928            chunk.copy_from_slice(resized_value);
1929        })
1930    }
1931}
1932
1933fn get_float_16_array_slice(
1934    array: &arrow_array::Float16Array,
1935    indices: impl ExactSizeIterator<Item = usize>,
1936) -> Vec<FixedLenByteArray> {
1937    chunk_array_slice(2, indices, move |i, chunk| {
1938        let value = array.value(i).to_le_bytes();
1939        chunk.copy_from_slice(&value);
1940    })
1941}
1942
1943fn get_fsb_array_slice(
1944    array: &arrow_array::FixedSizeBinaryArray,
1945    indices: impl ExactSizeIterator<Item = usize>,
1946) -> Vec<FixedLenByteArray> {
1947    chunk_array_slice(array.value_size(), indices, move |i, chunk| {
1948        let value = array.value(i);
1949        chunk.copy_from_slice(value);
1950    })
1951}
1952
1953#[inline]
1954fn chunk_array_slice(
1955    chunk_size: usize,
1956    indices: impl ExactSizeIterator<Item = usize>,
1957    writer: impl Fn(usize, &mut [u8]),
1958) -> Vec<FixedLenByteArray> {
1959    let capacity = indices.len() * chunk_size;
1960    // TODO: This could be done with Vec::spare_capacity_mut,
1961    //       but [MaybeUninit]::write_copy_of_slice is gated behind MSRV 1.93
1962    let mut arena = vec![0; capacity];
1963    for (i, chunk) in indices.zip(arena.chunks_exact_mut(chunk_size)) {
1964        writer(i, chunk);
1965    }
1966    chunk_contiguous_vec(arena, chunk_size)
1967}
1968
1969fn chunk_contiguous_vec(arena: Vec<u8>, chunk_size: usize) -> Vec<FixedLenByteArray> {
1970    let mut values = Vec::with_capacity(arena.len() / chunk_size);
1971    let mut arena = Bytes::from(arena);
1972    while arena.len() >= chunk_size {
1973        let slice = arena.split_to(chunk_size);
1974        values.push(FixedLenByteArray::from(ByteArray::from(slice)));
1975    }
1976    values
1977}
1978
1979/// Hash a byte slice to a u64 for NDV tracking.
1980#[inline]
1981fn hash_bytes(bytes: &[u8]) -> u64 {
1982    twox_hash::XxHash64::oneshot(0, bytes)
1983}
1984
1985/// Returns the fixed byte width for primitive Arrow types, or `None` for variable-length types.
1986fn fixed_byte_width(dt: &ArrowDataType) -> Option<usize> {
1987    use ArrowDataType::*;
1988    match dt {
1989        Int8 | UInt8 => Some(1),
1990        Int16 | UInt16 | Float16 => Some(2),
1991        Int32 | UInt32 | Float32 | Date32 | Time32(_) | Decimal32(_, _) => Some(4),
1992        Int64
1993        | UInt64
1994        | Float64
1995        | Date64
1996        | Time64(_)
1997        | Timestamp(_, _)
1998        | Duration(_)
1999        | Decimal64(_, _) => Some(8),
2000        Interval(IntervalUnit::YearMonth) => Some(4),
2001        Interval(IntervalUnit::DayTime) => Some(8),
2002        Interval(IntervalUnit::MonthDayNano) => Some(16),
2003        Decimal128(_, _) => Some(16),
2004        Decimal256(_, _) => Some(32),
2005        _ => None,
2006    }
2007}
2008
2009/// Hash the non-null values in `array` (at `non_null_indices`) into `seen`.
2010///
2011/// Handles primitive, boolean, fixed-size-binary, and variable-length (Utf8/Binary)
2012/// arrays. Unsupported types are silently skipped, leaving `seen` unchanged for
2013/// those values (NDV is best-effort).
2014fn update_distinct_values_seen(
2015    array: &dyn arrow_array::Array,
2016    non_null_indices: &[usize],
2017    seen: &mut DistinctValuesSet,
2018) {
2019    let data = array.to_data();
2020    let offset = data.offset();
2021
2022    match array.data_type() {
2023        ArrowDataType::Boolean => {
2024            let arr = array
2025                .as_any()
2026                .downcast_ref::<arrow_array::BooleanArray>()
2027                .unwrap();
2028            for &row in non_null_indices {
2029                seen.insert(arr.value(row) as u64);
2030            }
2031        }
2032        ArrowDataType::Utf8 | ArrowDataType::Binary => {
2033            let offsets = data.buffers()[0].typed_data::<i32>();
2034            let values = data.buffers()[1].as_slice();
2035            for &row in non_null_indices {
2036                let start = offsets[offset + row] as usize;
2037                let end = offsets[offset + row + 1] as usize;
2038                seen.insert(hash_bytes(&values[start..end]));
2039            }
2040        }
2041        ArrowDataType::LargeUtf8 | ArrowDataType::LargeBinary => {
2042            let offsets = data.buffers()[0].typed_data::<i64>();
2043            let values = data.buffers()[1].as_slice();
2044            for &row in non_null_indices {
2045                let start = offsets[offset + row] as usize;
2046                let end = offsets[offset + row + 1] as usize;
2047                seen.insert(hash_bytes(&values[start..end]));
2048            }
2049        }
2050        ArrowDataType::FixedSizeBinary(byte_width) => {
2051            let byte_width = *byte_width as usize;
2052            let buffer = data.buffers()[0].as_slice();
2053            for &row in non_null_indices {
2054                let start = (offset + row) * byte_width;
2055                seen.insert(hash_bytes(&buffer[start..start + byte_width]));
2056            }
2057        }
2058        ArrowDataType::Utf8View => {
2059            let string_view_array = array.as_string_view();
2060            for &row in non_null_indices {
2061                seen.insert(hash_bytes(string_view_array.value(row).as_bytes()));
2062            }
2063        }
2064        ArrowDataType::BinaryView => {
2065            let binary_view_array = array.as_binary_view();
2066            for &row in non_null_indices {
2067                seen.insert(hash_bytes(binary_view_array.value(row)));
2068            }
2069        }
2070        data_type => {
2071            if let Some(width) = fixed_byte_width(data_type) {
2072                let buffer = data.buffers()[0].as_slice();
2073                for &row in non_null_indices {
2074                    let pos = (offset + row) * width;
2075                    seen.insert(hash_bytes(&buffer[pos..pos + width]));
2076                }
2077            }
2078            // nested types (List, LargeList, etc.) are Parquet groups, not leaf columns: skip
2079        }
2080    }
2081}
2082
2083// Allow the helpers to use the same imports in unit and integration tests.
2084#[cfg(test)]
2085use crate as parquet_crate;
2086
2087#[cfg(test)]
2088#[path = "../../../tests/arrow_writer/roundtrip_helpers.rs"]
2089mod roundtrip_helpers;
2090
2091#[cfg(test)]
2092mod tests {
2093    use super::roundtrip_helpers::{
2094        RoundTripTest, SMALL_SIZE, required_and_optional, roundtrip_opts,
2095        roundtrip_opts_with_array_validation,
2096    };
2097    use super::*;
2098    use std::cmp::Ordering;
2099    use std::collections::HashMap;
2100
2101    use std::fs::File;
2102
2103    use crate::arrow::ARROW_SCHEMA_META_KEY;
2104    use crate::arrow::arrow_reader::{ParquetRecordBatchReader, ParquetRecordBatchReaderBuilder};
2105    use crate::column::page::{Page, PageReader};
2106    use crate::file::metadata::thrift::PageHeader;
2107    use crate::file::page_index::column_index::ColumnIndexMetaData;
2108    use crate::file::reader::SerializedPageReader;
2109    use crate::parquet_thrift::{ReadThrift, ThriftSliceInputProtocol};
2110    use crate::schema::types::ColumnPath;
2111    use arrow::datatypes::{DataType, Schema};
2112    use arrow::error::Result as ArrowResult;
2113    use arrow::util::data_gen::create_random_array;
2114    use arrow::util::pretty::pretty_format_batches;
2115    use arrow::{array::*, buffer::Buffer};
2116    use arrow_buffer::{IntervalMonthDayNano, NullBuffer, OffsetBuffer};
2117    use arrow_schema::Fields;
2118    use arrow_select::concat::concat;
2119
2120    use crate::basic::{Encoding, EncodingMask};
2121    use crate::data_type::AsBytes;
2122    use crate::file::metadata::{ColumnChunkMetaData, ParquetMetaData, ParquetMetaDataReader};
2123    use crate::file::properties::{
2124        BloomFilterPosition, EnabledStatistics, ReaderProperties, WriterVersion,
2125    };
2126    use crate::file::serialized_reader::ReadOptionsBuilder;
2127    use crate::file::{
2128        reader::{FileReader, SerializedFileReader},
2129        statistics::Statistics,
2130    };
2131
2132    /// A [`PageStore`] that allocates *sparse, non-contiguous* handles and keeps
2133    /// blobs in a `HashMap` — nothing like the default `Vec<Bytes>`. Used to
2134    /// prove the writer relies only on the opaque-handle contract and never on
2135    /// handles being dense `Vec` indices. Records how many blobs were stored.
2136    #[derive(Debug, Default)]
2137    struct RecordingPageStore {
2138        next: u64,
2139        blobs: HashMap<u64, Bytes>,
2140        puts: Arc<std::sync::atomic::AtomicUsize>,
2141    }
2142
2143    impl PageStore for RecordingPageStore {
2144        fn put(&mut self, value: Bytes) -> Result<PageKey> {
2145            // Deliberately non-sequential, never-zero handles.
2146            let id = 100 + self.next * 7;
2147            self.next += 1;
2148            self.puts.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2149            self.blobs.insert(id, value);
2150            Ok(PageKey::new(id))
2151        }
2152
2153        fn take(&mut self, key: PageKey) -> Result<Bytes> {
2154            self.blobs
2155                .remove(&key.get())
2156                .ok_or_else(|| ParquetError::General(format!("missing key {}", key.get())))
2157        }
2158    }
2159
2160    #[derive(Debug)]
2161    struct RecordingPageStoreFactory {
2162        puts: Arc<std::sync::atomic::AtomicUsize>,
2163    }
2164
2165    impl PageStoreFactory for RecordingPageStoreFactory {
2166        fn create(&self, _args: &PageStoreArgs<'_>) -> Result<Box<dyn PageStore>> {
2167            Ok(Box::new(RecordingPageStore {
2168                puts: self.puts.clone(),
2169                ..Default::default()
2170            }))
2171        }
2172    }
2173
2174    /// A custom [`PageStore`] must produce byte-identical files to the in-memory
2175    /// default, across dictionary and non-dictionary columns and multiple row
2176    /// groups (so multiple store instances are exercised).
2177    #[test]
2178    fn custom_page_store_is_byte_identical_to_default() {
2179        let schema = Arc::new(Schema::new(vec![
2180            Field::new("i", DataType::Int32, true),
2181            // A low-cardinality string column to exercise the dictionary path.
2182            Field::new("s", DataType::Utf8, true),
2183        ]));
2184        let i = Int32Array::from(vec![Some(1), None, Some(3), Some(4), Some(5), Some(6)]);
2185        let s = StringArray::from(vec![
2186            Some("a"),
2187            Some("bb"),
2188            Some("a"),
2189            None,
2190            Some("bb"),
2191            Some("ccc"),
2192        ]);
2193        let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(i), Arc::new(s)]).unwrap();
2194
2195        // Small row groups so multiple column chunks (hence multiple store
2196        // instances) are produced.
2197        let props = WriterProperties::builder()
2198            .set_max_row_group_row_count(Some(3))
2199            .build();
2200
2201        let write = |factory: Option<Arc<dyn PageStoreFactory>>| {
2202            let mut buffer = Vec::new();
2203            let mut opts = ArrowWriterOptions::new().with_properties(props.clone());
2204            if let Some(factory) = factory {
2205                opts = opts.with_page_store_factory(factory);
2206            }
2207            let mut writer =
2208                ArrowWriter::try_new_with_options(&mut buffer, schema.clone(), opts).unwrap();
2209            writer.write(&batch).unwrap();
2210            writer.close().unwrap();
2211            buffer
2212        };
2213
2214        let default_bytes = write(None);
2215
2216        let puts = Arc::new(std::sync::atomic::AtomicUsize::new(0));
2217        let custom_bytes = write(Some(Arc::new(RecordingPageStoreFactory {
2218            puts: puts.clone(),
2219        })));
2220
2221        assert!(
2222            puts.load(std::sync::atomic::Ordering::Relaxed) > 0,
2223            "custom PageStore was never written to"
2224        );
2225        assert_eq!(
2226            default_bytes, custom_bytes,
2227            "a custom PageStore must produce byte-identical output to the default"
2228        );
2229    }
2230
2231    /// A dictionary-encoded column written through the deferred-ordering Arrow
2232    /// path must round-trip correctly even with the offset index disabled, when
2233    /// only the chunk-level dictionary/data page offsets are rewritten (there is
2234    /// no offset index to rebuild). Spans multiple data pages so the
2235    /// dictionary-first reordering is exercised.
2236    #[test]
2237    #[cfg_attr(miri, ignore)] // Takes too long
2238    fn dictionary_column_round_trips_with_offset_index_disabled() {
2239        let schema = Arc::new(Schema::new(vec![Field::new("k", DataType::Int32, true)]));
2240
2241        // Low cardinality so the column stays dictionary-encoded; enough rows to
2242        // span several data pages within a single row group.
2243        let values: Vec<Option<i32>> = (0..50_000).map(|i| Some(i % 8)).collect();
2244        let array = Int32Array::from(values.clone());
2245        let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(array)]).unwrap();
2246
2247        let props = WriterProperties::builder()
2248            .set_offset_index_disabled(true)
2249            .set_data_page_row_count_limit(4096)
2250            .build();
2251        let opts = ArrowWriterOptions::new().with_properties(props);
2252
2253        let mut buffer = Vec::new();
2254        let mut writer =
2255            ArrowWriter::try_new_with_options(&mut buffer, schema.clone(), opts).unwrap();
2256        writer.write(&batch).unwrap();
2257        writer.close().unwrap();
2258
2259        let reader = ParquetRecordBatchReader::try_new(Bytes::from(buffer), values.len()).unwrap();
2260        let read: Vec<RecordBatch> = reader.collect::<ArrowResult<_>>().unwrap();
2261        let read_values: Vec<Option<i32>> = read
2262            .iter()
2263            .flat_map(|b| b.column(0).as_primitive::<Int32Type>().iter())
2264            .collect();
2265        assert_eq!(read_values, values);
2266    }
2267
2268    /// The dictionary page is routed through the [`PageStore`] like any other
2269    /// page rather than held resident in memory, so a dictionary column chunk's
2270    /// *entire* serialized size — dictionary page included — passes through the
2271    /// store.
2272    #[test]
2273    fn dictionary_page_is_routed_through_the_store() {
2274        /// A store that sums the bytes handed to `put`.
2275        #[derive(Debug, Default)]
2276        struct SizeRecordingPageStore {
2277            blobs: Vec<Bytes>,
2278            bytes_put: Arc<std::sync::atomic::AtomicUsize>,
2279        }
2280        impl PageStore for SizeRecordingPageStore {
2281            fn put(&mut self, value: Bytes) -> Result<PageKey> {
2282                self.bytes_put
2283                    .fetch_add(value.len(), std::sync::atomic::Ordering::Relaxed);
2284                let key = PageKey::new(self.blobs.len() as u64);
2285                self.blobs.push(value);
2286                Ok(key)
2287            }
2288            fn take(&mut self, key: PageKey) -> Result<Bytes> {
2289                Ok(std::mem::take(&mut self.blobs[key.get() as usize]))
2290            }
2291        }
2292        #[derive(Debug)]
2293        struct Factory {
2294            bytes_put: Arc<std::sync::atomic::AtomicUsize>,
2295        }
2296        impl PageStoreFactory for Factory {
2297            fn create(&self, _args: &PageStoreArgs<'_>) -> Result<Box<dyn PageStore>> {
2298                Ok(Box::new(SizeRecordingPageStore {
2299                    bytes_put: self.bytes_put.clone(),
2300                    ..Default::default()
2301                }))
2302            }
2303        }
2304
2305        let schema = Arc::new(Schema::new(vec![Field::new("s", DataType::Utf8, false)]));
2306        // Low cardinality keeps the column dictionary-encoded with a real,
2307        // non-empty dictionary page.
2308        let values: Vec<&str> = (0..2048)
2309            .map(|i| ["alpha", "beta", "gamma", "delta"][i % 4])
2310            .collect();
2311        let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(StringArray::from(values))])
2312            .unwrap();
2313
2314        let bytes_put = Arc::new(std::sync::atomic::AtomicUsize::new(0));
2315        let opts = ArrowWriterOptions::new().with_page_store_factory(Arc::new(Factory {
2316            bytes_put: bytes_put.clone(),
2317        }));
2318
2319        // A single batch / single column means exactly one row group and one
2320        // store instance, so the bytes it saw map to one column chunk.
2321        let mut buffer = Vec::new();
2322        let mut writer =
2323            ArrowWriter::try_new_with_options(&mut buffer, schema.clone(), opts).unwrap();
2324        writer.write(&batch).unwrap();
2325        writer.close().unwrap();
2326
2327        let reader = SerializedFileReader::new(Bytes::from(buffer)).unwrap();
2328        let column = reader.metadata().row_group(0).column(0);
2329        assert!(
2330            column.dictionary_page_offset().is_some(),
2331            "expected the column to be dictionary-encoded"
2332        );
2333
2334        // The bytes the store was handed must account for the whole chunk,
2335        // dictionary page included. Holding the dictionary page apart from the
2336        // store would make this fall short by the dictionary page's size.
2337        assert_eq!(
2338            bytes_put.load(std::sync::atomic::Ordering::Relaxed) as i64,
2339            column.compressed_size(),
2340            "the dictionary page must pass through the store like any other page"
2341        );
2342    }
2343
2344    /// The `page_encoding_stats` list of a dictionary-encoded column chunk must
2345    /// list the dictionary page *before* the data pages, matching the on-disk
2346    /// page layout (the dictionary page is always written first) and the order
2347    /// produced by the column-at-a-time `SerializedFileWriter`.
2348    #[test]
2349    fn dictionary_page_encoding_stats_lists_dictionary_first() {
2350        use crate::basic::PageType;
2351        use crate::file::metadata::ParquetMetaDataOptions;
2352
2353        // A low-cardinality column so it stays dictionary-encoded, with enough
2354        // rows to emit at least one data page in addition to the dictionary page.
2355        let schema = Arc::new(Schema::new(vec![Field::new("k", DataType::Int32, true)]));
2356        let values: Vec<Option<i32>> = (0..4096).map(|i| Some(i % 4)).collect();
2357        let array = Int32Array::from(values);
2358        let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(array)]).unwrap();
2359
2360        let mut buffer = Vec::new();
2361        let mut writer = ArrowWriter::try_new(&mut buffer, schema.clone(), None).unwrap();
2362        writer.write(&batch).unwrap();
2363        writer.close().unwrap();
2364        let buffer = Bytes::from(buffer);
2365
2366        // Read the *full*, ordered page encoding stats. By default this crate
2367        // collapses them to a bitmask, which would discard the ordering this
2368        // test is about, so opt out of that here.
2369        let options = ParquetMetaDataOptions::new().with_encoding_stats_as_mask(false);
2370        let metadata = ParquetMetaDataReader::new()
2371            .with_metadata_options(Some(options))
2372            .parse_and_finish(&buffer)
2373            .unwrap();
2374
2375        let col = metadata.row_group(0).column(0);
2376        assert!(
2377            col.dictionary_page_offset().is_some(),
2378            "column should be dictionary encoded"
2379        );
2380        let stats = col
2381            .page_encoding_stats()
2382            .expect("full (non-mask) page encoding stats should be present");
2383
2384        // Arrow C++ (`IsColumnChunkFullyDictionaryEncoded`) requires the
2385        // dictionary page entry to be the first one.
2386        assert_eq!(
2387            stats[0].page_type,
2388            PageType::DICTIONARY_PAGE,
2389            "the DICTIONARY_PAGE encoding stat must come first, got {stats:?}"
2390        );
2391        assert!(
2392            stats[1..]
2393                .iter()
2394                .all(|s| s.page_type == PageType::DATA_PAGE)
2395        );
2396    }
2397
2398    fn get_bytes_after_close(schema: SchemaRef, expected_batch: &RecordBatch) -> Vec<u8> {
2399        let mut buffer = vec![];
2400
2401        let mut writer = ArrowWriter::try_new(&mut buffer, schema, None).unwrap();
2402        writer.write(expected_batch).unwrap();
2403        writer.close().unwrap();
2404
2405        buffer
2406    }
2407
2408    fn get_bytes_by_into_inner(schema: SchemaRef, expected_batch: &RecordBatch) -> Vec<u8> {
2409        let mut writer = ArrowWriter::try_new(Vec::new(), schema, None).unwrap();
2410        writer.write(expected_batch).unwrap();
2411        writer.into_inner().unwrap()
2412    }
2413
2414    #[test]
2415    fn roundtrip_bytes() {
2416        // define schema
2417        let schema = Arc::new(Schema::new(vec![
2418            Field::new("a", DataType::Int32, false),
2419            Field::new("b", DataType::Int32, true),
2420        ]));
2421
2422        // create some data
2423        let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
2424        let b = Int32Array::from(vec![Some(1), None, None, Some(4), Some(5)]);
2425
2426        // build a record batch
2427        let expected_batch =
2428            RecordBatch::try_new(schema.clone(), vec![Arc::new(a), Arc::new(b)]).unwrap();
2429
2430        for buffer in [
2431            get_bytes_after_close(schema.clone(), &expected_batch),
2432            get_bytes_by_into_inner(schema, &expected_batch),
2433        ] {
2434            let cursor = Bytes::from(buffer);
2435            let mut record_batch_reader = ParquetRecordBatchReader::try_new(cursor, 1024).unwrap();
2436
2437            let actual_batch = record_batch_reader
2438                .next()
2439                .expect("No batch found")
2440                .expect("Unable to get batch");
2441
2442            assert_eq!(expected_batch.schema(), actual_batch.schema());
2443            assert_eq!(expected_batch.num_columns(), actual_batch.num_columns());
2444            assert_eq!(expected_batch.num_rows(), actual_batch.num_rows());
2445            for i in 0..expected_batch.num_columns() {
2446                let expected_data = expected_batch.column(i).to_data();
2447                let actual_data = actual_batch.column(i).to_data();
2448
2449                assert_eq!(expected_data, actual_data);
2450            }
2451        }
2452    }
2453
2454    fn read_column(file: Vec<u8>) -> ArrayRef {
2455        let reader = ParquetRecordBatchReader::try_new(Bytes::from(file), 4096).unwrap();
2456        let batches: Vec<RecordBatch> = reader.map(|b| b.unwrap()).collect();
2457        let arrays: Vec<&dyn Array> = batches.iter().map(|b| b.column(0).as_ref()).collect();
2458        concat(&arrays).unwrap()
2459    }
2460
2461    fn roundtrip_compatible_column(field: Field, col: ArrayRef) -> ArrayRef {
2462        let writer_schema = Arc::new(Schema::new(vec![field]));
2463        let batch_schema = Arc::new(Schema::new(vec![Field::new(
2464            "c",
2465            col.data_type().clone(),
2466            col.logical_null_count() != 0,
2467        )]));
2468        let batch = RecordBatch::try_new(batch_schema, vec![col]).unwrap();
2469        // Isolate level/value compatibility from Arrow metadata reconstruction,
2470        // which is covered separately by the default-reader regression below.
2471        let options = ArrowWriterOptions::new().with_skip_arrow_metadata(true);
2472        let mut file = vec![];
2473        let mut writer =
2474            ArrowWriter::try_new_with_options(&mut file, writer_schema, options).unwrap();
2475        writer.write(&batch).unwrap();
2476        writer.close().unwrap();
2477        read_column(file)
2478    }
2479
2480    fn assert_compatible_roundtrip(field: Field, actual: ArrayRef, expected: &ArrayRef) {
2481        assert!(!compute_leaves(&field, &actual).unwrap().is_empty());
2482        assert_eq!(
2483            roundtrip_compatible_column(field, actual).as_ref(),
2484            expected.as_ref()
2485        );
2486    }
2487
2488    fn run_end_type(value_type: DataType, nullable_values: bool) -> DataType {
2489        DataType::RunEndEncoded(
2490            Arc::new(Field::new(
2491                Field::REE_RUN_ENDS_FIELD_DEFAULT_NAME,
2492                DataType::Int32,
2493                false,
2494            )),
2495            Arc::new(Field::new(
2496                Field::REE_VALUES_FIELD_DEFAULT_NAME,
2497                value_type,
2498                nullable_values,
2499            )),
2500        )
2501    }
2502
2503    #[test]
2504    fn arrow_writer_required_ree_schema_rejects_nullable_dense_input() {
2505        let writer_schema = Arc::new(Schema::new(vec![Field::new(
2506            "c",
2507            run_end_type(DataType::Int32, false),
2508            false,
2509        )]));
2510        let batch_schema = Arc::new(Schema::new(vec![Field::new("c", DataType::Int32, true)]));
2511        let batch = RecordBatch::try_new(
2512            batch_schema.clone(),
2513            vec![Arc::new(Int32Array::from(vec![Some(7), None, Some(9)]))],
2514        )
2515        .unwrap();
2516
2517        for skip_metadata in [false, true] {
2518            for cdc in [false, true] {
2519                let props = WriterProperties::builder()
2520                    .set_content_defined_chunking(cdc.then(Default::default))
2521                    .build();
2522                let options = ArrowWriterOptions::new()
2523                    .with_properties(props)
2524                    .with_skip_arrow_metadata(skip_metadata);
2525                let mut writer = ArrowWriter::try_new_with_options(
2526                    Vec::new(),
2527                    writer_schema.clone(),
2528                    options.clone(),
2529                )
2530                .unwrap();
2531                let error = writer.write(&batch).unwrap_err().to_string();
2532                assert!(
2533                    error.contains("Found null at index 1 for required field 'c'"),
2534                    "skip_metadata={skip_metadata}, cdc={cdc}: {error}"
2535                );
2536
2537                // A nullable batch schema is fine when the data has no actual nulls.
2538                let values: ArrayRef = Arc::new(Int32Array::from(vec![7, 8, 9]));
2539                let batch =
2540                    RecordBatch::try_new(batch_schema.clone(), vec![values.clone()]).unwrap();
2541                let mut file = vec![];
2542                let mut writer =
2543                    ArrowWriter::try_new_with_options(&mut file, writer_schema.clone(), options)
2544                        .unwrap();
2545                writer.write(&batch).unwrap();
2546                writer.close().unwrap();
2547                assert_eq!(read_column(file).as_ref(), values.as_ref());
2548            }
2549        }
2550    }
2551
2552    #[test]
2553    fn ree_nulls_respect_dense_schema_nullability() {
2554        let run_ends = Int32Array::from(vec![2, 4, 5]);
2555        let values = Int32Array::from(vec![Some(1), None, Some(2)]);
2556        let ree: ArrayRef = Arc::new(Int32RunArray::try_new(&run_ends, &values).unwrap());
2557        let ree_batch = RecordBatch::try_new(
2558            Arc::new(Schema::new(vec![Field::new(
2559                "c",
2560                ree.data_type().clone(),
2561                true,
2562            )])),
2563            vec![ree],
2564        )
2565        .unwrap();
2566
2567        let nullable_schema = Arc::new(Schema::new(vec![Field::new("c", DataType::Int32, true)]));
2568        let mut file = vec![];
2569        let mut writer = ArrowWriter::try_new(&mut file, nullable_schema, None).unwrap();
2570        writer.write(&ree_batch).unwrap();
2571        writer.close().unwrap();
2572        assert_eq!(
2573            read_column(file).as_primitive::<Int32Type>(),
2574            &Int32Array::from(vec![Some(1), Some(1), None, None, Some(2)])
2575        );
2576
2577        let required_schema = Arc::new(Schema::new(vec![Field::new("c", DataType::Int32, false)]));
2578        let mut writer = ArrowWriter::try_new(Vec::new(), required_schema, None).unwrap();
2579        let error = writer.write(&ree_batch).unwrap_err().to_string();
2580        assert!(error.contains("Found null") && error.contains("required field 'c'"));
2581    }
2582
2583    #[test]
2584    fn required_null_validation_respects_reachability_and_write_timing() {
2585        let required = Field::new("c", DataType::Int32, false);
2586        let nullable: ArrayRef = Arc::new(Int32Array::from(vec![Some(1), None]));
2587        let leaves = compute_leaves(&required, &nullable).unwrap();
2588        let schema = Arc::new(Schema::new(vec![required.clone()]));
2589        let writer = ArrowWriter::try_new(Vec::new(), schema, None).unwrap();
2590        let (_file, factory) = writer.into_serialized_writer().unwrap();
2591        let mut columns = factory.create_column_writers(0).unwrap();
2592        assert!(
2593            columns[0]
2594                .write(&leaves[0])
2595                .unwrap_err()
2596                .to_string()
2597                .contains("required field 'c'")
2598        );
2599
2600        // Only a referenced logical dictionary null is invalid, not an unused value.
2601        let values: ArrayRef = Arc::new(Int32Array::from(vec![Some(7), None]));
2602        let dict: ArrayRef = Arc::new(DictionaryArray::new(
2603            Int8Array::from(vec![0, 0]),
2604            values.clone(),
2605        ));
2606        assert_eq!(
2607            roundtrip_compatible_column(required.clone(), dict).as_primitive::<Int32Type>(),
2608            &Int32Array::from(vec![7, 7])
2609        );
2610        let dict: ArrayRef = Arc::new(DictionaryArray::new(Int8Array::from(vec![0, 1]), values));
2611        let leaves = compute_leaves(&required, &dict).unwrap();
2612        assert!(leaves[0].0.validate().is_err());
2613        let dict: ArrayRef = Arc::new(DictionaryArray::new(
2614            Int8Array::from(vec![Some(0), None]),
2615            Arc::new(Int32Array::from(vec![7])),
2616        ));
2617        let leaves = compute_leaves(&required, &dict).unwrap();
2618        assert!(leaves[0].0.validate().is_err());
2619
2620        // A nullable ancestor masks an otherwise required child null, including
2621        // when the target child has a schema-only REE wrapper.
2622        let actual_fields = Fields::from(vec![Field::new("source_child", DataType::Int32, true)]);
2623        let array: ArrayRef = Arc::new(StructArray::new(
2624            actual_fields.clone(),
2625            vec![nullable.clone()],
2626            Some(NullBuffer::from(vec![true, false])),
2627        ));
2628        let unmasked: ArrayRef = Arc::new(StructArray::new(
2629            actual_fields,
2630            vec![nullable.clone()],
2631            None,
2632        ));
2633        for child_type in [DataType::Int32, run_end_type(DataType::Int32, false)] {
2634            let target = Field::new(
2635                "c",
2636                DataType::Struct(Fields::from(vec![Field::new(
2637                    "target_child",
2638                    child_type,
2639                    false,
2640                )])),
2641                true,
2642            );
2643            let leaves = compute_leaves(&target, &unmasked).unwrap();
2644            assert!(leaves[0].0.validate().is_err());
2645            let leaves = compute_leaves(&target, &array).unwrap();
2646            assert!(leaves[0].0.validate().is_ok());
2647            let result = roundtrip_compatible_column(target, array.clone());
2648            assert_eq!(result.as_struct().fields()[0].name(), "target_child");
2649            assert!(result.is_null(1));
2650        }
2651
2652        // Unused list child slots and out-of-slice scalar nulls are unreachable.
2653        let values: ArrayRef = Arc::new(Int32Array::from(vec![None, Some(9), None]));
2654        let list: ArrayRef = Arc::new(ListArray::new(
2655            Arc::new(Field::new_list_field(DataType::Int32, true)),
2656            OffsetBuffer::new(vec![1_i32, 2].into()),
2657            values,
2658            None,
2659        ));
2660        let target = Field::new(
2661            "c",
2662            DataType::List(Arc::new(Field::new_list_field(DataType::Int32, false))),
2663            false,
2664        );
2665        assert!(
2666            compute_leaves(&target, &list).unwrap()[0]
2667                .0
2668                .validate()
2669                .is_ok()
2670        );
2671        assert_eq!(
2672            roundtrip_compatible_column(required, nullable.slice(0, 1)).as_primitive::<Int32Type>(),
2673            &Int32Array::from(vec![1])
2674        );
2675    }
2676
2677    fn check_required_list_validation(list_type: fn(Arc<Field>) -> DataType) {
2678        let make_array = |values: Vec<Option<i32>>,
2679                          offsets: Vec<i32>,
2680                          sizes: Vec<i32>,
2681                          nulls: Option<NullBuffer>| {
2682            let child = Arc::new(Field::new("source_child", DataType::Int32, true));
2683            let values: ArrayRef = Arc::new(Int32Array::from(values));
2684            match list_type(child.clone()) {
2685                DataType::List(_) => Arc::new(ListArray::new(
2686                    child,
2687                    OffsetBuffer::new(offsets.into()),
2688                    values,
2689                    nulls,
2690                )) as ArrayRef,
2691                DataType::LargeList(_) => Arc::new(LargeListArray::new(
2692                    child,
2693                    OffsetBuffer::new(
2694                        offsets
2695                            .into_iter()
2696                            .map(i64::from)
2697                            .collect::<Vec<_>>()
2698                            .into(),
2699                    ),
2700                    values,
2701                    nulls,
2702                )) as ArrayRef,
2703                DataType::ListView(_) => Arc::new(ListViewArray::new(
2704                    child,
2705                    offsets.into(),
2706                    sizes.into(),
2707                    values,
2708                    nulls,
2709                )) as ArrayRef,
2710                DataType::LargeListView(_) => Arc::new(LargeListViewArray::new(
2711                    child,
2712                    offsets
2713                        .into_iter()
2714                        .map(i64::from)
2715                        .collect::<Vec<_>>()
2716                        .into(),
2717                    sizes.into_iter().map(i64::from).collect::<Vec<_>>().into(),
2718                    values,
2719                    nulls,
2720                )) as ArrayRef,
2721                _ => unreachable!(),
2722            }
2723        };
2724        let is_view = matches!(
2725            list_type(Arc::new(Field::new("item", DataType::Int32, true))),
2726            DataType::ListView(_) | DataType::LargeListView(_)
2727        );
2728        let offsets = |starts: Vec<i32>, end: i32| {
2729            let mut result = starts;
2730            if !is_view {
2731                result.push(end);
2732            }
2733            result
2734        };
2735        let target = Field::new(
2736            "c",
2737            list_type(Arc::new(Field::new("target_child", DataType::Int32, false))),
2738            true,
2739        );
2740        let invalid = make_array(vec![None, Some(7)], offsets(vec![0], 2), vec![2], None);
2741        let valid = make_array(vec![Some(7), Some(8)], offsets(vec![0], 2), vec![2], None);
2742        let masked = make_array(
2743            vec![None, Some(7)],
2744            offsets(vec![0, 1], 2),
2745            vec![1, 1],
2746            Some(NullBuffer::from(vec![false, true])),
2747        );
2748        let unused = make_array(
2749            vec![None, Some(7), None],
2750            offsets(vec![1], 2),
2751            vec![1],
2752            None,
2753        );
2754        let empty = make_array(vec![None], offsets(vec![0], 0), vec![0], None);
2755        let sliced = make_array(
2756            vec![None, Some(7)],
2757            offsets(vec![0, 1], 2),
2758            vec![1, 1],
2759            None,
2760        )
2761        .slice(1, 1);
2762        let schema = Arc::new(Schema::new(vec![target.clone()]));
2763
2764        // Binding succeeds even for invalid input; writing the affected leaf rejects it.
2765        for (name, array, invalid) in [
2766            ("reachable null", invalid, true),
2767            ("valid required child", valid.clone(), false),
2768            ("null ancestor", masked, false),
2769            ("unused child slots", unused, false),
2770            ("empty list", empty, false),
2771            ("out-of-slice null", sliced, false),
2772        ] {
2773            let leaves = compute_leaves(&target, &array).unwrap();
2774            assert_eq!(leaves.len(), 1);
2775            for cdc in [false, true] {
2776                let props = WriterProperties::builder()
2777                    .set_content_defined_chunking(cdc.then(Default::default))
2778                    .build();
2779                let mut writer =
2780                    ArrowWriter::try_new(Vec::new(), schema.clone(), Some(props)).unwrap();
2781                let mut chunkers = writer.cdc_chunkers.take();
2782                let (_file, factory) = writer.into_serialized_writer().unwrap();
2783                let mut columns = factory.create_column_writers(0).unwrap();
2784                let before = (
2785                    columns[0].memory_size(),
2786                    columns[0].get_estimated_total_bytes(),
2787                );
2788                let result = match &mut chunkers {
2789                    Some(chunkers) => columns[0].write_with_chunker(&leaves[0], &mut chunkers[0]),
2790                    None => columns[0].write(&leaves[0]),
2791                };
2792                if invalid {
2793                    let error = result.unwrap_err().to_string();
2794                    assert!(
2795                        error.contains("Found null at index 0 for required field 'target_child'"),
2796                        "{name}, cdc={cdc}: {error}"
2797                    );
2798                    assert_eq!(
2799                        before,
2800                        (
2801                            columns[0].memory_size(),
2802                            columns[0].get_estimated_total_bytes()
2803                        ),
2804                        "invalid leaf must be rejected before encoding"
2805                    );
2806                    // A rejected leaf write must leave no encoded values behind.
2807                    let valid_leaves = compute_leaves(&target, &valid).unwrap();
2808                    match &mut chunkers {
2809                        Some(chunkers) => columns[0]
2810                            .write_with_chunker(&valid_leaves[0], &mut chunkers[0])
2811                            .unwrap(),
2812                        None => columns[0].write(&valid_leaves[0]).unwrap(),
2813                    }
2814                    assert_eq!(
2815                        columns
2816                            .pop()
2817                            .unwrap()
2818                            .close()
2819                            .unwrap()
2820                            .close
2821                            .metadata
2822                            .num_values(),
2823                        2
2824                    );
2825                } else {
2826                    result.unwrap();
2827                    columns.pop().unwrap().close().unwrap();
2828                }
2829
2830                // Exercise the ordinary and CDC row-group driving entry points as well.
2831                let batch = RecordBatch::try_new(
2832                    Arc::new(Schema::new(vec![Field::new(
2833                        "c",
2834                        array.data_type().clone(),
2835                        true,
2836                    )])),
2837                    vec![array.clone()],
2838                )
2839                .unwrap();
2840                let props = WriterProperties::builder()
2841                    .set_content_defined_chunking(cdc.then(Default::default))
2842                    .build();
2843                let mut writer =
2844                    ArrowWriter::try_new(Vec::new(), schema.clone(), Some(props)).unwrap();
2845                let result = writer.write(&batch);
2846                if invalid {
2847                    assert!(
2848                        result
2849                            .unwrap_err()
2850                            .to_string()
2851                            .contains("required field 'target_child'")
2852                    );
2853                } else {
2854                    result.unwrap();
2855                    writer.close().unwrap();
2856                }
2857            }
2858        }
2859    }
2860
2861    #[test]
2862    fn required_list_validation_preserves_level_generation() {
2863        check_required_list_validation(DataType::List);
2864    }
2865
2866    #[test]
2867    fn required_large_list_validation_preserves_level_generation() {
2868        check_required_list_validation(DataType::LargeList);
2869    }
2870
2871    #[test]
2872    fn required_list_view_validation_preserves_level_generation() {
2873        check_required_list_validation(DataType::ListView);
2874    }
2875
2876    #[test]
2877    fn required_large_list_view_validation_preserves_level_generation() {
2878        check_required_list_validation(DataType::LargeListView);
2879    }
2880
2881    fn nullable_int32_list() -> ArrayRef {
2882        Arc::new(ListArray::new(
2883            Arc::new(Field::new_list_field(DataType::Int32, true)),
2884            OffsetBuffer::new(vec![0_i32, 2, 3].into()),
2885            Arc::new(Int32Array::from(vec![Some(1), None, Some(3)])),
2886            None,
2887        ))
2888    }
2889
2890    #[test]
2891    fn arrow_writer_dense_list_under_ree_schema() {
2892        let list = nullable_int32_list();
2893        // The schema wrapper is physical, not a second logical list node.
2894        let field = Field::new("c", run_end_type(list.data_type().clone(), false), false);
2895        assert_compatible_roundtrip(field, list.clone(), &list);
2896    }
2897
2898    #[test]
2899    fn arrow_writer_dense_list_under_dictionary_schema() {
2900        let list = nullable_int32_list();
2901        let field = Field::new(
2902            "c",
2903            DataType::Dictionary(Box::new(DataType::Int8), Box::new(list.data_type().clone())),
2904            false,
2905        );
2906        assert_compatible_roundtrip(field, list.clone(), &list);
2907    }
2908
2909    #[test]
2910    fn arrow_writer_dense_values_under_nested_ree_schema() {
2911        let dense: ArrayRef = Arc::new(Int32Array::from(vec![Some(7), None, Some(9)]));
2912        let field = Field::new(
2913            "c",
2914            run_end_type(run_end_type(DataType::Int32, true), false),
2915            false,
2916        );
2917        assert_compatible_roundtrip(field, dense.clone(), &dense);
2918    }
2919
2920    #[test]
2921    fn arrow_writer_dense_values_under_dictionary_ree_schema() {
2922        let dense: ArrayRef = Arc::new(Int32Array::from(vec![Some(7), None, Some(9)]));
2923        let field = Field::new(
2924            "c",
2925            DataType::Dictionary(
2926                Box::new(DataType::Int8),
2927                Box::new(run_end_type(DataType::Int32, true)),
2928            ),
2929            false,
2930        );
2931        assert_compatible_roundtrip(field, dense.clone(), &dense);
2932    }
2933
2934    #[test]
2935    fn arrow_writer_dense_values_under_ree_dictionary_schema() {
2936        let dense: ArrayRef = Arc::new(Int32Array::from(vec![Some(7), None, Some(9)]));
2937        // Hoist REE value nullability before peeling the dictionary; the
2938        // dense batch contains an actual null despite the required outer field.
2939        let field = Field::new(
2940            "c",
2941            run_end_type(
2942                DataType::Dictionary(Box::new(DataType::Int8), Box::new(DataType::Int32)),
2943                true,
2944            ),
2945            false,
2946        );
2947        assert_compatible_roundtrip(field, dense.clone(), &dense);
2948    }
2949
2950    #[test]
2951    fn arrow_writer_dense_struct_under_ree_child_schema() {
2952        let dense: ArrayRef = Arc::new(Int32Array::from(vec![Some(7), None, Some(9)]));
2953        let struct_fields = Fields::from(vec![Field::new("value", DataType::Int32, true)]);
2954        let dense_struct: ArrayRef = Arc::new(StructArray::new(struct_fields, vec![dense], None));
2955        // A wrapper on a child must not make the enclosing struct incompatible.
2956        let field = Field::new(
2957            "c",
2958            DataType::Struct(Fields::from(vec![Field::new(
2959                "value",
2960                run_end_type(DataType::Int32, true),
2961                false,
2962            )])),
2963            false,
2964        );
2965        assert_compatible_roundtrip(field, dense_struct.clone(), &dense_struct);
2966    }
2967
2968    #[test]
2969    fn arrow_writer_dense_list_under_ree_child_schema() {
2970        let list = nullable_int32_list();
2971        let field = Field::new(
2972            "c",
2973            DataType::List(Arc::new(Field::new(
2974                "item",
2975                run_end_type(DataType::Int32, true),
2976                false,
2977            ))),
2978            false,
2979        );
2980        assert_compatible_roundtrip(field, list.clone(), &list);
2981    }
2982
2983    #[test]
2984    fn arrow_writer_dense_list_under_dictionary_child_schema() {
2985        let list = nullable_int32_list();
2986        let field = Field::new(
2987            "c",
2988            DataType::List(Arc::new(Field::new_list_field(
2989                DataType::Dictionary(Box::new(DataType::Int8), Box::new(DataType::Int32)),
2990                true,
2991            ))),
2992            false,
2993        );
2994        assert_compatible_roundtrip(field, list.clone(), &list);
2995    }
2996
2997    #[test]
2998    fn arrow_writer_dictionary_list_under_dense_child_schema() {
2999        let dict: ArrayRef = Arc::new(DictionaryArray::new(
3000            Int8Array::from(vec![Some(0), None, Some(1)]),
3001            Arc::new(Int32Array::from(vec![1, 3])),
3002        ));
3003        let dict_list: ArrayRef = Arc::new(ListArray::new(
3004            Arc::new(Field::new_list_field(dict.data_type().clone(), true)),
3005            OffsetBuffer::new(vec![0_i32, 2, 3].into()),
3006            dict,
3007            None,
3008        ));
3009        let expected = nullable_int32_list();
3010        assert_compatible_roundtrip(
3011            Field::new("c", expected.data_type().clone(), false),
3012            dict_list,
3013            &expected,
3014        );
3015    }
3016
3017    #[test]
3018    fn arrow_writer_dense_map_under_ree_value_schema() {
3019        let key_field = Arc::new(Field::new("keys", DataType::Utf8, false));
3020        let entries = StructArray::new(
3021            Fields::from(vec![
3022                key_field.clone(),
3023                Arc::new(Field::new("values", DataType::Int32, true)),
3024            ]),
3025            vec![
3026                Arc::new(StringArray::from(vec!["a", "b", "c"])) as ArrayRef,
3027                Arc::new(Int32Array::from(vec![Some(7), None, Some(9)])),
3028            ],
3029            None,
3030        );
3031        let map: ArrayRef = Arc::new(MapArray::new(
3032            Arc::new(Field::new("entries", entries.data_type().clone(), false)),
3033            OffsetBuffer::new(vec![0_i32, 2, 3].into()),
3034            entries,
3035            None,
3036            false,
3037        ));
3038        // Resolve the value wrapper after walking through the entries struct.
3039        let field = Field::new(
3040            "c",
3041            DataType::Map(
3042                Arc::new(Field::new(
3043                    "entries",
3044                    DataType::Struct(Fields::from(vec![
3045                        key_field,
3046                        Arc::new(Field::new(
3047                            "values",
3048                            run_end_type(DataType::Int32, true),
3049                            false,
3050                        )),
3051                    ])),
3052                    false,
3053                )),
3054                false,
3055            ),
3056            false,
3057        );
3058        assert_compatible_roundtrip(field, map.clone(), &map);
3059    }
3060
3061    #[test]
3062    fn arrow_writer_nested_dictionary_metadata_roundtrips_with_default_reader() {
3063        let dense: ArrayRef = Arc::new(StructArray::new(
3064            Fields::from(vec![Field::new("item", DataType::Int32, true)]),
3065            vec![Arc::new(Int32Array::from(vec![Some(7), None, Some(9)]))],
3066            None,
3067        ));
3068        let field = Field::new(
3069            "value",
3070            DataType::Dictionary(
3071                Box::new(DataType::Int8),
3072                Box::new(dense.data_type().clone()),
3073            ),
3074            false,
3075        )
3076        .with_metadata(HashMap::from([(
3077            "description".to_string(),
3078            "nested dictionary".to_string(),
3079        )]));
3080        let writer_schema = Arc::new(Schema::new(vec![field.clone()]));
3081        let expected_schema = Arc::new(Schema::new(vec![
3082            field.with_data_type(dense.data_type().clone()),
3083        ]));
3084        let batch = RecordBatch::try_new(expected_schema.clone(), vec![dense]).unwrap();
3085
3086        // Keep Arrow metadata enabled: ignoring it would hide the original
3087        // reader-initialization failure caused by the nested dictionary hint.
3088        let mut file = vec![];
3089        let mut writer = ArrowWriter::try_new(&mut file, writer_schema, None).unwrap();
3090        writer.write(&batch).unwrap();
3091        writer.close().unwrap();
3092
3093        let builder = ParquetRecordBatchReaderBuilder::try_new(Bytes::from(file)).unwrap();
3094        assert!(
3095            builder
3096                .metadata()
3097                .file_metadata()
3098                .key_value_metadata()
3099                .unwrap()
3100                .iter()
3101                .any(|kv| kv.key == ARROW_SCHEMA_META_KEY)
3102        );
3103        assert_eq!(builder.schema(), &expected_schema);
3104        let decoded = builder
3105            .build()
3106            .unwrap()
3107            .collect::<ArrowResult<Vec<_>>>()
3108            .unwrap();
3109        assert_eq!(decoded, vec![batch]);
3110    }
3111
3112    #[test]
3113    fn arrow_writer_page_size() {
3114        let schema = Arc::new(Schema::new(vec![Field::new("col", DataType::Utf8, false)]));
3115
3116        let mut builder = StringBuilder::with_capacity(100, 329 * 10_000);
3117
3118        // Generate an array of 10 unique 10 character string
3119        for i in 0..10 {
3120            let value = i
3121                .to_string()
3122                .repeat(10)
3123                .chars()
3124                .take(10)
3125                .collect::<String>();
3126
3127            builder.append_value(value);
3128        }
3129
3130        let array = Arc::new(builder.finish());
3131
3132        let batch = RecordBatch::try_new(schema, vec![array]).unwrap();
3133
3134        let file = tempfile::tempfile().unwrap();
3135
3136        // Set everything very low so we fallback to PLAIN encoding after the first row
3137        let props = WriterProperties::builder()
3138            .set_data_page_size_limit(1)
3139            .set_dictionary_page_size_limit(1)
3140            .set_write_batch_size(1)
3141            .build();
3142
3143        let mut writer =
3144            ArrowWriter::try_new(file.try_clone().unwrap(), batch.schema(), Some(props))
3145                .expect("Unable to write file");
3146        writer.write(&batch).unwrap();
3147        writer.close().unwrap();
3148
3149        let options = ReadOptionsBuilder::new().with_page_index().build();
3150        let reader =
3151            SerializedFileReader::new_with_options(file.try_clone().unwrap(), options).unwrap();
3152
3153        let column = reader.metadata().row_group(0).columns();
3154
3155        assert_eq!(column.len(), 1);
3156
3157        // We should write one row before falling back to PLAIN encoding so there should still be a
3158        // dictionary page.
3159        assert!(
3160            column[0].dictionary_page_offset().is_some(),
3161            "Expected a dictionary page"
3162        );
3163
3164        let page_index = reader
3165            .metadata()
3166            .page_index()
3167            .expect("page index should be present");
3168        let page_locations = page_index
3169            .page_locations(0, 0)
3170            .expect("page locations should exist");
3171
3172        // We should fallback to PLAIN encoding after the first row and our max page size is 1 bytes
3173        // so we expect one dictionary encoded page and then a page per row thereafter.
3174        assert_eq!(
3175            page_locations.len(),
3176            10,
3177            "Expected 10 pages but got {page_locations:#?}"
3178        );
3179    }
3180
3181    const MEDIUM_SIZE: usize = 63;
3182
3183    fn check_bloom_filter<T: AsBytes>(
3184        files: Vec<Bytes>,
3185        file_column: String,
3186        positive_values: Vec<T>,
3187        negative_values: Vec<T>,
3188    ) {
3189        files.into_iter().take(1).for_each(|file| {
3190            let file_reader = SerializedFileReader::new_with_options(
3191                file,
3192                ReadOptionsBuilder::new()
3193                    .with_reader_properties(
3194                        ReaderProperties::builder()
3195                            .set_read_bloom_filter(true)
3196                            .build(),
3197                    )
3198                    .build(),
3199            )
3200            .expect("Unable to open file as Parquet");
3201            let metadata = file_reader.metadata();
3202
3203            // Gets bloom filters from all row groups.
3204            let mut bloom_filters: Vec<_> = vec![];
3205            for (ri, row_group) in metadata.row_groups().iter().enumerate() {
3206                if let Some((column_index, _)) = row_group
3207                    .columns()
3208                    .iter()
3209                    .enumerate()
3210                    .find(|(_, column)| column.column_path().string() == file_column)
3211                {
3212                    let row_group_reader = file_reader
3213                        .get_row_group(ri)
3214                        .expect("Unable to read row group");
3215                    if let Some(sbbf) = row_group_reader.get_column_bloom_filter(column_index) {
3216                        bloom_filters.push(sbbf.clone());
3217                    } else {
3218                        panic!("No bloom filter for column named {file_column} found");
3219                    }
3220                } else {
3221                    panic!("No column named {file_column} found");
3222                }
3223            }
3224
3225            positive_values.iter().for_each(|value| {
3226                let found = bloom_filters.iter().find(|sbbf| sbbf.check(value));
3227                assert!(
3228                    found.is_some(),
3229                    "{}",
3230                    format!("Value {:?} should be in bloom filter", value.as_bytes())
3231                );
3232            });
3233
3234            negative_values.iter().for_each(|value| {
3235                let found = bloom_filters.iter().find(|sbbf| sbbf.check(value));
3236                assert!(
3237                    found.is_none(),
3238                    "{}",
3239                    format!("Value {:?} should not be in bloom filter", value.as_bytes())
3240                );
3241            });
3242        });
3243    }
3244
3245    #[test]
3246    #[cfg_attr(miri, ignore)] // Takes too long
3247    fn bool_large_single_column() {
3248        let values = Arc::new(
3249            [None, Some(true), Some(false)]
3250                .iter()
3251                .cycle()
3252                .copied()
3253                .take(200_000)
3254                .collect::<BooleanArray>(),
3255        );
3256        let schema = Schema::new(vec![Field::new("col", values.data_type().clone(), true)]);
3257        let expected_batch = RecordBatch::try_new(Arc::new(schema), vec![values]).unwrap();
3258        let file = tempfile::tempfile().unwrap();
3259
3260        let mut writer =
3261            ArrowWriter::try_new(file.try_clone().unwrap(), expected_batch.schema(), None)
3262                .expect("Unable to write file");
3263        writer.write(&expected_batch).unwrap();
3264        writer.close().unwrap();
3265    }
3266
3267    #[test]
3268    fn check_page_offset_index_with_nan() {
3269        let values = Arc::new(Float64Array::from(vec![f64::NAN; 10]));
3270        let schema = Schema::new(vec![Field::new("col", DataType::Float64, true)]);
3271        let batch = RecordBatch::try_new(Arc::new(schema), vec![values]).unwrap();
3272
3273        let mut out = Vec::with_capacity(1024);
3274        let mut writer =
3275            ArrowWriter::try_new(&mut out, batch.schema(), None).expect("Unable to write file");
3276        writer.write(&batch).unwrap();
3277        let file_meta_data = writer.close().unwrap();
3278        for row_group in file_meta_data.row_groups() {
3279            for column in row_group.columns() {
3280                assert!(column.offset_index_offset().is_some());
3281                assert!(column.offset_index_length().is_some());
3282                assert!(column.column_index_offset().is_some());
3283                assert!(column.column_index_length().is_some());
3284            }
3285        }
3286        if let Some(page_index) = file_meta_data.page_index() {
3287            for rg in 0..file_meta_data.num_row_groups() {
3288                for col in 0..file_meta_data.row_group(rg).num_columns() {
3289                    let idx = page_index
3290                        .column_index(rg, col)
3291                        .expect("column index should exist");
3292                    assert!(idx.nan_counts().is_some());
3293                    let ColumnIndexMetaData::DOUBLE(float_idx) = idx else {
3294                        panic!("expected double statistics")
3295                    };
3296                    for i in 0..idx.num_pages() as usize {
3297                        assert_eq!(float_idx.nan_count(i), Some(10));
3298                        assert_eq!(
3299                            f64::NAN.total_cmp(float_idx.min_value(i).unwrap()),
3300                            Ordering::Equal
3301                        );
3302                        assert_eq!(
3303                            f64::NAN.total_cmp(float_idx.max_value(i).unwrap()),
3304                            Ordering::Equal
3305                        );
3306                    }
3307                }
3308            }
3309        } else {
3310            panic!("page index should be present");
3311        }
3312    }
3313
3314    #[test]
3315    fn check_page_offset_index_with_mixed_nan() {
3316        let schema = Arc::new(Schema::new(vec![Field::new(
3317            "col",
3318            DataType::Float64,
3319            true,
3320        )]));
3321
3322        let mut out = Vec::with_capacity(1024);
3323        let props = WriterProperties::builder()
3324            .set_data_page_row_count_limit(10)
3325            .build();
3326        let mut writer = ArrowWriter::try_new(&mut out, schema.clone(), Some(props))
3327            .expect("Unable to write file");
3328
3329        // write a page of all NaN (since batch min and max are NaN, global min/max are NaN)
3330        let values = Arc::new(Float64Array::from(vec![f64::NAN; 10]));
3331        let batch = RecordBatch::try_new(schema.clone(), vec![values]).unwrap();
3332        writer.write(&batch).unwrap();
3333
3334        // write a page of all -NaN (batch min/max is -NaN, should update global min to -NaN)
3335        let values = Arc::new(Float64Array::from(vec![-f64::NAN; 10]));
3336        let batch = RecordBatch::try_new(schema.clone(), vec![values]).unwrap();
3337        writer.write(&batch).unwrap();
3338
3339        // write a page of all 0 (non-NaN should override global min/max, now 0/0)
3340        let values = Arc::new(Float64Array::from(vec![0_f64; 10]));
3341        let batch = RecordBatch::try_new(schema.clone(), vec![values]).unwrap();
3342        writer.write(&batch).unwrap();
3343
3344        // write a mixed page (should now have min -1, max 1)
3345        let values = Arc::new(Float64Array::from(vec![
3346            -1.0,
3347            0.0,
3348            f64::NAN,
3349            -f64::NAN,
3350            1.0,
3351        ]));
3352        let batch = RecordBatch::try_new(schema.clone(), vec![values]).unwrap();
3353        writer.write(&batch).unwrap();
3354
3355        let file_meta_data = writer.close().unwrap();
3356
3357        // check the column chunk stats are correct
3358        let col_stats = file_meta_data
3359            .row_group(0)
3360            .column(0)
3361            .statistics()
3362            .expect("missing column chunk statistics");
3363
3364        assert_eq!(col_stats.nan_count_opt(), Some(22));
3365        assert_eq!(col_stats.min_bytes_opt(), Some((-1.0f64).as_bytes()));
3366        assert_eq!(col_stats.max_bytes_opt(), Some(1.0f64.as_bytes()));
3367
3368        assert!(file_meta_data.page_index().is_some());
3369        let col_idx = &file_meta_data.page_index().unwrap().column_index(0, 0);
3370        assert_eq!(col_idx.as_ref().unwrap().num_pages(), 4);
3371
3372        // test each page
3373        let Some(ColumnIndexMetaData::DOUBLE(float_idx)) = col_idx else {
3374            panic!("expected double statistics")
3375        };
3376
3377        assert_eq!(float_idx.nan_counts, Some(vec![10, 10, 0, 2]));
3378        assert_eq!(
3379            f64::NAN.total_cmp(float_idx.min_value(0).unwrap()),
3380            Ordering::Equal
3381        );
3382        assert_eq!(
3383            f64::NAN.total_cmp(float_idx.max_value(0).unwrap()),
3384            Ordering::Equal
3385        );
3386        assert_eq!(
3387            (-f64::NAN).total_cmp(float_idx.min_value(1).unwrap()),
3388            Ordering::Equal
3389        );
3390        assert_eq!(
3391            (-f64::NAN).total_cmp(float_idx.max_value(1).unwrap()),
3392            Ordering::Equal
3393        );
3394        assert_eq!(float_idx.min_value(2), Some(&0.0));
3395        assert_eq!(float_idx.max_value(2), Some(&0.0));
3396        assert_eq!(float_idx.min_value(3), Some(&-1.0));
3397        assert_eq!(float_idx.max_value(3), Some(&1.0));
3398    }
3399
3400    #[test]
3401    #[should_panic(
3402        expected = "Attempting to write an Arrow interval type MonthDayNano to parquet that is not yet implemented"
3403    )]
3404    fn interval_month_day_nano_single_column() {
3405        required_and_optional::<IntervalMonthDayNanoArray, _>(vec![
3406            IntervalMonthDayNano::new(0, 1, 5),
3407            IntervalMonthDayNano::new(0, 3, 2),
3408            IntervalMonthDayNano::new(3, -2, -5),
3409            IntervalMonthDayNano::new(-200, 4, -1),
3410        ]);
3411    }
3412
3413    #[test]
3414    #[cfg_attr(miri, ignore)] // Takes too long
3415    fn i32_column_bloom_filter_at_end() {
3416        let array = Arc::new(Int32Array::from_iter(0..SMALL_SIZE as i32));
3417        let files = RoundTripTest::new(array)
3418            .with_nullable(false)
3419            .with_bloom_filter(true)
3420            .with_bloom_filter_position(BloomFilterPosition::End)
3421            .run();
3422
3423        check_bloom_filter(
3424            files,
3425            "col".to_string(),
3426            (0..SMALL_SIZE as i32).collect(),
3427            (SMALL_SIZE as i32 + 1..SMALL_SIZE as i32 + 10).collect(),
3428        );
3429    }
3430
3431    #[test]
3432    #[cfg_attr(miri, ignore)] // Takes too long
3433    fn i32_column_bloom_filter() {
3434        let array = Arc::new(Int32Array::from_iter(0..SMALL_SIZE as i32));
3435        let files = RoundTripTest::new(array)
3436            .with_nullable(false)
3437            .with_bloom_filter(true)
3438            .run();
3439
3440        check_bloom_filter(
3441            files,
3442            "col".to_string(),
3443            (0..SMALL_SIZE as i32).collect(),
3444            (SMALL_SIZE as i32 + 1..SMALL_SIZE as i32 + 10).collect(),
3445        );
3446    }
3447
3448    fn write_with_bloom_filter(array: ArrayRef, dictionary_page_size_limit: usize) -> Bytes {
3449        let schema = Arc::new(Schema::new(vec![Field::new(
3450            "col",
3451            array.data_type().clone(),
3452            false,
3453        )]));
3454        let batch = RecordBatch::try_new(schema.clone(), vec![array]).unwrap();
3455        let props = WriterProperties::builder()
3456            .set_dictionary_enabled(true)
3457            .set_dictionary_page_size_limit(dictionary_page_size_limit)
3458            .set_write_batch_size(256)
3459            .set_bloom_filter_enabled(true)
3460            .build();
3461        let mut buf = Vec::new();
3462        let mut writer = ArrowWriter::try_new(&mut buf, schema, Some(props)).unwrap();
3463        writer.write(&batch).unwrap();
3464        writer.close().unwrap();
3465        Bytes::from(buf)
3466    }
3467
3468    fn data_page_encoding_mask(file: &Bytes) -> EncodingMask {
3469        let metadata = ParquetMetaDataReader::new().parse_and_finish(file).unwrap();
3470        *metadata
3471            .row_group(0)
3472            .column(0)
3473            .page_encoding_stats_mask()
3474            .unwrap()
3475    }
3476
3477    /// While a column is dictionary encoded the bloom filter is populated from the dictionary
3478    /// when it is flushed, so a chunk that stays dictionary encoded must still contain every value.
3479    #[test]
3480    fn string_column_bloom_filter_populated_from_dictionary() {
3481        let values: Vec<String> = (0..2000).map(|i| format!("value-{}", i % 10)).collect();
3482        let array = Arc::new(StringArray::from_iter_values(&values));
3483        let file = write_with_bloom_filter(array, 1024 * 1024);
3484        assert!(data_page_encoding_mask(&file).is_only(Encoding::RLE_DICTIONARY));
3485
3486        check_bloom_filter(
3487            vec![file],
3488            "col".to_string(),
3489            (0..10).map(|i| format!("value-{i}").into_bytes()).collect(),
3490            (10..20)
3491                .map(|i| format!("value-{i}").into_bytes())
3492                .collect(),
3493        );
3494    }
3495
3496    /// After falling back from dictionary encoding the filter holds the dictionary's values
3497    /// and every value written plain afterwards.
3498    #[test]
3499    fn string_column_bloom_filter_across_dictionary_fallback() {
3500        let values: Vec<String> = (0..2000).map(|i| format!("value-{i}")).collect();
3501        let array = Arc::new(StringArray::from_iter_values(&values));
3502        let file = write_with_bloom_filter(array, 1024);
3503        let encodings = data_page_encoding_mask(&file);
3504        assert!(
3505            encodings.is_set(Encoding::RLE_DICTIONARY) && encodings.is_set(Encoding::PLAIN),
3506            "expected dictionary and plain data pages, got {encodings:?}"
3507        );
3508
3509        check_bloom_filter(
3510            vec![file],
3511            "col".to_string(),
3512            values.into_iter().map(String::into_bytes).collect(),
3513            (2000..2010)
3514                .map(|i| format!("value-{i}").into_bytes())
3515                .collect(),
3516        );
3517    }
3518
3519    #[test]
3520    fn i64_column_bloom_filter_populated_from_dictionary() {
3521        let array = Arc::new(Int64Array::from_iter_values((0..2000).map(|i| i % 10)));
3522        let file = write_with_bloom_filter(array, 1024 * 1024);
3523        assert!(data_page_encoding_mask(&file).is_only(Encoding::RLE_DICTIONARY));
3524
3525        check_bloom_filter(
3526            vec![file],
3527            "col".to_string(),
3528            (0..10i64).collect(),
3529            (10..20i64).collect(),
3530        );
3531    }
3532
3533    #[test]
3534    fn i64_column_bloom_filter_across_dictionary_fallback() {
3535        let array = Arc::new(Int64Array::from_iter_values(0..2000i64));
3536        let file = write_with_bloom_filter(array, 1024);
3537        let encodings = data_page_encoding_mask(&file);
3538        assert!(
3539            encodings.is_set(Encoding::RLE_DICTIONARY) && encodings.is_set(Encoding::PLAIN),
3540            "expected dictionary and plain data pages, got {encodings:?}"
3541        );
3542
3543        check_bloom_filter(
3544            vec![file],
3545            "col".to_string(),
3546            (0..2000i64).collect(),
3547            (2000..2010i64).collect(),
3548        );
3549    }
3550
3551    /// Test that bloom filter folding produces correct results even when
3552    /// the configured NDV differs significantly from actual NDV.
3553    /// A large NDV means a larger initial filter that gets folded down;
3554    /// a small NDV means a smaller initial filter.
3555    #[test]
3556    #[cfg_attr(miri, ignore)] // Takes too long
3557    fn i32_column_bloom_filter_fixed_ndv() {
3558        let array = Arc::new(Int32Array::from_iter(0..SMALL_SIZE as i32));
3559
3560        // NDV much larger than actual distinct values — tests folding a large filter down
3561        let files = RoundTripTest::new(array.clone())
3562            .with_nullable(false)
3563            .with_bloom_filter(true)
3564            .with_bloom_filter_ndv(1_000_000)
3565            .run();
3566
3567        check_bloom_filter(
3568            files,
3569            "col".to_string(),
3570            (0..SMALL_SIZE as i32).collect(),
3571            (SMALL_SIZE as i32 + 1..SMALL_SIZE as i32 + 10).collect(),
3572        );
3573
3574        // NDV smaller than actual distinct values — tests the underestimate path
3575        let files = RoundTripTest::new(array)
3576            .with_nullable(false)
3577            .with_bloom_filter(true)
3578            .with_bloom_filter_ndv(3)
3579            .run();
3580
3581        check_bloom_filter(
3582            files,
3583            "col".to_string(),
3584            (0..SMALL_SIZE as i32).collect(),
3585            (SMALL_SIZE as i32 + 1..SMALL_SIZE as i32 + 10).collect(),
3586        );
3587    }
3588
3589    #[test]
3590    #[cfg_attr(miri, ignore)] // Takes too long
3591    fn binary_column_bloom_filter() {
3592        let one_vec: Vec<u8> = (0..SMALL_SIZE as u8).collect();
3593        let many_vecs: Vec<_> = std::iter::repeat_n(one_vec, SMALL_SIZE).collect();
3594        let many_vecs_iter = many_vecs.iter().map(|v| v.as_slice());
3595
3596        let array = Arc::new(BinaryArray::from_iter_values(many_vecs_iter));
3597        let files = RoundTripTest::new(array)
3598            .with_nullable(false)
3599            .with_bloom_filter(true)
3600            .run();
3601
3602        check_bloom_filter(
3603            files,
3604            "col".to_string(),
3605            many_vecs,
3606            vec![vec![(SMALL_SIZE + 1) as u8]],
3607        );
3608    }
3609
3610    #[test]
3611    #[cfg_attr(miri, ignore)] // Takes too long
3612    fn empty_string_null_column_bloom_filter() {
3613        let raw_values: Vec<_> = (0..SMALL_SIZE).map(|i| i.to_string()).collect();
3614        let raw_strs = raw_values.iter().map(|s| s.as_str());
3615
3616        let array = Arc::new(StringArray::from_iter_values(raw_strs));
3617        let files = RoundTripTest::new(array)
3618            .with_nullable(false)
3619            .with_bloom_filter(true)
3620            .run();
3621
3622        let optional_raw_values: Vec<_> = raw_values
3623            .iter()
3624            .enumerate()
3625            .filter_map(|(i, v)| if i % 2 == 0 { None } else { Some(v.as_str()) })
3626            .collect();
3627        // For null slots, empty string should not be in bloom filter.
3628        check_bloom_filter(files, "col".to_string(), optional_raw_values, vec![""]);
3629    }
3630
3631    #[test]
3632    fn list_and_map_coerced_names() {
3633        // Create map and list with non-Parquet naming
3634        let list_field =
3635            Field::new_list("my_list", Field::new("item", DataType::Int32, false), false);
3636        let map_field = Field::new_map(
3637            "my_map",
3638            "my_entries",
3639            Field::new("my_keys", DataType::Int32, false),
3640            Field::new("my_values", DataType::Int32, true),
3641            false,
3642            true,
3643        );
3644
3645        let list_array = create_random_array(&list_field, 100, 0.0, 0.0).unwrap();
3646        let map_array = create_random_array(&map_field, 100, 0.0, 0.0).unwrap();
3647
3648        let arrow_schema = Arc::new(Schema::new(vec![list_field, map_field]));
3649
3650        // Write data to Parquet but coerce names to match spec
3651        let props = Some(WriterProperties::builder().set_coerce_types(true).build());
3652        let file = tempfile::tempfile().unwrap();
3653        let mut writer =
3654            ArrowWriter::try_new(file.try_clone().unwrap(), arrow_schema.clone(), props).unwrap();
3655
3656        let batch = RecordBatch::try_new(arrow_schema, vec![list_array, map_array]).unwrap();
3657        writer.write(&batch).unwrap();
3658        let file_metadata = writer.close().unwrap();
3659
3660        let schema = file_metadata.file_metadata().schema();
3661        // Coerced name of "item" should be "element"
3662        let list_field = &schema.get_fields()[0].get_fields()[0];
3663        assert_eq!(list_field.get_fields()[0].name(), "element");
3664
3665        let map_field = &schema.get_fields()[1].get_fields()[0];
3666        // Coerced name of "entries" should be "key_value"
3667        assert_eq!(map_field.name(), "key_value");
3668        // Coerced name of "my_keys" should be "key"
3669        assert_eq!(map_field.get_fields()[0].name(), "key");
3670        // Coerced name of "my_values" should be "value"
3671        assert_eq!(map_field.get_fields()[1].name(), "value");
3672
3673        // Double check schema after reading from the file
3674        let reader = SerializedFileReader::new(file).unwrap();
3675        let file_schema = reader.metadata().file_metadata().schema();
3676        let fields = file_schema.get_fields();
3677        let list_field = &fields[0].get_fields()[0];
3678        assert_eq!(list_field.get_fields()[0].name(), "element");
3679        let map_field = &fields[1].get_fields()[0];
3680        assert_eq!(map_field.name(), "key_value");
3681        assert_eq!(map_field.get_fields()[0].name(), "key");
3682        assert_eq!(map_field.get_fields()[1].name(), "value");
3683    }
3684
3685    #[test]
3686    #[cfg_attr(miri, ignore)] // Takes too long
3687    fn fallback_flush_data_page() {
3688        //tests if the Fallback::flush_data_page clears all buffers correctly
3689        let raw_values: Vec<_> = (0..MEDIUM_SIZE).map(|i| i.to_string()).collect();
3690        let values = Arc::new(StringArray::from(raw_values));
3691        let encodings = vec![
3692            Encoding::DELTA_BYTE_ARRAY,
3693            Encoding::DELTA_LENGTH_BYTE_ARRAY,
3694        ];
3695        let data_type = values.data_type().clone();
3696        let schema = Arc::new(Schema::new(vec![Field::new("col", data_type, false)]));
3697        let expected_batch = RecordBatch::try_new(schema, vec![values]).unwrap();
3698
3699        let row_group_sizes = [1024, SMALL_SIZE, SMALL_SIZE / 2, SMALL_SIZE / 2 + 1, 10];
3700        let data_page_size_limit: usize = 32;
3701        let write_batch_size: usize = 16;
3702
3703        for encoding in &encodings {
3704            for row_group_size in row_group_sizes {
3705                let props = WriterProperties::builder()
3706                    .set_writer_version(WriterVersion::PARQUET_2_0)
3707                    .set_max_row_group_row_count(Some(row_group_size))
3708                    .set_dictionary_enabled(false)
3709                    .set_encoding(*encoding)
3710                    .set_data_page_size_limit(data_page_size_limit)
3711                    .set_write_batch_size(write_batch_size)
3712                    .build();
3713
3714                roundtrip_opts_with_array_validation(&expected_batch, props, |a, b| {
3715                    let string_array_a = StringArray::from(a.clone());
3716                    let string_array_b = StringArray::from(b.clone());
3717                    let vec_a: Vec<&str> = string_array_a.iter().map(|v| v.unwrap()).collect();
3718                    let vec_b: Vec<&str> = string_array_b.iter().map(|v| v.unwrap()).collect();
3719                    assert_eq!(
3720                        vec_a, vec_b,
3721                        "failed for encoder: {encoding:?} and row_group_size: {row_group_size:?}"
3722                    );
3723                });
3724            }
3725        }
3726    }
3727
3728    #[test]
3729    #[cfg_attr(miri, ignore)] // Takes too long
3730    fn u32_min_max() {
3731        // check values roundtrip through parquet
3732        let src = [
3733            u32::MIN,
3734            1,
3735            (i32::MAX as u32) - 1,
3736            i32::MAX as u32,
3737            (i32::MAX as u32) + 1,
3738            u32::MAX - 1,
3739            u32::MAX,
3740        ];
3741        let values = Arc::new(UInt32Array::from_iter_values(src.iter().copied()));
3742        let files = RoundTripTest::new(values).with_nullable(false).run();
3743
3744        for file in files {
3745            // check statistics are valid
3746            let reader = SerializedFileReader::new(file).unwrap();
3747            let metadata = reader.metadata();
3748
3749            let mut row_offset = 0;
3750            for row_group in metadata.row_groups() {
3751                assert_eq!(row_group.num_columns(), 1);
3752                let column = row_group.column(0);
3753
3754                let num_values = column.num_values() as usize;
3755                let src_slice = &src[row_offset..row_offset + num_values];
3756                row_offset += column.num_values() as usize;
3757
3758                let stats = column.statistics().unwrap();
3759                if let Statistics::Int32(stats) = stats {
3760                    assert_eq!(
3761                        *stats.min_opt().unwrap() as u32,
3762                        *src_slice.iter().min().unwrap()
3763                    );
3764                    assert_eq!(
3765                        *stats.max_opt().unwrap() as u32,
3766                        *src_slice.iter().max().unwrap()
3767                    );
3768                } else {
3769                    panic!("Statistics::Int32 missing")
3770                }
3771            }
3772        }
3773    }
3774
3775    #[test]
3776    #[cfg_attr(miri, ignore)] // Takes too long
3777    fn u64_min_max() {
3778        // check values roundtrip through parquet
3779        let src = [
3780            u64::MIN,
3781            1,
3782            (i64::MAX as u64) - 1,
3783            i64::MAX as u64,
3784            (i64::MAX as u64) + 1,
3785            u64::MAX - 1,
3786            u64::MAX,
3787        ];
3788        let values = Arc::new(UInt64Array::from_iter_values(src.iter().copied()));
3789        let files = RoundTripTest::new(values).with_nullable(false).run();
3790
3791        for file in files {
3792            // check statistics are valid
3793            let reader = SerializedFileReader::new(file).unwrap();
3794            let metadata = reader.metadata();
3795
3796            let mut row_offset = 0;
3797            for row_group in metadata.row_groups() {
3798                assert_eq!(row_group.num_columns(), 1);
3799                let column = row_group.column(0);
3800
3801                let num_values = column.num_values() as usize;
3802                let src_slice = &src[row_offset..row_offset + num_values];
3803                row_offset += column.num_values() as usize;
3804
3805                let stats = column.statistics().unwrap();
3806                if let Statistics::Int64(stats) = stats {
3807                    assert_eq!(
3808                        *stats.min_opt().unwrap() as u64,
3809                        *src_slice.iter().min().unwrap()
3810                    );
3811                    assert_eq!(
3812                        *stats.max_opt().unwrap() as u64,
3813                        *src_slice.iter().max().unwrap()
3814                    );
3815                } else {
3816                    panic!("Statistics::Int64 missing")
3817                }
3818            }
3819        }
3820    }
3821
3822    #[test]
3823    #[cfg_attr(miri, ignore)] // Takes too long
3824    fn statistics_null_counts_only_nulls() {
3825        // check that null-count statistics for "only NULL"-columns are correct
3826        let values = Arc::new(UInt64Array::from(vec![None, None]));
3827        let files = RoundTripTest::new(values).run();
3828
3829        for file in files {
3830            // check statistics are valid
3831            let reader = SerializedFileReader::new(file).unwrap();
3832            let metadata = reader.metadata();
3833            assert_eq!(metadata.num_row_groups(), 1);
3834            let row_group = metadata.row_group(0);
3835            assert_eq!(row_group.num_columns(), 1);
3836            let column = row_group.column(0);
3837            let stats = column.statistics().unwrap();
3838            assert_eq!(stats.null_count_opt(), Some(2));
3839        }
3840    }
3841
3842    fn row_group_sizes(metadata: &ParquetMetaData) -> Vec<i64> {
3843        metadata.row_groups().iter().map(|x| x.num_rows()).collect()
3844    }
3845
3846    #[test]
3847    fn test_aggregates_records() {
3848        let arrays = [
3849            Int32Array::from((0..100).collect::<Vec<_>>()),
3850            Int32Array::from((0..50).collect::<Vec<_>>()),
3851            Int32Array::from((200..500).collect::<Vec<_>>()),
3852        ];
3853
3854        let schema = Arc::new(Schema::new(vec![Field::new(
3855            "int",
3856            ArrowDataType::Int32,
3857            false,
3858        )]));
3859
3860        let file = tempfile::tempfile().unwrap();
3861
3862        let props = WriterProperties::builder()
3863            .set_max_row_group_row_count(Some(200))
3864            .build();
3865
3866        let mut writer =
3867            ArrowWriter::try_new(file.try_clone().unwrap(), schema.clone(), Some(props)).unwrap();
3868
3869        for array in arrays {
3870            let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(array)]).unwrap();
3871            writer.write(&batch).unwrap();
3872        }
3873
3874        writer.close().unwrap();
3875
3876        let builder = ParquetRecordBatchReaderBuilder::try_new(file).unwrap();
3877        assert_eq!(&row_group_sizes(builder.metadata()), &[200, 200, 50]);
3878
3879        let batches = builder
3880            .with_batch_size(100)
3881            .build()
3882            .unwrap()
3883            .collect::<ArrowResult<Vec<_>>>()
3884            .unwrap();
3885
3886        assert_eq!(batches.len(), 5);
3887        assert!(batches.iter().all(|x| x.num_columns() == 1));
3888
3889        let batch_sizes: Vec<_> = batches.iter().map(|x| x.num_rows()).collect();
3890
3891        assert_eq!(&batch_sizes, &[100, 100, 100, 100, 50]);
3892
3893        let values: Vec<_> = batches
3894            .iter()
3895            .flat_map(|x| {
3896                x.column(0)
3897                    .as_any()
3898                    .downcast_ref::<Int32Array>()
3899                    .unwrap()
3900                    .values()
3901                    .iter()
3902                    .copied()
3903            })
3904            .collect();
3905
3906        let expected_values: Vec<_> = [0..100, 0..50, 200..500].into_iter().flatten().collect();
3907        assert_eq!(&values, &expected_values)
3908    }
3909
3910    #[test]
3911    fn complex_aggregate() {
3912        // Tests aggregating nested data
3913        let field_a = Arc::new(Field::new("leaf_a", DataType::Int32, false));
3914        let field_b = Arc::new(Field::new("leaf_b", DataType::Int32, true));
3915        let struct_a = Arc::new(Field::new(
3916            "struct_a",
3917            DataType::Struct(vec![field_a.clone(), field_b.clone()].into()),
3918            true,
3919        ));
3920
3921        let list_a = Arc::new(Field::new("list", DataType::List(struct_a), true));
3922        let struct_b = Arc::new(Field::new(
3923            "struct_b",
3924            DataType::Struct(vec![list_a.clone()].into()),
3925            false,
3926        ));
3927
3928        let schema = Arc::new(Schema::new(vec![struct_b]));
3929
3930        // create nested data
3931        let field_a_array = Int32Array::from(vec![1, 2, 3, 4, 5, 6]);
3932        let field_b_array =
3933            Int32Array::from_iter(vec![Some(1), None, Some(2), None, None, Some(6)]);
3934
3935        let struct_a_array = StructArray::from(vec![
3936            (field_a.clone(), Arc::new(field_a_array) as ArrayRef),
3937            (field_b.clone(), Arc::new(field_b_array) as ArrayRef),
3938        ]);
3939
3940        let list_data = ArrayDataBuilder::new(list_a.data_type().clone())
3941            .len(5)
3942            .add_buffer(Buffer::from_iter(vec![
3943                0_i32, 1_i32, 1_i32, 3_i32, 3_i32, 5_i32,
3944            ]))
3945            .null_bit_buffer(Some(Buffer::from_iter(vec![
3946                true, false, true, false, true,
3947            ])))
3948            .child_data(vec![struct_a_array.into_data()])
3949            .build()
3950            .unwrap();
3951
3952        let list_a_array = Arc::new(ListArray::from(list_data)) as ArrayRef;
3953        let struct_b_array = StructArray::from(vec![(list_a.clone(), list_a_array)]);
3954
3955        let batch1 =
3956            RecordBatch::try_from_iter(vec![("struct_b", Arc::new(struct_b_array) as ArrayRef)])
3957                .unwrap();
3958
3959        let field_a_array = Int32Array::from(vec![6, 7, 8, 9, 10]);
3960        let field_b_array = Int32Array::from_iter(vec![None, None, None, Some(1), None]);
3961
3962        let struct_a_array = StructArray::from(vec![
3963            (field_a, Arc::new(field_a_array) as ArrayRef),
3964            (field_b, Arc::new(field_b_array) as ArrayRef),
3965        ]);
3966
3967        let list_data = ArrayDataBuilder::new(list_a.data_type().clone())
3968            .len(2)
3969            .add_buffer(Buffer::from_iter(vec![0_i32, 4_i32, 5_i32]))
3970            .child_data(vec![struct_a_array.into_data()])
3971            .build()
3972            .unwrap();
3973
3974        let list_a_array = Arc::new(ListArray::from(list_data)) as ArrayRef;
3975        let struct_b_array = StructArray::from(vec![(list_a, list_a_array)]);
3976
3977        let batch2 =
3978            RecordBatch::try_from_iter(vec![("struct_b", Arc::new(struct_b_array) as ArrayRef)])
3979                .unwrap();
3980
3981        let batches = &[batch1, batch2];
3982
3983        // Verify data is as expected
3984
3985        let expected = r"
3986            +-------------------------------------------------------------------------------------------------------+
3987            | struct_b                                                                                              |
3988            +-------------------------------------------------------------------------------------------------------+
3989            | {list: [{leaf_a: 1, leaf_b: 1}]}                                                                      |
3990            | {list: }                                                                                              |
3991            | {list: [{leaf_a: 2, leaf_b: }, {leaf_a: 3, leaf_b: 2}]}                                               |
3992            | {list: }                                                                                              |
3993            | {list: [{leaf_a: 4, leaf_b: }, {leaf_a: 5, leaf_b: }]}                                                |
3994            | {list: [{leaf_a: 6, leaf_b: }, {leaf_a: 7, leaf_b: }, {leaf_a: 8, leaf_b: }, {leaf_a: 9, leaf_b: 1}]} |
3995            | {list: [{leaf_a: 10, leaf_b: }]}                                                                      |
3996            +-------------------------------------------------------------------------------------------------------+
3997        ".trim().split('\n').map(|x| x.trim()).collect::<Vec<_>>().join("\n");
3998
3999        let actual = pretty_format_batches(batches).unwrap().to_string();
4000        assert_eq!(actual, expected);
4001
4002        // Write data
4003        let file = tempfile::tempfile().unwrap();
4004        let props = WriterProperties::builder()
4005            .set_max_row_group_row_count(Some(6))
4006            .build();
4007
4008        let mut writer =
4009            ArrowWriter::try_new(file.try_clone().unwrap(), schema, Some(props)).unwrap();
4010
4011        for batch in batches {
4012            writer.write(batch).unwrap();
4013        }
4014        writer.close().unwrap();
4015
4016        // Read Data
4017        // Should have written entire first batch and first row of second to the first row group
4018        // leaving a single row in the second row group
4019
4020        let builder = ParquetRecordBatchReaderBuilder::try_new(file).unwrap();
4021        assert_eq!(&row_group_sizes(builder.metadata()), &[6, 1]);
4022
4023        let batches = builder
4024            .with_batch_size(2)
4025            .build()
4026            .unwrap()
4027            .collect::<ArrowResult<Vec<_>>>()
4028            .unwrap();
4029
4030        assert_eq!(batches.len(), 4);
4031        let batch_counts: Vec<_> = batches.iter().map(|x| x.num_rows()).collect();
4032        assert_eq!(&batch_counts, &[2, 2, 2, 1]);
4033
4034        let actual = pretty_format_batches(&batches).unwrap().to_string();
4035        assert_eq!(actual, expected);
4036    }
4037
4038    #[test]
4039    fn test_arrow_writer_metadata() {
4040        let batch_schema = Schema::new(vec![Field::new("int32", DataType::Int32, false)]);
4041        let file_schema = batch_schema.clone().with_metadata([("foo", "bar")]);
4042
4043        let batch = RecordBatch::try_new(
4044            Arc::new(batch_schema),
4045            vec![Arc::new(Int32Array::from(vec![1, 2, 3, 4])) as _],
4046        )
4047        .unwrap();
4048
4049        let mut buf = Vec::with_capacity(1024);
4050        let mut writer = ArrowWriter::try_new(&mut buf, Arc::new(file_schema), None).unwrap();
4051        writer.write(&batch).unwrap();
4052        writer.close().unwrap();
4053    }
4054
4055    #[test]
4056    fn in_progress_accounting() {
4057        // define schema
4058        let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
4059
4060        // create some data
4061        let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
4062
4063        // build a record batch
4064        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(a)]).unwrap();
4065
4066        let mut writer = ArrowWriter::try_new(vec![], batch.schema(), None).unwrap();
4067
4068        // starts empty
4069        assert_eq!(writer.in_progress_size(), 0);
4070        assert_eq!(writer.in_progress_rows(), 0);
4071        assert_eq!(writer.memory_size(), 0);
4072        assert_eq!(writer.bytes_written(), 4); // Initial header
4073        writer.write(&batch).unwrap();
4074
4075        // updated on write
4076        let initial_size = writer.in_progress_size();
4077        assert!(initial_size > 0);
4078        assert_eq!(writer.in_progress_rows(), 5);
4079        let initial_memory = writer.memory_size();
4080        assert!(initial_memory > 0);
4081        // memory estimate is larger than estimated encoded size
4082        assert!(
4083            initial_size <= initial_memory,
4084            "{initial_size} <= {initial_memory}"
4085        );
4086
4087        // updated on second write
4088        writer.write(&batch).unwrap();
4089        assert!(writer.in_progress_size() > initial_size);
4090        assert_eq!(writer.in_progress_rows(), 10);
4091        assert!(writer.memory_size() > initial_memory);
4092        assert!(
4093            writer.in_progress_size() <= writer.memory_size(),
4094            "in_progress_size {} <= memory_size {}",
4095            writer.in_progress_size(),
4096            writer.memory_size()
4097        );
4098
4099        // in progress tracking is cleared, but the overall data written is updated
4100        let pre_flush_bytes_written = writer.bytes_written();
4101        writer.flush().unwrap();
4102        assert_eq!(writer.in_progress_size(), 0);
4103        assert_eq!(writer.memory_size(), 0);
4104        assert!(writer.bytes_written() > pre_flush_bytes_written);
4105
4106        writer.close().unwrap();
4107    }
4108
4109    #[test]
4110    fn test_writer_all_null() {
4111        let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
4112        let b = Int32Array::new(vec![0; 5].into(), Some(NullBuffer::new_null(5)));
4113        let batch = RecordBatch::try_from_iter(vec![
4114            ("a", Arc::new(a) as ArrayRef),
4115            ("b", Arc::new(b) as ArrayRef),
4116        ])
4117        .unwrap();
4118
4119        let mut buf = Vec::with_capacity(1024);
4120        let mut writer = ArrowWriter::try_new(&mut buf, batch.schema(), None).unwrap();
4121        writer.write(&batch).unwrap();
4122        writer.close().unwrap();
4123
4124        let bytes = Bytes::from(buf);
4125        let options = ReadOptionsBuilder::new().with_page_index().build();
4126        let reader = SerializedFileReader::new_with_options(bytes, options).unwrap();
4127        let index = reader.metadata().page_index().unwrap();
4128
4129        assert_eq!(index.num_data_pages(0, 0), Some(1)); // 1 page
4130        assert_eq!(index.num_data_pages(0, 1), Some(1)); // 1 page
4131    }
4132
4133    #[test]
4134    fn test_disabled_statistics_with_page() {
4135        let file_schema = Schema::new(vec![
4136            Field::new("a", DataType::Utf8, true),
4137            Field::new("b", DataType::Utf8, true),
4138        ]);
4139        let file_schema = Arc::new(file_schema);
4140
4141        let batch = RecordBatch::try_new(
4142            file_schema.clone(),
4143            vec![
4144                Arc::new(StringArray::from(vec!["a", "b", "c", "d"])) as _,
4145                Arc::new(StringArray::from(vec!["w", "x", "y", "z"])) as _,
4146            ],
4147        )
4148        .unwrap();
4149
4150        let props = WriterProperties::builder()
4151            .set_statistics_enabled(EnabledStatistics::None)
4152            .set_column_statistics_enabled("a".into(), EnabledStatistics::Page)
4153            .build();
4154
4155        let mut buf = Vec::with_capacity(1024);
4156        let mut writer = ArrowWriter::try_new(&mut buf, file_schema.clone(), Some(props)).unwrap();
4157        writer.write(&batch).unwrap();
4158
4159        let metadata = writer.close().unwrap();
4160        assert_eq!(metadata.num_row_groups(), 1);
4161        let row_group = metadata.row_group(0);
4162        assert_eq!(row_group.num_columns(), 2);
4163        // Column "a" has both offset and column index, as requested
4164        assert!(row_group.column(0).offset_index_offset().is_some());
4165        assert!(row_group.column(0).column_index_offset().is_some());
4166        // Column "b" should only have offset index
4167        assert!(row_group.column(1).offset_index_offset().is_some());
4168        assert!(row_group.column(1).column_index_offset().is_none());
4169
4170        let options = ReadOptionsBuilder::new().with_page_index().build();
4171        let reader = SerializedFileReader::new_with_options(Bytes::from(buf), options).unwrap();
4172
4173        let row_group = reader.get_row_group(0).unwrap();
4174        let a_col = row_group.metadata().column(0);
4175        let b_col = row_group.metadata().column(1);
4176
4177        // Column chunk of column "a" should have chunk level statistics
4178        if let Statistics::ByteArray(byte_array_stats) = a_col.statistics().unwrap() {
4179            let min = byte_array_stats.min_opt().unwrap();
4180            let max = byte_array_stats.max_opt().unwrap();
4181
4182            assert_eq!(min.as_bytes(), b"a");
4183            assert_eq!(max.as_bytes(), b"d");
4184        } else {
4185            panic!("expecting Statistics::ByteArray");
4186        }
4187
4188        // The column chunk for column "b" shouldn't have statistics
4189        assert!(b_col.statistics().is_none());
4190
4191        let page_index = reader.metadata().page_index().unwrap();
4192
4193        let a_idx = page_index.column_index(0, 0);
4194        assert!(
4195            matches!(a_idx, Some(ColumnIndexMetaData::BYTE_ARRAY(_))),
4196            "{a_idx:?}"
4197        );
4198        let b_idx = page_index.column_index(0, 1);
4199        assert!(b_idx.is_none(), "{b_idx:?}");
4200    }
4201
4202    #[test]
4203    fn test_disabled_statistics_with_chunk() {
4204        let file_schema = Schema::new(vec![
4205            Field::new("a", DataType::Utf8, true),
4206            Field::new("b", DataType::Utf8, true),
4207        ]);
4208        let file_schema = Arc::new(file_schema);
4209
4210        let batch = RecordBatch::try_new(
4211            file_schema.clone(),
4212            vec![
4213                Arc::new(StringArray::from(vec!["a", "b", "c", "d"])) as _,
4214                Arc::new(StringArray::from(vec!["w", "x", "y", "z"])) as _,
4215            ],
4216        )
4217        .unwrap();
4218
4219        let props = WriterProperties::builder()
4220            .set_statistics_enabled(EnabledStatistics::None)
4221            .set_column_statistics_enabled("a".into(), EnabledStatistics::Chunk)
4222            .build();
4223
4224        let mut buf = Vec::with_capacity(1024);
4225        let mut writer = ArrowWriter::try_new(&mut buf, file_schema.clone(), Some(props)).unwrap();
4226        writer.write(&batch).unwrap();
4227
4228        let metadata = writer.close().unwrap();
4229        assert_eq!(metadata.num_row_groups(), 1);
4230        let row_group = metadata.row_group(0);
4231        assert_eq!(row_group.num_columns(), 2);
4232        // Column "a" should only have offset index
4233        assert!(row_group.column(0).offset_index_offset().is_some());
4234        assert!(row_group.column(0).column_index_offset().is_none());
4235        // Column "b" should only have offset index
4236        assert!(row_group.column(1).offset_index_offset().is_some());
4237        assert!(row_group.column(1).column_index_offset().is_none());
4238
4239        let options = ReadOptionsBuilder::new().with_page_index().build();
4240        let reader = SerializedFileReader::new_with_options(Bytes::from(buf), options).unwrap();
4241
4242        let row_group = reader.get_row_group(0).unwrap();
4243        let a_col = row_group.metadata().column(0);
4244        let b_col = row_group.metadata().column(1);
4245
4246        // Column chunk of column "a" should have chunk level statistics
4247        if let Statistics::ByteArray(byte_array_stats) = a_col.statistics().unwrap() {
4248            let min = byte_array_stats.min_opt().unwrap();
4249            let max = byte_array_stats.max_opt().unwrap();
4250
4251            assert_eq!(min.as_bytes(), b"a");
4252            assert_eq!(max.as_bytes(), b"d");
4253        } else {
4254            panic!("expecting Statistics::ByteArray");
4255        }
4256
4257        // The column chunk for column "b"  shouldn't have statistics
4258        assert!(b_col.statistics().is_none());
4259
4260        let page_index = reader.metadata().page_index().unwrap();
4261
4262        let a_idx = page_index.column_index(0, 0);
4263        assert!(a_idx.is_none(), "{a_idx:?}");
4264        let b_idx = page_index.column_index(0, 1);
4265        assert!(b_idx.is_none(), "{b_idx:?}");
4266    }
4267
4268    #[test]
4269    fn test_arrow_writer_skip_metadata() {
4270        let batch_schema = Schema::new(vec![Field::new("int32", DataType::Int32, false)]);
4271        let file_schema = Arc::new(batch_schema.clone());
4272
4273        let batch = RecordBatch::try_new(
4274            Arc::new(batch_schema),
4275            vec![Arc::new(Int32Array::from(vec![1, 2, 3, 4])) as _],
4276        )
4277        .unwrap();
4278        let skip_options = ArrowWriterOptions::new().with_skip_arrow_metadata(true);
4279
4280        let mut buf = Vec::with_capacity(1024);
4281        let mut writer =
4282            ArrowWriter::try_new_with_options(&mut buf, file_schema.clone(), skip_options).unwrap();
4283        writer.write(&batch).unwrap();
4284        writer.close().unwrap();
4285
4286        let bytes = Bytes::from(buf);
4287        let reader_builder = ParquetRecordBatchReaderBuilder::try_new(bytes).unwrap();
4288        assert_eq!(file_schema, *reader_builder.schema());
4289        if let Some(key_value_metadata) = reader_builder
4290            .metadata()
4291            .file_metadata()
4292            .key_value_metadata()
4293        {
4294            assert!(
4295                !key_value_metadata
4296                    .iter()
4297                    .any(|kv| kv.key.as_str() == ARROW_SCHEMA_META_KEY)
4298            );
4299        }
4300    }
4301
4302    #[test]
4303    fn test_arrow_writer_skip_path_in_schema() {
4304        let batch_schema = Schema::new(vec![Field::new("int32", DataType::Int32, false)]);
4305        let file_schema = Arc::new(batch_schema.clone());
4306
4307        let batch = RecordBatch::try_new(
4308            Arc::new(batch_schema),
4309            vec![Arc::new(Int32Array::from(vec![1, 2, 3, 4])) as _],
4310        )
4311        .unwrap();
4312
4313        // default options should still write path_in_schema
4314        let skip_options = ArrowWriterOptions::new();
4315
4316        let mut buf = Vec::with_capacity(1024);
4317        let mut writer =
4318            ArrowWriter::try_new_with_options(&mut buf, file_schema.clone(), skip_options).unwrap();
4319        writer.write(&batch).unwrap();
4320        writer.close().unwrap();
4321
4322        // override to not write path_in_schema
4323        let skip_options = ArrowWriterOptions::new().with_properties(
4324            WriterProperties::builder()
4325                .set_write_path_in_schema(false)
4326                .build(),
4327        );
4328
4329        let mut buf2 = Vec::with_capacity(1024);
4330        let mut writer =
4331            ArrowWriter::try_new_with_options(&mut buf2, file_schema.clone(), skip_options)
4332                .unwrap();
4333        writer.write(&batch).unwrap();
4334        writer.close().unwrap();
4335
4336        // buf2 should be a bit smaller due to lack of path_in_schema
4337        assert!(buf.len() > buf2.len());
4338    }
4339
4340    #[test]
4341    fn mismatched_schemas() {
4342        let batch_schema = Schema::new(vec![Field::new("count", DataType::Int32, false)]);
4343        let file_schema = Arc::new(Schema::new(vec![Field::new(
4344            "temperature",
4345            DataType::Float64,
4346            false,
4347        )]));
4348
4349        let batch = RecordBatch::try_new(
4350            Arc::new(batch_schema),
4351            vec![Arc::new(Int32Array::from(vec![1, 2, 3, 4])) as _],
4352        )
4353        .unwrap();
4354
4355        let mut buf = Vec::with_capacity(1024);
4356        let mut writer = ArrowWriter::try_new(&mut buf, file_schema.clone(), None).unwrap();
4357
4358        let err = writer.write(&batch).unwrap_err().to_string();
4359        assert_eq!(
4360            err,
4361            "Arrow: Incompatible type. Field 'temperature' has type Float64, array has type Int32"
4362        );
4363    }
4364
4365    #[test]
4366    fn test_page_stats_not_written_by_default() {
4367        let string_field = Field::new("a", DataType::Utf8, false);
4368        let schema = Schema::new(vec![string_field]);
4369        let raw_string_values = vec!["Blart Versenwald III"];
4370        let string_values = StringArray::from(raw_string_values.clone());
4371        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(string_values)]).unwrap();
4372
4373        let props = WriterProperties::builder()
4374            .set_statistics_enabled(EnabledStatistics::Page)
4375            .set_dictionary_enabled(false)
4376            .set_encoding(Encoding::PLAIN)
4377            .set_compression(crate::basic::Compression::UNCOMPRESSED)
4378            .build();
4379
4380        let file = roundtrip_opts(&batch, props);
4381
4382        // read file and decode page headers
4383        // Note: use the thrift API as there is no Rust API to access the statistics in the page headers
4384
4385        // decode first page header
4386        let first_page = &file[4..];
4387        let mut prot = ThriftSliceInputProtocol::new(first_page);
4388        let hdr = PageHeader::read_thrift(&mut prot).unwrap();
4389        let stats = hdr.data_page_header.unwrap().statistics;
4390
4391        assert!(stats.is_none());
4392    }
4393
4394    #[test]
4395    fn test_page_stats_when_enabled() {
4396        let string_field = Field::new("a", DataType::Utf8, false);
4397        let schema = Schema::new(vec![string_field]);
4398        let raw_string_values = vec!["Blart Versenwald III", "Andrew Lamb"];
4399        let string_values = StringArray::from(raw_string_values.clone());
4400        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(string_values)]).unwrap();
4401
4402        let props = WriterProperties::builder()
4403            .set_statistics_enabled(EnabledStatistics::Page)
4404            .set_dictionary_enabled(false)
4405            .set_encoding(Encoding::PLAIN)
4406            .set_write_page_header_statistics(true)
4407            .set_compression(crate::basic::Compression::UNCOMPRESSED)
4408            .build();
4409
4410        let file = roundtrip_opts(&batch, props);
4411
4412        // read file and decode page headers
4413        // Note: use the thrift API as there is no Rust API to access the statistics in the page headers
4414
4415        // decode first page header
4416        let first_page = &file[4..];
4417        let mut prot = ThriftSliceInputProtocol::new(first_page);
4418        let hdr = PageHeader::read_thrift(&mut prot).unwrap();
4419        let stats = hdr.data_page_header.unwrap().statistics;
4420
4421        let stats = stats.unwrap();
4422        // check that min/max were actually written to the page
4423        assert!(stats.is_max_value_exact.unwrap());
4424        assert!(stats.is_min_value_exact.unwrap());
4425        assert_eq!(stats.max_value.unwrap(), b"Blart Versenwald III");
4426        assert_eq!(stats.min_value.unwrap(), b"Andrew Lamb");
4427    }
4428
4429    #[test]
4430    fn test_page_stats_truncation() {
4431        let string_field = Field::new("a", DataType::Utf8, false);
4432        let binary_field = Field::new("b", DataType::Binary, false);
4433        let schema = Schema::new(vec![string_field, binary_field]);
4434
4435        let raw_string_values = vec!["Blart Versenwald III"];
4436        let raw_binary_values = [b"Blart Versenwald III".to_vec()];
4437        let raw_binary_value_refs = raw_binary_values
4438            .iter()
4439            .map(|x| x.as_slice())
4440            .collect::<Vec<_>>();
4441
4442        let string_values = StringArray::from(raw_string_values.clone());
4443        let binary_values = BinaryArray::from(raw_binary_value_refs);
4444        let batch = RecordBatch::try_new(
4445            Arc::new(schema),
4446            vec![Arc::new(string_values), Arc::new(binary_values)],
4447        )
4448        .unwrap();
4449
4450        let props = WriterProperties::builder()
4451            .set_statistics_truncate_length(Some(2))
4452            .set_dictionary_enabled(false)
4453            .set_encoding(Encoding::PLAIN)
4454            .set_write_page_header_statistics(true)
4455            .set_compression(crate::basic::Compression::UNCOMPRESSED)
4456            .build();
4457
4458        let file = roundtrip_opts(&batch, props);
4459
4460        // read file and decode page headers
4461        // Note: use the thrift API as there is no Rust API to access the statistics in the page headers
4462
4463        // decode first page header
4464        let first_page = &file[4..];
4465        let mut prot = ThriftSliceInputProtocol::new(first_page);
4466        let hdr = PageHeader::read_thrift(&mut prot).unwrap();
4467        let stats = hdr.data_page_header.unwrap().statistics;
4468        assert!(stats.is_some());
4469        let stats = stats.unwrap();
4470        // check that min/max were properly truncated
4471        assert!(!stats.is_max_value_exact.unwrap());
4472        assert!(!stats.is_min_value_exact.unwrap());
4473        assert_eq!(stats.max_value.unwrap(), b"Bm");
4474        assert_eq!(stats.min_value.unwrap(), b"Bl");
4475
4476        // check second page now
4477        let second_page = &prot.as_slice()[hdr.compressed_page_size as usize..];
4478        let mut prot = ThriftSliceInputProtocol::new(second_page);
4479        let hdr = PageHeader::read_thrift(&mut prot).unwrap();
4480        let stats = hdr.data_page_header.unwrap().statistics;
4481        assert!(stats.is_some());
4482        let stats = stats.unwrap();
4483        // check that min/max were properly truncated
4484        assert!(!stats.is_max_value_exact.unwrap());
4485        assert!(!stats.is_min_value_exact.unwrap());
4486        assert_eq!(stats.max_value.unwrap(), b"Bm");
4487        assert_eq!(stats.min_value.unwrap(), b"Bl");
4488    }
4489
4490    #[test]
4491    fn test_page_encoding_statistics_roundtrip() {
4492        let batch_schema = Schema::new(vec![Field::new(
4493            "int32",
4494            arrow_schema::DataType::Int32,
4495            false,
4496        )]);
4497
4498        let batch = RecordBatch::try_new(
4499            Arc::new(batch_schema.clone()),
4500            vec![Arc::new(Int32Array::from(vec![1, 2, 3, 4])) as _],
4501        )
4502        .unwrap();
4503
4504        let mut file: File = tempfile::tempfile().unwrap();
4505        let mut writer = ArrowWriter::try_new(&mut file, Arc::new(batch_schema), None).unwrap();
4506        writer.write(&batch).unwrap();
4507        let file_metadata = writer.close().unwrap();
4508
4509        assert_eq!(file_metadata.num_row_groups(), 1);
4510        assert_eq!(file_metadata.row_group(0).num_columns(), 1);
4511        assert!(
4512            file_metadata
4513                .row_group(0)
4514                .column(0)
4515                .page_encoding_stats()
4516                .is_some()
4517        );
4518        let chunk_page_stats = file_metadata
4519            .row_group(0)
4520            .column(0)
4521            .page_encoding_stats()
4522            .unwrap();
4523
4524        // check that the read metadata is also correct
4525        let options = ReadOptionsBuilder::new()
4526            .with_page_index()
4527            .with_encoding_stats_as_mask(false)
4528            .build();
4529        let reader = SerializedFileReader::new_with_options(file, options).unwrap();
4530
4531        let rowgroup = reader.get_row_group(0).expect("row group missing");
4532        assert_eq!(rowgroup.num_columns(), 1);
4533        let column = rowgroup.metadata().column(0);
4534        assert!(column.page_encoding_stats().is_some());
4535        let file_page_stats = column.page_encoding_stats().unwrap();
4536        assert_eq!(chunk_page_stats, file_page_stats);
4537    }
4538
4539    #[test]
4540    #[cfg_attr(miri, ignore)] // Takes too long
4541    fn test_different_dict_page_size_limit() {
4542        let array = Arc::new(Int64Array::from_iter(0..1024 * 1024));
4543        let schema = Arc::new(Schema::new(vec![
4544            Field::new("col0", arrow_schema::DataType::Int64, false),
4545            Field::new("col1", arrow_schema::DataType::Int64, false),
4546        ]));
4547        let batch =
4548            arrow_array::RecordBatch::try_new(schema.clone(), vec![array.clone(), array]).unwrap();
4549
4550        let props = WriterProperties::builder()
4551            .set_dictionary_page_size_limit(1024 * 1024)
4552            .set_column_dictionary_page_size_limit(ColumnPath::from("col1"), 1024 * 1024 * 4)
4553            .build();
4554        let mut writer = ArrowWriter::try_new(Vec::new(), schema, Some(props)).unwrap();
4555        writer.write(&batch).unwrap();
4556        let data = Bytes::from(writer.into_inner().unwrap());
4557
4558        let mut metadata = ParquetMetaDataReader::new();
4559        metadata.try_parse(&data).unwrap();
4560        let metadata = metadata.finish().unwrap();
4561        let col0_meta = metadata.row_group(0).column(0);
4562        let col1_meta = metadata.row_group(0).column(1);
4563
4564        let get_dict_page_size = move |meta: &ColumnChunkMetaData| {
4565            let mut reader =
4566                SerializedPageReader::new(Arc::new(data.clone()), meta, 0, None).unwrap();
4567            let page = reader.get_next_page().unwrap().unwrap();
4568            match page {
4569                Page::DictionaryPage { buf, .. } => buf.len(),
4570                _ => panic!("expected DictionaryPage"),
4571            }
4572        };
4573
4574        assert_eq!(get_dict_page_size(col0_meta), 1024 * 1024);
4575        assert_eq!(get_dict_page_size(col1_meta), 1024 * 1024 * 4);
4576    }
4577
4578    #[test]
4579    #[cfg_attr(miri, ignore)] // Takes too long
4580    fn test_arrow_writer_granular_mode_roundtrip() {
4581        // Granular mode subdivides chunks and writes more pages than the
4582        // default batched path. Make sure the data we write back is
4583        // bit-identical to what went in — page-count assertions elsewhere
4584        // only prove pages were cut, not that the encoded data is correct.
4585        //
4586        // Mix value sizes so that the cumulative-byte-budget cutoff
4587        // lands mid-chunk, exercising both batched and granular paths
4588        // within the same `write_batch_internal` call.
4589        let small = "tiny".to_string();
4590        let big = "x".repeat(64 * 1024);
4591        let strings: Vec<String> = (0..256)
4592            .map(|i| {
4593                if i % 16 == 0 {
4594                    big.clone()
4595                } else {
4596                    small.clone()
4597                }
4598            })
4599            .collect();
4600
4601        let schema = Arc::new(Schema::new(vec![Field::new(
4602            "col",
4603            ArrowDataType::Utf8,
4604            false,
4605        )]));
4606        let batch = RecordBatch::try_new(
4607            schema.clone(),
4608            vec![Arc::new(StringArray::from(strings.clone())) as _],
4609        )
4610        .unwrap();
4611
4612        let props = WriterProperties::builder()
4613            .set_dictionary_enabled(false)
4614            .set_data_page_size_limit(16 * 1024)
4615            .build();
4616        let mut writer = ArrowWriter::try_new(Vec::new(), schema, Some(props)).unwrap();
4617        writer.write(&batch).unwrap();
4618        let data = Bytes::from(writer.into_inner().unwrap());
4619
4620        let mut reader = ParquetRecordBatchReader::try_new(data, 1024).unwrap();
4621        let read = reader.next().unwrap().unwrap();
4622        assert!(reader.next().is_none(), "expected one batch");
4623        let col = read
4624            .column(0)
4625            .as_any()
4626            .downcast_ref::<StringArray>()
4627            .unwrap();
4628        assert_eq!(col.len(), strings.len());
4629        for (i, expected) in strings.iter().enumerate() {
4630            assert_eq!(
4631                col.value(i),
4632                expected.as_str(),
4633                "value mismatch at index {i}"
4634            );
4635        }
4636    }
4637
4638    #[test]
4639    fn test_arrow_writer_all_null_string_column() {
4640        // The `LevelDataRef::value_count` Uniform branch with
4641        // `value != max_def` (entirely-null chunk) must return 0 so the
4642        // sub-batch sizer short-circuits to batch mode without trying
4643        // to estimate byte budgets for non-existent values.
4644        let num_rows = 1024;
4645        let schema = Arc::new(Schema::new(vec![Field::new(
4646            "col",
4647            ArrowDataType::Utf8,
4648            true,
4649        )]));
4650        let nulls: Vec<Option<&str>> = vec![None; num_rows];
4651        let batch = RecordBatch::try_new(
4652            schema.clone(),
4653            vec![Arc::new(StringArray::from(nulls)) as _],
4654        )
4655        .unwrap();
4656
4657        let props = WriterProperties::builder()
4658            .set_dictionary_enabled(false)
4659            .set_data_page_size_limit(16 * 1024)
4660            .build();
4661        let mut writer = ArrowWriter::try_new(Vec::new(), schema, Some(props)).unwrap();
4662        writer.write(&batch).unwrap();
4663        let data = Bytes::from(writer.into_inner().unwrap());
4664
4665        // Re-parse the file: row group has one column, every row is
4666        // null, all data pages report `num_rows / page_count` rows.
4667        let mut metadata = ParquetMetaDataReader::new();
4668        metadata.try_parse(&data).unwrap();
4669        let metadata = metadata.finish().unwrap();
4670        let row_group = metadata.row_group(0);
4671        let col_meta = row_group.column(0);
4672        assert_eq!(row_group.num_rows() as usize, num_rows);
4673        // Statistics record `null_count = num_rows` — proves every value
4674        // was written as null.
4675        if let Some(stats) = col_meta.statistics() {
4676            assert_eq!(
4677                stats.null_count_opt().unwrap_or(0) as usize,
4678                num_rows,
4679                "expected all-null column to report null_count = num_rows"
4680            );
4681        }
4682
4683        let mut reader =
4684            SerializedPageReader::new(Arc::new(data.clone()), col_meta, num_rows, None).unwrap();
4685        let mut total_values = 0u32;
4686        while let Some(page) = reader.get_next_page().unwrap() {
4687            if matches!(page, Page::DataPage { .. } | Page::DataPageV2 { .. }) {
4688                total_values += page.num_values();
4689            }
4690        }
4691        assert_eq!(
4692            total_values as usize, num_rows,
4693            "expected every level position to be represented in some page"
4694        );
4695    }
4696
4697    struct WriteBatchesShape {
4698        num_batches: usize,
4699        rows_per_batch: usize,
4700        row_size: usize,
4701    }
4702
4703    /// Helper function to write batches with the provided `WriteBatchesShape` into an `ArrowWriter`
4704    fn write_batches(
4705        WriteBatchesShape {
4706            num_batches,
4707            rows_per_batch,
4708            row_size,
4709        }: WriteBatchesShape,
4710        props: WriterProperties,
4711    ) -> ParquetRecordBatchReaderBuilder<File> {
4712        let schema = Arc::new(Schema::new(vec![Field::new(
4713            "str",
4714            ArrowDataType::Utf8,
4715            false,
4716        )]));
4717        let file = tempfile::tempfile().unwrap();
4718        let mut writer =
4719            ArrowWriter::try_new(file.try_clone().unwrap(), schema.clone(), Some(props)).unwrap();
4720
4721        for batch_idx in 0..num_batches {
4722            let strings: Vec<String> = (0..rows_per_batch)
4723                .map(|i| format!("{:0>width$}", batch_idx * 10 + i, width = row_size))
4724                .collect();
4725            let array = StringArray::from(strings);
4726            let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(array)]).unwrap();
4727            writer.write(&batch).unwrap();
4728        }
4729        writer.close().unwrap();
4730        ParquetRecordBatchReaderBuilder::try_new(file).unwrap()
4731    }
4732
4733    #[test]
4734    // When both limits are None, all data should go into a single row group
4735    fn test_row_group_limit_none_writes_single_row_group() {
4736        let props = WriterProperties::builder()
4737            .set_max_row_group_row_count(None)
4738            .set_max_row_group_bytes(None)
4739            .build();
4740
4741        let builder = write_batches(
4742            WriteBatchesShape {
4743                num_batches: 1,
4744                rows_per_batch: 1000,
4745                row_size: 4,
4746            },
4747            props,
4748        );
4749
4750        assert_eq!(
4751            &row_group_sizes(builder.metadata()),
4752            &[1000],
4753            "With no limits, all rows should be in a single row group"
4754        );
4755    }
4756
4757    #[test]
4758    // When only max_row_group_size is set, respect the row limit
4759    fn test_row_group_limit_rows_only() {
4760        let props = WriterProperties::builder()
4761            .set_max_row_group_row_count(Some(300))
4762            .set_max_row_group_bytes(None)
4763            .build();
4764
4765        let builder = write_batches(
4766            WriteBatchesShape {
4767                num_batches: 1,
4768                rows_per_batch: 1000,
4769                row_size: 4,
4770            },
4771            props,
4772        );
4773
4774        assert_eq!(
4775            &row_group_sizes(builder.metadata()),
4776            &[300, 300, 300, 100],
4777            "Row groups should be split by row count"
4778        );
4779    }
4780
4781    #[test]
4782    #[cfg_attr(miri, ignore)] // Takes too long
4783    // A row limit far smaller than the batch splits it many times over; the split must not
4784    // consume stack proportional to the number of row groups.
4785    fn test_row_group_limit_rows_only_many_splits() {
4786        let props = WriterProperties::builder()
4787            .set_max_row_group_row_count(Some(1))
4788            .set_max_row_group_bytes(None)
4789            .build();
4790
4791        let rows = 50_000;
4792        let builder = write_batches(
4793            WriteBatchesShape {
4794                num_batches: 1,
4795                rows_per_batch: rows,
4796                row_size: 4,
4797            },
4798            props,
4799        );
4800
4801        let sizes = row_group_sizes(builder.metadata());
4802        assert_eq!(sizes.len(), rows, "Every row should get its own row group");
4803        assert_eq!(
4804            sizes.iter().sum::<i64>(),
4805            rows as i64,
4806            "Total rows should be preserved"
4807        );
4808    }
4809
4810    #[test]
4811    // When only max_row_group_bytes is set, respect the byte limit
4812    fn test_row_group_limit_bytes_only() {
4813        let props = WriterProperties::builder()
4814            .set_max_row_group_row_count(None)
4815            // Set byte limit to approximately fit ~30 rows worth of data (~100 bytes each)
4816            .set_max_row_group_bytes(Some(3500))
4817            .build();
4818
4819        let builder = write_batches(
4820            WriteBatchesShape {
4821                num_batches: 10,
4822                rows_per_batch: 10,
4823                row_size: 100,
4824            },
4825            props,
4826        );
4827
4828        let sizes = row_group_sizes(builder.metadata());
4829
4830        assert!(
4831            sizes.len() > 1,
4832            "Should have multiple row groups due to byte limit, got {sizes:?}",
4833        );
4834
4835        let total_rows: i64 = sizes.iter().sum();
4836        assert_eq!(total_rows, 100, "Total rows should be preserved");
4837    }
4838
4839    #[test]
4840    // If an in-progress row group is already oversized, it should be flushed before writing more.
4841    fn test_row_group_limit_bytes_flushes_when_current_group_already_too_large() {
4842        let schema = Arc::new(Schema::new(vec![Field::new(
4843            "str",
4844            ArrowDataType::Utf8,
4845            false,
4846        )]));
4847        let file = tempfile::tempfile().unwrap();
4848
4849        // Start with no byte limit so we can intentionally build an oversized in-progress row group.
4850        let props = WriterProperties::builder()
4851            .set_max_row_group_row_count(None)
4852            .set_max_row_group_bytes(None)
4853            .build();
4854        let mut writer =
4855            ArrowWriter::try_new(file.try_clone().unwrap(), schema.clone(), Some(props)).unwrap();
4856
4857        let first_array = StringArray::from(
4858            (0..10)
4859                .map(|i| format!("{i:0>100}"))
4860                .collect::<Vec<String>>(),
4861        );
4862        let first_batch =
4863            RecordBatch::try_new(schema.clone(), vec![Arc::new(first_array)]).unwrap();
4864        writer.write(&first_batch).unwrap();
4865        assert_eq!(writer.in_progress_rows(), 10);
4866
4867        // Tighten the limit below the current in-progress bytes to exercise:
4868        // `if current_bytes >= max_bytes { self.flush()?; ... }`
4869        writer.max_row_group_bytes = Some(1);
4870
4871        let second_array = StringArray::from(vec!["x".to_string()]);
4872        let second_batch =
4873            RecordBatch::try_new(schema.clone(), vec![Arc::new(second_array)]).unwrap();
4874        writer.write(&second_batch).unwrap();
4875        writer.close().unwrap();
4876        let builder = ParquetRecordBatchReaderBuilder::try_new(file).unwrap();
4877
4878        assert_eq!(
4879            &row_group_sizes(builder.metadata()),
4880            &[10, 1],
4881            "The second write should flush an oversized in-progress row group first",
4882        );
4883    }
4884
4885    #[test]
4886    // When both limits are set, the row limit triggers first
4887    fn test_row_group_limit_both_row_wins_single_batch() {
4888        let props = WriterProperties::builder()
4889            .set_max_row_group_row_count(Some(200)) // Will trigger at 200 rows
4890            .set_max_row_group_bytes(Some(1024 * 1024)) // 1MB - won't trigger for small int data
4891            .build();
4892
4893        let builder = write_batches(
4894            WriteBatchesShape {
4895                num_batches: 1,
4896                row_size: 4,
4897                rows_per_batch: 1000,
4898            },
4899            props,
4900        );
4901
4902        assert_eq!(
4903            &row_group_sizes(builder.metadata()),
4904            &[200, 200, 200, 200, 200],
4905            "Row limit should trigger before byte limit"
4906        );
4907    }
4908
4909    #[test]
4910    // When both limits are set, the row limit triggers first
4911    fn test_row_group_limit_both_row_wins_multiple_batches() {
4912        let props = WriterProperties::builder()
4913            .set_max_row_group_row_count(Some(5)) // Will trigger every 5 rows
4914            .set_max_row_group_bytes(Some(9999)) // Won't trigger
4915            .build();
4916
4917        let builder = write_batches(
4918            WriteBatchesShape {
4919                num_batches: 10,
4920                rows_per_batch: 10,
4921                row_size: 100,
4922            },
4923            props,
4924        );
4925
4926        assert_eq!(
4927            &row_group_sizes(builder.metadata()),
4928            &[5; 20],
4929            "Row limit should trigger before byte limit"
4930        );
4931    }
4932
4933    #[test]
4934    // When both limits are set, the byte limit triggers first
4935    fn test_row_group_limit_both_bytes_wins() {
4936        let props = WriterProperties::builder()
4937            .set_max_row_group_row_count(Some(1000)) // Won't trigger for 100 rows
4938            .set_max_row_group_bytes(Some(3500)) // Will trigger at ~30-35 rows
4939            .build();
4940
4941        let builder = write_batches(
4942            WriteBatchesShape {
4943                num_batches: 10,
4944                rows_per_batch: 10,
4945                row_size: 100,
4946            },
4947            props,
4948        );
4949
4950        let sizes = row_group_sizes(builder.metadata());
4951
4952        assert!(
4953            sizes.len() > 1,
4954            "Byte limit should trigger before row limit, got {sizes:?}",
4955        );
4956
4957        assert!(
4958            sizes.iter().all(|&s| s < 1000),
4959            "No row group should hit the row limit"
4960        );
4961
4962        let total_rows: i64 = sizes.iter().sum();
4963        assert_eq!(total_rows, 100, "Total rows should be preserved");
4964    }
4965
4966    #[test]
4967    // Both limits can apply to the same batch: the row limit trims it to 5 rows, and the
4968    // byte limit then trims those 5 down to 4.
4969    fn test_row_group_limit_both_apply_to_same_batch() {
4970        let props = WriterProperties::builder()
4971            .set_max_row_group_row_count(Some(15))
4972            .set_max_row_group_bytes(Some(1500))
4973            .build();
4974
4975        let builder = write_batches(
4976            WriteBatchesShape {
4977                num_batches: 2,
4978                rows_per_batch: 10,
4979                row_size: 100,
4980            },
4981            props,
4982        );
4983
4984        assert_eq!(
4985            &row_group_sizes(builder.metadata()),
4986            &[14, 6],
4987            "Byte limit should still apply to a batch the row limit already split"
4988        );
4989    }
4990
4991    #[test]
4992    // A batch far larger than the byte limit must be split even when it is the first one
4993    // written to a row group, where there are no buffered rows to estimate the row size from.
4994    fn test_row_group_limit_bytes_splits_first_batch() {
4995        let props = WriterProperties::builder()
4996            .set_max_row_group_row_count(None)
4997            .set_max_row_group_bytes(Some(3500))
4998            .build();
4999
5000        let builder = write_batches(
5001            WriteBatchesShape {
5002                num_batches: 3,
5003                rows_per_batch: 100,
5004                row_size: 100,
5005            },
5006            props,
5007        );
5008
5009        let sizes = row_group_sizes(builder.metadata());
5010        assert!(
5011            sizes.iter().all(|&s| s < 100),
5012            "No row group should hold a whole batch, got {sizes:?}",
5013        );
5014        assert_eq!(
5015            sizes.iter().sum::<i64>(),
5016            300,
5017            "Total rows should be preserved"
5018        );
5019        for row_group in builder.metadata().row_groups() {
5020            assert!(
5021                row_group.total_byte_size() <= 3500 + 100,
5022                "Row groups should stay within one row of the byte limit, got {}",
5023                row_group.total_byte_size(),
5024            );
5025        }
5026    }
5027
5028    #[test]
5029    fn arrow_column_chunk_close_mut_drops_column_index() {
5030        use crate::arrow::ArrowSchemaConverter;
5031        use crate::file::writer::SerializedFileWriter;
5032
5033        let schema = Arc::new(Schema::new(vec![Field::new("i", DataType::Int32, false)]));
5034        let props = Arc::new(
5035            WriterProperties::builder()
5036                .set_statistics_enabled(EnabledStatistics::Page)
5037                .build(),
5038        );
5039        let parquet_schema = ArrowSchemaConverter::new()
5040            .with_coerce_types(props.coerce_types())
5041            .convert(&schema)
5042            .unwrap();
5043
5044        let mut buf = Vec::with_capacity(1024);
5045        let mut writer =
5046            SerializedFileWriter::new(&mut buf, parquet_schema.root_schema_ptr(), props.clone())
5047                .unwrap();
5048
5049        let factory = ArrowRowGroupWriterFactory::new(&writer, Arc::clone(&schema));
5050        let mut col_writers = factory.create_column_writers(0).unwrap();
5051        let arr: ArrayRef = Arc::new(Int32Array::from_iter_values(0..64));
5052        for leaves in compute_leaves(schema.field(0), &arr).unwrap() {
5053            col_writers[0].write(&leaves).unwrap();
5054        }
5055        let mut chunk = col_writers.pop().unwrap().close().unwrap();
5056
5057        // Immutable accessor exposes the close result produced at close time.
5058        assert!(
5059            chunk.close().column_index.is_some(),
5060            "EnabledStatistics::Page should produce a column_index"
5061        );
5062
5063        // Mutable accessor lets callers drop the page-level index before append.
5064        chunk.close_mut().column_index = None;
5065        assert!(chunk.close().column_index.is_none());
5066
5067        let mut rg = writer.next_row_group().unwrap();
5068        chunk.append_to_row_group(&mut rg).unwrap();
5069        rg.close().unwrap();
5070        let file_meta = writer.close().unwrap();
5071
5072        // After dropping column_index, the resulting file records no column
5073        // index offset/length for this chunk.
5074        let cc = file_meta.row_group(0).column(0);
5075        assert!(cc.column_index_range().is_none());
5076    }
5077
5078    #[test]
5079    #[cfg_attr(miri, ignore)] // Takes too long
5080    fn test_number_distinct_values_exact_count() {
5081        // 50 distinct Int32 values repeated across 100k rows, with every 7th row null.
5082        // Nulls must not be counted as a distinct value.
5083        let cardinality = 50u32;
5084        let array: ArrayRef = Arc::new(Int32Array::from_iter((0..100_000u32).map(|i| {
5085            if i % 7 == 0 {
5086                None
5087            } else {
5088                Some((i % cardinality) as i32)
5089            }
5090        })));
5091        let schema = Arc::new(Schema::new(vec![Field::new("x", DataType::Int32, true)]));
5092        let batch = RecordBatch::try_new(schema, vec![array]).unwrap();
5093
5094        let props = WriterProperties::builder()
5095            .set_write_row_group_number_distinct_values(true)
5096            .build();
5097        let mut buf = Vec::new();
5098        let mut writer = ArrowWriter::try_new(&mut buf, batch.schema(), Some(props)).unwrap();
5099        writer.write(&batch).unwrap();
5100        let metadata = writer.close().unwrap();
5101
5102        let count = metadata
5103            .row_group(0)
5104            .column(0)
5105            .statistics()
5106            .and_then(|s| s.distinct_count_opt())
5107            .expect("distinct_count should be set");
5108        // Must equal cardinality exactly; nulls must not inflate the count.
5109        assert_eq!(count, cardinality as u64);
5110    }
5111
5112    #[test]
5113    fn test_number_distinct_values_view_types() {
5114        // 5 distinct values repeated across 30 rows, with every 4th row null.
5115        // Verifies Utf8View is counted correctly (BinaryView shares the same code path).
5116        let cardinality = 5u32;
5117        let distinct_strings = ["alpha", "beta", "gamma", "delta", "epsilon"];
5118
5119        let string_view_col: ArrayRef = Arc::new(StringViewArray::from_iter((0..30u32).map(|i| {
5120            if i % 4 == 0 {
5121                None
5122            } else {
5123                Some(distinct_strings[(i % cardinality) as usize])
5124            }
5125        })));
5126
5127        let schema = Arc::new(Schema::new(vec![Field::new(
5128            "string_view_col",
5129            DataType::Utf8View,
5130            true,
5131        )]));
5132        let batch = RecordBatch::try_new(schema, vec![string_view_col]).unwrap();
5133
5134        let props = WriterProperties::builder()
5135            .set_write_row_group_number_distinct_values(true)
5136            .build();
5137        let mut parquet_bytes = Vec::new();
5138        let mut writer =
5139            ArrowWriter::try_new(&mut parquet_bytes, batch.schema(), Some(props)).unwrap();
5140        writer.write(&batch).unwrap();
5141        let metadata = writer.close().unwrap();
5142
5143        let distinct_count = metadata
5144            .row_group(0)
5145            .column(0)
5146            .statistics()
5147            .and_then(|s| s.distinct_count_opt())
5148            .expect("distinct_count should be set for Utf8View column");
5149        assert_eq!(distinct_count, cardinality as u64);
5150    }
5151
5152    #[test]
5153    fn test_number_distinct_values_not_written_by_default() {
5154        let array: ArrayRef = Arc::new(Int32Array::from_iter_values(0..100));
5155        let schema = Arc::new(Schema::new(vec![Field::new("x", DataType::Int32, false)]));
5156        let batch = RecordBatch::try_new(schema, vec![array]).unwrap();
5157
5158        let mut buf = Vec::new();
5159        let mut writer = ArrowWriter::try_new(&mut buf, batch.schema(), None).unwrap();
5160        writer.write(&batch).unwrap();
5161        let metadata = writer.close().unwrap();
5162
5163        let count = metadata
5164            .row_group(0)
5165            .column(0)
5166            .statistics()
5167            .and_then(|s| s.distinct_count_opt());
5168        assert!(count.is_none());
5169    }
5170
5171    #[test]
5172    fn test_dictionary_ndv_single_batch() {
5173        // Dictionary array with 3 distinct string values repeated many times.
5174        // NDV must equal the number of distinct values in the dictionary (3),
5175        // not the number of rows.
5176        let keys = Int32Array::from(vec![0, 1, 2, 0, 1, 2, 0, 1, 2]);
5177        let values: ArrayRef = Arc::new(StringArray::from(vec!["cat", "dog", "bird"]));
5178        let dict: ArrayRef = Arc::new(DictionaryArray::<Int32Type>::try_new(keys, values).unwrap());
5179
5180        let schema = Arc::new(Schema::new(vec![Field::new(
5181            "x",
5182            DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
5183            false,
5184        )]));
5185        let batch = RecordBatch::try_new(schema, vec![dict]).unwrap();
5186
5187        let props = WriterProperties::builder()
5188            .set_write_row_group_number_distinct_values(true)
5189            .build();
5190        let mut buf = Vec::new();
5191        let mut writer = ArrowWriter::try_new(&mut buf, batch.schema(), Some(props)).unwrap();
5192        writer.write(&batch).unwrap();
5193        let metadata = writer.close().unwrap();
5194
5195        let count = metadata
5196            .row_group(0)
5197            .column(0)
5198            .statistics()
5199            .and_then(|s| s.distinct_count_opt())
5200            .expect("distinct_count should be set");
5201        assert_eq!(count, 3);
5202    }
5203
5204    #[test]
5205    fn test_dictionary_ndv_excludes_unreferenced_values() {
5206        // Keys only reference indices 0 and 1; value at index 2 ("unreferenced") should not
5207        // count toward NDV even though it appears in the dictionary's values array.
5208        let keys = Int32Array::from(vec![0, 1, 0, 1]);
5209        let values: ArrayRef = Arc::new(StringArray::from(vec!["cat", "dog", "unreferenced"]));
5210        let dict: ArrayRef = Arc::new(DictionaryArray::<Int32Type>::try_new(keys, values).unwrap());
5211
5212        let schema = Arc::new(Schema::new(vec![Field::new(
5213            "x",
5214            DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
5215            false,
5216        )]));
5217        let batch = RecordBatch::try_new(schema, vec![dict]).unwrap();
5218
5219        let props = WriterProperties::builder()
5220            .set_write_row_group_number_distinct_values(true)
5221            .build();
5222        let mut buf = Vec::new();
5223        let mut writer = ArrowWriter::try_new(&mut buf, batch.schema(), Some(props)).unwrap();
5224        writer.write(&batch).unwrap();
5225        let metadata = writer.close().unwrap();
5226
5227        let count = metadata
5228            .row_group(0)
5229            .column(0)
5230            .statistics()
5231            .and_then(|s| s.distinct_count_opt())
5232            .expect("distinct_count should be set");
5233        assert_eq!(
5234            count, 2,
5235            "unreferenced dictionary values must not count toward NDV"
5236        );
5237    }
5238
5239    #[test]
5240    fn test_dictionary_ndv_across_batches_regression() {
5241        // Regression test for https://github.com/apache/arrow-rs/issues/11172.
5242        let make_dict_batch = |a: &str, b: &str| -> RecordBatch {
5243            let keys = Int32Array::from(vec![0, 1, 0, 1]);
5244            let values: ArrayRef = Arc::new(StringArray::from(vec![a, b]));
5245            let dict: ArrayRef =
5246                Arc::new(DictionaryArray::<Int32Type>::try_new(keys, values).unwrap());
5247            let schema = Arc::new(Schema::new(vec![Field::new(
5248                "x",
5249                DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
5250                false,
5251            )]));
5252            RecordBatch::try_new(schema, vec![dict]).unwrap()
5253        };
5254
5255        // batch1: dict = ["cat", "dog"], batch2: dict = ["fish", "cat"]
5256        // Distinct values across both batches: "cat", "dog", "fish" NDV = 3
5257        let batch1 = make_dict_batch("cat", "dog");
5258        let batch2 = make_dict_batch("fish", "cat");
5259
5260        let props = WriterProperties::builder()
5261            .set_write_row_group_number_distinct_values(true)
5262            .build();
5263        let mut buf = Vec::new();
5264        let mut writer = ArrowWriter::try_new(&mut buf, batch1.schema(), Some(props)).unwrap();
5265        writer.write(&batch1).unwrap();
5266        writer.write(&batch2).unwrap();
5267        let metadata = writer.close().unwrap();
5268
5269        let count = metadata
5270            .row_group(0)
5271            .column(0)
5272            .statistics()
5273            .and_then(|s| s.distinct_count_opt())
5274            .expect("distinct_count should be set");
5275        assert_eq!(
5276            count, 3,
5277            "NDV should count distinct values, not distinct key indices"
5278        );
5279    }
5280
5281    #[test]
5282    fn ree_struct_with_ree_child() {
5283        // Struct with a REE string field and a REE int field — confirms
5284        // recursion visits every child and each collapses to the right leaf type.
5285        let run_ends = Int32Array::from(vec![2i32, 3, 5]);
5286
5287        let col_a: ArrayRef = Arc::new(
5288            RunArray::try_new(
5289                &run_ends,
5290                &StringArray::from(vec![Some("foo"), None, Some("bar")]),
5291            )
5292            .unwrap(),
5293        );
5294        let col_b: ArrayRef = Arc::new(
5295            RunArray::try_new(&run_ends, &Int32Array::from(vec![Some(1), None, Some(2)])).unwrap(),
5296        );
5297
5298        let struct_array: ArrayRef = Arc::new(StructArray::new(
5299            Fields::from(vec![
5300                Field::new("a", col_a.data_type().clone(), true),
5301                Field::new("b", col_b.data_type().clone(), true),
5302            ]),
5303            vec![col_a, col_b],
5304            None,
5305        ));
5306
5307        let schema = Arc::new(Schema::new(vec![Field::new(
5308            "row",
5309            struct_array.data_type().clone(),
5310            true,
5311        )]));
5312        let batch = RecordBatch::try_new(schema.clone(), vec![struct_array]).unwrap();
5313
5314        let mut buf = Vec::new();
5315        let mut writer = ArrowWriter::try_new(&mut buf, schema, None).unwrap();
5316        writer.write(&batch).unwrap();
5317        let metadata = writer.close().unwrap();
5318
5319        let parquet_schema = metadata.file_metadata().schema_descr();
5320        assert_eq!(parquet_schema.num_columns(), 2);
5321        assert_eq!(
5322            parquet_schema.column(0).physical_type(),
5323            crate::basic::Type::BYTE_ARRAY
5324        );
5325        assert_eq!(parquet_schema.column(0).path().string(), "row.a");
5326        assert_eq!(
5327            parquet_schema.column(1).physical_type(),
5328            crate::basic::Type::INT32
5329        );
5330        assert_eq!(parquet_schema.column(1).path().string(), "row.b");
5331    }
5332
5333    /// Regression test for https://github.com/apache/arrow-rs/issues/11073
5334    ///
5335    /// This checks that the `ArrowColumnWriter` path produces the same min/max
5336    /// statistics as writing the column directly with the low-level
5337    /// `SerializedFileWriter` API, for both `BinaryArray` (the buggy case)
5338    /// and `FixedSizeBinaryArray` (which already worked correctly).
5339    #[test]
5340    fn test_decimal_byte_array_statistics_signed_comparison() {
5341        use crate::basic::{LogicalType, Repetition, Type as PhysicalType};
5342        use crate::data_type::{ByteArray, ByteArrayType};
5343        use crate::schema::types::Type as SchemaType;
5344
5345        // 1-byte two's-complement decimal values: -1, 0, 1
5346        const VALUES: [&[u8]; 3] = [&[0xffu8], &[0x00], &[0x01]];
5347
5348        fn new_file(physical: PhysicalType) -> SerializedFileWriter<Vec<u8>> {
5349            let mut field = SchemaType::primitive_type_builder("value", physical)
5350                .with_repetition(Repetition::REQUIRED)
5351                .with_logical_type(Some(LogicalType::decimal(0, 2)))
5352                .with_precision(2)
5353                .with_scale(0);
5354            if physical == PhysicalType::FIXED_LEN_BYTE_ARRAY {
5355                field = field.with_length(1);
5356            }
5357            let root = SchemaType::group_type_builder("root")
5358                .with_fields(vec![Arc::new(field.build().unwrap())])
5359                .build()
5360                .unwrap();
5361            SerializedFileWriter::new(Vec::new(), Arc::new(root), Default::default()).unwrap()
5362        }
5363
5364        fn read_minmax(file: Vec<u8>) -> (i8, i8) {
5365            let reader = SerializedFileReader::new(Bytes::from(file)).unwrap();
5366            let metadata = reader.metadata();
5367            assert_eq!(metadata.file_metadata().num_rows(), 3);
5368            let stats = metadata
5369                .row_group(0)
5370                .column(0)
5371                .statistics()
5372                .expect("missing statistics");
5373            (
5374                stats.min_bytes_opt().unwrap()[0] as i8,
5375                stats.max_bytes_opt().unwrap()[0] as i8,
5376            )
5377        }
5378
5379        fn direct_parquet() -> Vec<u8> {
5380            let mut file = new_file(PhysicalType::BYTE_ARRAY);
5381            let mut group = file.next_row_group().unwrap();
5382            let mut column = group.next_column().unwrap().unwrap();
5383            let values = VALUES
5384                .iter()
5385                .map(|v| ByteArray::from(v.to_vec()))
5386                .collect::<Vec<_>>();
5387            column
5388                .typed::<ByteArrayType>()
5389                .write_batch(&values, None, None)
5390                .unwrap();
5391            column.close().unwrap();
5392            group.close().unwrap();
5393            file.into_inner().unwrap()
5394        }
5395
5396        fn arrow_bounds(mut file: SerializedFileWriter<Vec<u8>>, array: ArrayRef) -> Vec<u8> {
5397            let field = Field::new("value", array.data_type().clone(), false);
5398            let schema = Arc::new(Schema::new(vec![field.clone()]));
5399            let factory = ArrowRowGroupWriterFactory::new(&file, schema);
5400            let mut writer: ArrowColumnWriter = factory.create_column_writers(0).unwrap().remove(0);
5401            let leaf = compute_leaves(&field, &array).unwrap().remove(0);
5402            writer.write(&leaf).unwrap();
5403            let mut group = file.next_row_group().unwrap();
5404            writer
5405                .close()
5406                .unwrap()
5407                .append_to_row_group(&mut group)
5408                .unwrap();
5409            group.close().unwrap();
5410            file.into_inner().unwrap()
5411        }
5412
5413        fn arrow_binary() -> Vec<u8> {
5414            let file = new_file(PhysicalType::BYTE_ARRAY);
5415            let array: ArrayRef = Arc::new(BinaryArray::from_vec(VALUES.to_vec()));
5416            arrow_bounds(file, array)
5417        }
5418
5419        fn arrow_fixed_size_binary() -> Vec<u8> {
5420            let file = new_file(PhysicalType::FIXED_LEN_BYTE_ARRAY);
5421            let array: ArrayRef =
5422                Arc::new(FixedSizeBinaryArray::try_from_iter(VALUES.into_iter()).unwrap());
5423            arrow_bounds(file, array)
5424        }
5425
5426        let direct = read_minmax(direct_parquet());
5427        let fixed = read_minmax(arrow_fixed_size_binary());
5428        let binary = read_minmax(arrow_binary());
5429
5430        assert_eq!(direct, (-1, 1), "incorrect direct Parquet stats");
5431        assert_eq!(fixed, (-1, 1), "incorrect Arrow FixedSizeBinaryArray stats");
5432        assert_eq!(binary, (-1, 1), "incorrect Arrow BinaryArray stats");
5433    }
5434}