Skip to main content

vortex_arrow/
session.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Plugin layer for moving Arrow extension types in and out of Vortex.
5//!
6//! Vortex's canonical Arrow conversion (see [`crate::dtype`] and the executor in
7//! [`crate::executor`]) handles every non-extension Arrow type and the builtin temporal
8//! extensions. The plugins registered here cover the remaining case: **Arrow extension types**.
9//!
10//! * An [`ArrowExportVTable`] is dispatched purely by the **target Arrow extension Id** —
11//!   the plugin is selected when the caller asks for an Arrow [`Field`] carrying matching
12//!   `ARROW:extension:name` metadata. The Vortex source dtype/encoding is irrelevant to
13//!   dispatch.
14//! * An [`ArrowImportVTable`] is dispatched by the **source Arrow extension name** carried
15//!   on the incoming [`Field`]. The plugin is responsible for both preserving extension
16//!   identity and re-encoding storage if needed (e.g. Arrow `FixedSizeBinary[16]` for UUID
17//!   becomes Vortex `FixedSizeList<u8; 16>`).
18//!
19//! Multiple plugins may register against the same key. They are tried in registration order;
20//! each may return [`ArrowExport::Unsupported`] / [`ArrowImport::Unsupported`] to defer to
21//! the next.
22
23use std::any::Any;
24use std::borrow::Cow;
25use std::fmt::Debug;
26use std::sync::Arc;
27
28use arrow_array::Array as ArrowArray;
29use arrow_array::ArrayRef as ArrowArrayRef;
30use arrow_array::RecordBatch;
31use arrow_array::RunArray;
32use arrow_array::cast::AsArray;
33use arrow_array::make_array;
34use arrow_array::types::Int16Type;
35use arrow_array::types::Int32Type;
36use arrow_array::types::Int64Type;
37use arrow_array::types::RunEndIndexType;
38use arrow_schema::DataType;
39use arrow_schema::Field;
40use arrow_schema::FieldRef;
41use arrow_schema::Fields;
42use arrow_schema::Schema;
43use arrow_schema::extension::EXTENSION_TYPE_NAME_KEY;
44use tracing::debug;
45use tracing::trace;
46use vortex_array::ArrayRef;
47use vortex_array::ExecutionCtx;
48use vortex_array::IntoArray;
49use vortex_array::arrays::DictArray;
50use vortex_array::arrays::FixedSizeListArray;
51use vortex_array::arrays::ListArray;
52use vortex_array::arrays::ListViewArray;
53use vortex_array::arrays::StructArray;
54use vortex_array::dtype::DType;
55use vortex_array::dtype::FieldName;
56use vortex_array::dtype::FieldNames;
57use vortex_array::dtype::NativePType;
58use vortex_array::dtype::Nullability;
59use vortex_array::dtype::StructFields;
60use vortex_array::dtype::extension::ExtId;
61use vortex_array::extension::datetime::AnyTemporal;
62use vortex_array::validity::Validity;
63use vortex_error::VortexResult;
64use vortex_error::vortex_bail;
65use vortex_error::vortex_ensure;
66use vortex_error::vortex_ensure_eq;
67use vortex_error::vortex_err;
68use vortex_session::ArcSwapMap;
69use vortex_session::SessionExt;
70use vortex_session::SessionGuard;
71use vortex_session::SessionVar;
72use vortex_session::registry::Id;
73
74use crate::ArrowExportOptions;
75use crate::IntoVortexArray;
76use crate::convert::from_arrow_dyn;
77use crate::convert::map_from_arrow_parts;
78use crate::convert::nulls;
79use crate::convert::remove_nulls;
80use crate::convert::trim_offsets;
81use crate::dtype::from_arrow_data_type;
82use crate::dtype::to_data_type_naive;
83use crate::executor::execute_arrow_naive;
84use crate::run_end_import::run_end_from_arrow;
85
86/// Outcome of a successful call to [`ArrowExportVTable::execute_arrow`].
87///
88/// Plugins that don't handle the supplied array return [`Unsupported`][Self::Unsupported]
89/// with ownership of the input so the session can probe the next plugin or fall back to the
90/// canonical path. Errors are propagated through [`VortexResult`].
91pub enum ArrowExport {
92    /// The plugin does not handle this input; the session may try another plugin.
93    Unsupported(ArrayRef),
94    /// A successful export.
95    Exported(ArrowArrayRef),
96}
97
98/// Outcome of a successful call to [`ArrowImportVTable::from_arrow_array`].
99///
100/// Plugins that don't handle the supplied array return [`Unsupported`][Self::Unsupported]
101/// with ownership of the input so the session can probe the next plugin or fall back to the
102/// canonical path. Errors are propagated through [`VortexResult`].
103pub enum ArrowImport {
104    /// The plugin does not handle this input; the session may try another plugin.
105    Unsupported(ArrowArrayRef),
106    /// A successful import.
107    Imported(ArrayRef),
108}
109
110/// The Arrow type description of an array being imported by [`ArrowSession::from_arrow_array`].
111///
112/// Callers holding an Arrow [`Field`] (or [`FieldRef`]) should pass it: its
113/// `ARROW:extension:name` metadata is what dispatches the array to a registered
114/// [`ArrowImportVTable`].
115///
116/// An Arrow array can carry a validity (null) buffer regardless of whether its schema declares
117/// the field nullable, so when no [`Field`] is in hand the caller passes the desired nullability
118/// instead, as a [`bool`] or a [`Nullability`]. An anonymous field is then synthesized from the
119/// array's own data type, which means no extension plugin is dispatched for the array itself;
120/// fields nested inside container data types still carry their metadata and are routed through
121/// their importers.
122pub trait IntoArrowField<'a> {
123    /// Resolve to the Arrow [`Field`] describing an array of `data_type`.
124    fn into_arrow_field(self, data_type: &DataType) -> Cow<'a, Field>;
125}
126
127impl<'a> IntoArrowField<'a> for &'a Field {
128    fn into_arrow_field(self, _data_type: &DataType) -> Cow<'a, Field> {
129        Cow::Borrowed(self)
130    }
131}
132
133impl<'a> IntoArrowField<'a> for &'a FieldRef {
134    fn into_arrow_field(self, _data_type: &DataType) -> Cow<'a, Field> {
135        Cow::Borrowed(self.as_ref())
136    }
137}
138
139impl<'a> IntoArrowField<'a> for bool {
140    fn into_arrow_field(self, data_type: &DataType) -> Cow<'a, Field> {
141        Cow::Owned(Field::new("", data_type.clone(), self))
142    }
143}
144
145impl<'a> IntoArrowField<'a> for Nullability {
146    fn into_arrow_field(self, data_type: &DataType) -> Cow<'a, Field> {
147        self.is_nullable().into_arrow_field(data_type)
148    }
149}
150
151/// Plugin layer for exporting a Vortex array to an Arrow extension type.
152///
153/// This is purely an implementation trait, its methods should not be called directly. Instead,
154/// use the methods on [`ArrowSession`].
155pub trait ArrowExportVTable: 'static + Send + Sync + Debug {
156    /// The Arrow extension ID this plugin produces.
157    fn arrow_ext_id(&self) -> Id;
158
159    /// The Vortex array or extension ID this plugin maps from. Used only for inference by
160    /// [`ArrowSession::to_arrow_field`] / [`ArrowSession::to_arrow_schema`]; never as a
161    /// dispatch key for [`execute_arrow`][Self::execute_arrow].
162    fn vortex_id(&self) -> Id;
163
164    /// Build the Arrow [`Field`] this plugin produces for the given Vortex extension
165    /// `dtype`. Used during schema inference.
166    fn to_arrow_field(
167        &self,
168        name: &str,
169        dtype: &DType,
170        session: &ArrowSession,
171    ) -> VortexResult<Option<Field>>;
172
173    /// Convert a Vortex array into an Arrow array shaped to `target`.
174    ///
175    /// Returns ownership of `array` via [`ArrowExport::Unsupported`] when the plugin cannot
176    /// handle the input. Plugins that export child or storage arrays must pass `options` on to
177    /// those exports.
178    fn execute_arrow(
179        &self,
180        array: ArrayRef,
181        target: &Field,
182        options: &ArrowExportOptions,
183        ctx: &mut ExecutionCtx,
184    ) -> VortexResult<ArrowExport>;
185}
186
187/// Plugin layer for importing an Arrow extension-typed array into a Vortex array.
188///
189/// Plugins are dispatched by `arrow_ext_id`. The session peels Arrow dictionaries before it
190/// dispatches, so a plugin never sees a [`DataType::Dictionary`] field or array. It sees the value
191/// field, with the dictionary field's metadata, and the values array. The session then wraps the
192/// plugin's result in a [`DictArray`] with the dictionary's codes.
193///
194/// Arrow stores dictionary values as a bare [`DataType`], so their extension metadata lives on
195/// the outer [`Field`]. Peeling the dictionary lets the importer see the value type described by
196/// that metadata. [`DataType::RunEndEncoded`] has a separate values field that can carry its own
197/// extension metadata, so its values use the normal nested-field import path.
198///
199/// This is purely an implementation trait, its methods should not be called directly. Instead,
200/// use the methods on [`ArrowSession`].
201pub trait ArrowImportVTable: 'static + Send + Sync + Debug {
202    /// The Arrow extension name this plugin handles.
203    fn arrow_ext_id(&self) -> Id;
204
205    /// Build the Vortex [`DType`] that corresponds to `field` (which carries this plugin's
206    /// Arrow extension metadata).
207    ///
208    /// `session` is provided so plugins can resolve nested or storage fields through the
209    /// plugin-aware conversion (e.g. [`ArrowSession::from_arrow_datatype`]) instead of the
210    /// naive Arrow → Vortex mapping.
211    #[allow(clippy::wrong_self_convention)]
212    fn from_arrow_field(
213        &self,
214        field: &Field,
215        session: &ArrowSession,
216    ) -> VortexResult<Option<DType>>;
217
218    /// Convert an Arrow array into a Vortex array of `dtype`.
219    ///
220    /// Returns ownership of `array` via [`ArrowImport::Unsupported`] when the plugin cannot
221    /// handle the input.
222    ///
223    /// `session` is provided so plugins can convert storage or nested arrays through the
224    /// session (e.g. [`ArrowSession::from_arrow_array`], passing a nullability rather than a
225    /// [`Field`] so the plugin is not dispatched again).
226    #[allow(clippy::wrong_self_convention)]
227    fn from_arrow_array(
228        &self,
229        array: ArrowArrayRef,
230        field: &Field,
231        dtype: &DType,
232        session: &ArrowSession,
233    ) -> VortexResult<ArrowImport>;
234}
235
236pub type ArrowExportVTableRef = Arc<dyn ArrowExportVTable>;
237pub type ArrowImportVTableRef = Arc<dyn ArrowImportVTable>;
238
239/// Registry of Arrow exporters, keyed by target Arrow extension [`Id`].
240type ArrowExporterRegistry = ArcSwapMap<Id, Arc<[ArrowExportVTableRef]>>;
241/// Registry of Arrow exporters, keyed by source Vortex extension [`ExtId`].
242type VortexExporterRegistry = ArcSwapMap<ExtId, Arc<[ArrowExportVTableRef]>>;
243/// Registry of Arrow importers, keyed by source Arrow extension [`Id`].
244type ArrowImporterRegistry = ArcSwapMap<Id, Arc<[ArrowImportVTableRef]>>;
245
246/// Session-scoped registry of Arrow extension plugins.
247///
248/// Exporters are stored in two indices: one keyed by Arrow extension Id (used for
249/// `execute_arrow` dispatch) and one keyed by Vortex extension Id (used **only** by
250/// `to_arrow_field` / `to_arrow_schema` inference, when callers need to translate a Vortex
251/// extension `DType` into an Arrow `Field` with no target schema in hand). Importers are
252/// keyed by Arrow extension name. Extension plugins are registered by the crate that owns the
253/// extension type (for example `vortex-uuid`); temporal extensions are handled by the canonical
254/// Arrow ↔ Vortex path and do not need plugins.
255#[derive(Clone, Debug, Default)]
256pub struct ArrowSession {
257    exporters: ArrowExporterRegistry,
258    exporters_by_vortex: VortexExporterRegistry,
259    importers: ArrowImporterRegistry,
260}
261
262impl ArrowSession {
263    /// Register an [`ArrowExportVTable`] under its target Arrow extension Id (for dispatch)
264    /// and its source Vortex extension Id (for schema inference).
265    pub fn register_exporter(&self, exporter: ArrowExportVTableRef) {
266        self.exporters.push(
267            exporter.arrow_ext_id(),
268            ArrowExportVTableRef::clone(&exporter),
269        );
270        self.exporters_by_vortex
271            .push(exporter.vortex_id(), exporter);
272    }
273
274    /// Register an [`ArrowImportVTable`] under its source Arrow extension name.
275    pub fn register_importer(&self, importer: ArrowImportVTableRef) {
276        self.importers.push(importer.arrow_ext_id(), importer);
277    }
278
279    fn exporters(&self, id: &Id) -> Arc<[ArrowExportVTableRef]> {
280        self.exporters.get(id).unwrap_or_else(|| Arc::from([]))
281    }
282
283    fn exporters_by_vortex(&self, id: &Id) -> Arc<[ArrowExportVTableRef]> {
284        self.exporters_by_vortex
285            .get(id)
286            .unwrap_or_else(|| Arc::from([]))
287    }
288
289    fn importers(&self, id: &Id) -> Arc<[ArrowImportVTableRef]> {
290        self.importers.get(id).unwrap_or_else(|| Arc::from([]))
291    }
292
293    /// Build the Arrow [`Field`] for a Vortex [`DType`].
294    ///
295    /// For [`DType::Extension`]s, plugins registered against the extension's `Id`
296    /// are tried in registration order; the first plugin to return `Some(field)` wins.
297    pub fn to_arrow_field(&self, name: &str, dtype: &DType) -> VortexResult<Field> {
298        // Handle the structural encodings, which may have recursive types
299        match dtype {
300            DType::List(elem_dtype, nullability) => {
301                let elem_field = self.to_arrow_field(Field::LIST_FIELD_DEFAULT_NAME, elem_dtype)?;
302                Ok(Field::new_list(name, elem_field, nullability.is_nullable()))
303            }
304            DType::FixedSizeList(elem_dtype, elem_size, nullability) => {
305                let elem_field = self.to_arrow_field(Field::LIST_FIELD_DEFAULT_NAME, elem_dtype)?;
306                Ok(Field::new_fixed_size_list(
307                    name,
308                    elem_field,
309                    (*elem_size).try_into()?,
310                    nullability.is_nullable(),
311                ))
312            }
313            DType::Map(map_dtype, nullability) => {
314                let key = self.to_arrow_field("key", &map_dtype.key_dtype())?;
315                let value = self.to_arrow_field("value", &map_dtype.value_dtype())?;
316                let entries = Field::new_struct("entries", Fields::from(vec![key, value]), false);
317                Ok(Field::new(
318                    name,
319                    DataType::Map(Arc::new(entries), map_dtype.keys_sorted()),
320                    nullability.is_nullable(),
321                ))
322            }
323            DType::Struct(fields, nullability) => {
324                let arrow_fields = Fields::from_iter(
325                    fields
326                        .fields()
327                        .zip(fields.names().iter())
328                        .map(|(field, name)| self.to_arrow_field(name.as_ref(), &field))
329                        .collect::<VortexResult<Vec<_>>>()?,
330                );
331                Ok(Field::new_struct(
332                    name,
333                    arrow_fields,
334                    nullability.is_nullable(),
335                ))
336            }
337            DType::Extension(ext) if !ext.is::<AnyTemporal>() => {
338                for plugin in self.exporters_by_vortex(&ext.id()).iter() {
339                    if let Some(field) =
340                        plugin.to_arrow_field(name, &DType::Extension(ext.clone()), self)?
341                    {
342                        return Ok(field);
343                    }
344                }
345                vortex_bail!("extension type cannot be converted to Arrow without a plugin: {ext}");
346            }
347            DType::Variant(_) => {
348                // TODO(Adam): This currently encodes information about parquet-variant
349                // at this level. Variant's complexity with being an essentially logical type
350                // with multiple physical layout complicates handling this correctly.
351                Ok(Field::new(
352                    name,
353                    DataType::Struct(
354                        vec![
355                            Field::new("metadata", DataType::BinaryView, dtype.is_nullable()),
356                            Field::new("value", DataType::BinaryView, dtype.is_nullable()),
357                        ]
358                        .into(),
359                    ),
360                    dtype.is_nullable(),
361                )
362                .with_metadata(
363                    [(
364                        EXTENSION_TYPE_NAME_KEY.to_string(),
365                        "arrow.parquet.variant".to_string(),
366                    )]
367                    .into(),
368                ))
369            }
370            _ => Ok(Field::new(
371                name,
372                to_data_type_naive(dtype)?,
373                dtype.is_nullable(),
374            )),
375        }
376    }
377
378    /// Build the Arrow [`Schema`] for a Vortex top-level [`DType::Struct`], dispatching
379    /// extension fields through registered export plugins for inference. Nested
380    /// extensions are preserved via [`Self::to_arrow_field`].
381    pub fn to_arrow_schema(&self, dtype: &DType) -> VortexResult<Schema> {
382        let DType::Struct(struct_dtype, _) = dtype else {
383            vortex_bail!("to_arrow_schema requires a top-level struct dtype, got {dtype}");
384        };
385        let mut fields = Vec::with_capacity(struct_dtype.names().len());
386        for (name, field_dtype) in struct_dtype.names().iter().zip(struct_dtype.fields()) {
387            fields.push(self.to_arrow_field(name.as_ref(), &field_dtype)?);
388        }
389        Ok(Schema::new(fields))
390    }
391
392    /// Returns the Arrow [`DataType`] that best corresponds to the given Vortex [`DType`],
393    /// dispatching [`DType::Extension`]s through registered export plugins.
394    ///
395    /// Note that a bare [`DataType`] cannot carry `ARROW:extension:name` metadata; use
396    /// [`Self::to_arrow_field`] when extension identity must survive the roundtrip.
397    pub fn to_arrow_datatype(&self, dtype: &DType) -> VortexResult<DataType> {
398        Ok(self.to_arrow_field("", dtype)?.data_type().clone())
399    }
400
401    /// Build the Vortex [`DType`] for an Arrow [`Field`].
402    ///
403    /// A [`DataType::Dictionary`] field converts as its value field with the same metadata.
404    ///
405    /// Plugins registered against the field's Arrow extension name are tried in
406    /// registration order; the first plugin to return `Some(dtype)` wins. If none
407    /// match (or all return `None`), the builtin `arrow.parquet.variant` extension maps
408    /// to [`DType::Variant`], and any other field converts through
409    /// [`Self::from_arrow_datatype`] so extension metadata on nested element/struct
410    /// fields is preserved.
411    #[expect(clippy::disallowed_methods, reason = "interning a dynamic id")]
412    pub fn from_arrow_field(&self, field: &Field) -> VortexResult<DType> {
413        if let DataType::Dictionary(_, value_type) = field.data_type() {
414            return self
415                .from_arrow_field(&field.clone().with_data_type(value_type.as_ref().clone()));
416        }
417
418        if let Some(name) = field.metadata().get(EXTENSION_TYPE_NAME_KEY) {
419            for plugin in self.importers(&Id::new(name)).iter() {
420                if let Some(dtype) = plugin.from_arrow_field(field, self)? {
421                    return Ok(dtype);
422                }
423            }
424            // Parquet Variant is understood even without a registered importer plugin.
425            if name == "arrow.parquet.variant" {
426                return Ok(DType::Variant(field.is_nullable().into()));
427            }
428        }
429        self.from_arrow_datatype(field.data_type(), field.is_nullable().into())
430    }
431
432    /// Build the Vortex [`DType`] for an Arrow [`DataType`].
433    ///
434    /// Recurses into container types ([`DataType::List`] family, [`DataType::FixedSizeList`],
435    /// [`DataType::Struct`], [`DataType::Map`], [`DataType::RunEndEncoded`]) via
436    /// [`Self::from_arrow_field`] so extension metadata on nested fields dispatches through
437    /// registered import plugins. Leaf types use the canonical Arrow → Vortex mapping.
438    ///
439    /// [`DataType::Dictionary`] is a partial exception: Arrow models its values as a bare
440    /// [`DataType`] rather than a [`Field`], so the values themselves cannot carry an extension
441    /// name. Fields nested *inside* that data type still do, and are dispatched normally.
442    pub fn from_arrow_datatype(
443        &self,
444        data_type: &DataType,
445        nullability: Nullability,
446    ) -> VortexResult<DType> {
447        Ok(match data_type {
448            DataType::List(elem)
449            | DataType::LargeList(elem)
450            | DataType::ListView(elem)
451            | DataType::LargeListView(elem) => {
452                DType::List(Arc::new(self.from_arrow_field(elem.as_ref())?), nullability)
453            }
454            DataType::FixedSizeList(elem, size) => DType::FixedSizeList(
455                Arc::new(self.from_arrow_field(elem.as_ref())?),
456                *size as u32,
457                nullability,
458            ),
459            DataType::Map(entries, keys_sorted) => {
460                vortex_ensure!(
461                    !entries.is_nullable(),
462                    "Arrow map entries field must be non-nullable"
463                );
464                let DataType::Struct(fields) = entries.data_type() else {
465                    vortex_bail!(
466                        "Arrow map entries field must have Struct type, got {:?}",
467                        entries.data_type()
468                    );
469                };
470                vortex_ensure_eq!(
471                    fields.len(),
472                    2,
473                    "Arrow map entries struct must contain exactly two fields"
474                );
475                vortex_ensure!(
476                    !fields[0].is_nullable(),
477                    "Arrow map key field must be non-nullable"
478                );
479                DType::map(
480                    self.from_arrow_field(fields[0].as_ref())?,
481                    self.from_arrow_field(fields[1].as_ref())?,
482                    *keys_sorted,
483                    nullability,
484                )?
485            }
486            DataType::Struct(fields) => DType::Struct(self.from_arrow_fields(fields)?, nullability),
487            DataType::Dictionary(_, value_type) => {
488                self.from_arrow_datatype(value_type.as_ref(), nullability)?
489            }
490            DataType::RunEndEncoded(_, value_field) => {
491                self.from_arrow_field(&run_end_values_field(value_field, nullability))?
492            }
493            _ => from_arrow_data_type(data_type, nullability)?,
494        })
495    }
496
497    /// Build Vortex [`StructFields`] for Arrow [`Fields`], dispatching each field through
498    /// [`Self::from_arrow_field`].
499    pub fn from_arrow_fields(&self, fields: &Fields) -> VortexResult<StructFields> {
500        fields
501            .iter()
502            .map(|f| {
503                self.from_arrow_field(f)
504                    .map(|dt| (FieldName::from(f.name().as_str()), dt))
505            })
506            .collect::<VortexResult<StructFields>>()
507    }
508
509    /// Build the Vortex [`DType`] for an Arrow [`Schema`], dispatching extension fields
510    /// through registered import plugins. The result is a top-level non-nullable struct
511    /// matching the schema's fields.
512    pub fn from_arrow_schema(&self, schema: &Schema) -> VortexResult<DType> {
513        Ok(DType::Struct(
514            self.from_arrow_fields(schema.fields())?,
515            Nullability::NonNullable,
516        ))
517    }
518
519    /// Decode an Arrow [`RecordBatch`] into a Vortex struct array, dispatching each
520    /// extension column through its registered import plugin.
521    ///
522    /// `schema` is the authoritative Arrow schema used for dispatch — the columns are
523    /// consumed positionally. Pass an external schema (rather than relying on
524    /// `batch.schema()`) when upstream DataFusion plumbing may have stripped Field-level
525    /// extension metadata from the runtime RecordBatch.
526    pub fn from_arrow_record_batch(
527        &self,
528        batch: RecordBatch,
529        schema: &Schema,
530    ) -> VortexResult<ArrayRef> {
531        vortex_ensure_eq!(batch.num_columns(), schema.fields().len());
532        let length = batch.num_rows();
533        let names = FieldNames::from_iter(
534            schema
535                .fields()
536                .iter()
537                .map(|f| FieldName::from(f.name().as_str())),
538        );
539        let mut columns = Vec::with_capacity(schema.fields().len());
540        for (col, field) in batch.columns().iter().zip(schema.fields().iter()) {
541            columns.push(self.from_arrow_array_inner(ArrowArrayRef::clone(col), field)?);
542        }
543        Ok(StructArray::try_new(names, columns, length, Validity::NonNullable)?.into_array())
544    }
545
546    /// Execute a Vortex array into an Arrow array.
547    ///
548    /// If `target` carries an `ARROW:extension:name`, the plugin registry is probed for one that
549    /// can support executing to the target extension type.
550    ///
551    /// With `target = None` the fallback path picks the array's preferred Arrow physical type
552    /// and executes directly into that, ignoring extension types.
553    ///
554    /// Uses the default [`ArrowExportOptions`]; see [`exporter`](Self::exporter) to
555    /// change them.
556    pub fn execute_arrow(
557        &self,
558        array: ArrayRef,
559        target: Option<&Field>,
560        ctx: &mut ExecutionCtx,
561    ) -> VortexResult<ArrowArrayRef> {
562        self.exporter(&ArrowExportOptions::default())
563            .execute_arrow(array, target, ctx)
564    }
565
566    /// Return an exporter that applies `options` to its exports.
567    ///
568    /// ```
569    /// use arrow_array::Array;
570    /// use vortex_array::IntoArray;
571    /// use vortex_array::VortexSessionExecute;
572    /// use vortex_session::VortexSession;
573    /// use vortex_array::arrays::VarBinViewArray;
574    /// use vortex_arrow::ArrowExportOptions;
575    /// use vortex_arrow::ArrowSessionExt;
576    /// use vortex_arrow::CompactBuffers;
577    ///
578    /// let session = VortexSession::empty();
579    /// let array = VarBinViewArray::from_iter_str(["a", "b"]).into_array();
580    /// let options = ArrowExportOptions::default().with(CompactBuffers(false));
581    /// let arrow = session.arrow().exporter(&options).execute_arrow(
582    ///     array,
583    ///     None,
584    ///     &mut session.create_execution_ctx(),
585    /// )?;
586    /// assert_eq!(arrow.len(), 2);
587    /// # Ok::<(), vortex_error::VortexError>(())
588    /// ```
589    pub fn exporter<'a>(&'a self, options: &'a ArrowExportOptions) -> ArrowExporter<'a> {
590        ArrowExporter {
591            session: self,
592            options,
593        }
594    }
595
596    /// Decode an Arrow array into a Vortex array.
597    ///
598    /// `field` describes the Arrow type the array is imported from: pass an Arrow [`Field`] when
599    /// one is available, or just the desired nullability (`true` / `false` /
600    /// [`Nullability`]) to synthesize an anonymous field from the array's own data type. See
601    /// [`IntoArrowField`] for the trade-off between the two.
602    ///
603    /// Routes through the registered import plugin if `field` carries an Arrow extension
604    /// name we recognize, probing each plugin in registration order until one handles the
605    /// input or all return [`ArrowImport::Unsupported`]. Otherwise recurses into container
606    /// arrays ([`arrow_array::StructArray`], [`arrow_array::GenericListArray`],
607    /// [`arrow_array::FixedSizeListArray`], [`arrow_array::GenericListViewArray`]) so
608    /// extension fields nested inside containers reach their importers; leaf types fall
609    /// through to the canonical Arrow → Vortex array conversion.
610    ///
611    /// A dictionary array imports as a [`DictArray`]. Its values import as described above, with
612    /// `field`'s metadata.
613    ///
614    /// # Errors
615    ///
616    /// Returns an error if the field (or requested nullability) is non-nullable but the array
617    /// physically contains nulls, or if the Arrow data type is unsupported.
618    pub fn from_arrow_array<'a>(
619        &self,
620        array: ArrowArrayRef,
621        field: impl IntoArrowField<'a>,
622    ) -> VortexResult<ArrayRef> {
623        let field = field.into_arrow_field(array.data_type());
624        self.from_arrow_array_inner(array, field.as_ref())
625    }
626
627    /// [`Self::from_arrow_array`] with the Arrow [`Field`] already resolved: peel a dictionary,
628    /// probe the import plugins registered for the field's extension name, then fall back to the
629    /// canonical conversion. Also the recursion point for nested fields, which already have a
630    /// [`Field`].
631    #[allow(clippy::wrong_self_convention)]
632    fn from_arrow_array_inner(
633        &self,
634        array: ArrowArrayRef,
635        field: &Field,
636    ) -> VortexResult<ArrayRef> {
637        if let DataType::Dictionary(..) = field.data_type() {
638            return self.dictionary_from_arrow(array.as_ref(), field);
639        }
640
641        if let Some(extension_name) = field.metadata().get(EXTENSION_TYPE_NAME_KEY) {
642            #[expect(clippy::disallowed_methods, reason = "interning a dynamic id")]
643            let importers = self.importers(&Id::new(extension_name));
644            if !importers.is_empty() {
645                let dtype = self.from_arrow_field(field)?;
646                let len = array.len();
647                let mut current = array;
648                for plugin in importers.iter() {
649                    match plugin.from_arrow_array(current, field, &dtype, self)? {
650                        // Parents such as lists reuse the Arrow offsets into this array without
651                        // checking them again, so a plugin must preserve its length, both in what
652                        // it imports and in what it hands back when it declines.
653                        ArrowImport::Imported(arr) => {
654                            vortex_ensure_eq!(
655                                arr.len(),
656                                len,
657                                "Arrow importer {} returned {} elements for an array of {}",
658                                plugin.arrow_ext_id(),
659                                arr.len(),
660                                len
661                            );
662                            return Ok(arr);
663                        }
664                        ArrowImport::Unsupported(arr) => {
665                            vortex_ensure_eq!(
666                                arr.len(),
667                                len,
668                                "Arrow importer {} declined and returned {} elements for an array of {}",
669                                plugin.arrow_ext_id(),
670                                arr.len(),
671                                len
672                            );
673                            current = arr;
674                        }
675                    }
676                }
677                return self.from_arrow_array_canonical(current.as_ref(), field);
678            }
679        }
680        self.from_arrow_array_canonical(array.as_ref(), field)
681    }
682
683    /// Recurse into Arrow container arrays so nested fields with extension metadata reach
684    /// their importers, falling through to the canonical conversion for leaf types.
685    #[allow(clippy::wrong_self_convention)]
686    fn from_arrow_array_canonical(
687        &self,
688        array: &dyn ArrowArray,
689        field: &Field,
690    ) -> VortexResult<ArrayRef> {
691        match field.data_type() {
692            DataType::Struct(fields) => {
693                let arrow_struct = array.as_struct();
694                let names = FieldNames::from_iter(
695                    fields.iter().map(|f| FieldName::from(f.name().as_str())),
696                );
697                let columns = arrow_struct
698                    .columns()
699                    .iter()
700                    .zip(fields.iter())
701                    .map(|(col, child_field)| {
702                        // Arrow pushes nulls into non-nullable fields; strip before recursing
703                        // so Vortex's stricter validity invariants are upheld.
704                        let inner = if col.null_count() > 0 && !child_field.is_nullable() {
705                            make_array(remove_nulls(col.to_data())?)
706                        } else {
707                            ArrowArrayRef::clone(col)
708                        };
709                        self.from_arrow_array_inner(inner, child_field.as_ref())
710                    })
711                    .collect::<VortexResult<Vec<_>>>()?;
712                let validity = nulls(arrow_struct.nulls(), field.is_nullable())?;
713                Ok(
714                    StructArray::try_new(names, columns, arrow_struct.len(), validity)?
715                        .into_array(),
716                )
717            }
718            DataType::List(elem_field) => {
719                let list = array.as_list::<i32>();
720                let (offsets, referenced) = trim_offsets(list.offsets());
721                let elements = self.from_arrow_array(
722                    list.values().slice(referenced.start, referenced.len()),
723                    elem_field.as_ref(),
724                )?;
725                let validity = nulls(list.nulls(), field.is_nullable())?;
726                // SAFETY: Arrow offsets are non-negative and sorted, and `trim_offsets` rebases
727                // them onto the referenced values. The validity has one entry per list.
728                Ok(
729                    unsafe { ListArray::new_unchecked(elements, offsets.into_array(), validity) }
730                        .into_array(),
731                )
732            }
733            DataType::LargeList(elem_field) => {
734                let list = array.as_list::<i64>();
735                let (offsets, referenced) = trim_offsets(list.offsets());
736                let elements = self.from_arrow_array(
737                    list.values().slice(referenced.start, referenced.len()),
738                    elem_field.as_ref(),
739                )?;
740                let validity = nulls(list.nulls(), field.is_nullable())?;
741                // SAFETY: Arrow offsets are non-negative and sorted, and `trim_offsets` rebases
742                // them onto the referenced values. The validity has one entry per list.
743                Ok(
744                    unsafe { ListArray::new_unchecked(elements, offsets.into_array(), validity) }
745                        .into_array(),
746                )
747            }
748            DataType::FixedSizeList(elem_field, list_size) => {
749                let fsl = array.as_fixed_size_list();
750                let elements = self.from_arrow_array_inner(
751                    ArrowArrayRef::clone(fsl.values()),
752                    elem_field.as_ref(),
753                )?;
754                let validity = nulls(fsl.nulls(), field.is_nullable())?;
755                Ok(
756                    FixedSizeListArray::try_new(elements, *list_size as u32, validity, fsl.len())?
757                        .into_array(),
758                )
759            }
760            DataType::ListView(elem_field) => {
761                let list = array.as_list_view::<i32>();
762                let elements = self
763                    .from_arrow_array(ArrowArrayRef::clone(list.values()), elem_field.as_ref())?;
764                let offsets = list.offsets().clone().into_array();
765                let sizes = list.sizes().clone().into_array();
766                let validity = nulls(list.nulls(), field.is_nullable())?;
767                // SAFETY: Arrow list views share one integer type for offsets and sizes, and every
768                // view lies within the values. The validity has one entry per list.
769                Ok(
770                    unsafe { ListViewArray::new_unchecked(elements, offsets, sizes, validity) }
771                        .into_array(),
772                )
773            }
774            DataType::LargeListView(elem_field) => {
775                let list = array.as_list_view::<i64>();
776                let elements = self
777                    .from_arrow_array(ArrowArrayRef::clone(list.values()), elem_field.as_ref())?;
778                let offsets = list.offsets().clone().into_array();
779                let sizes = list.sizes().clone().into_array();
780                let validity = nulls(list.nulls(), field.is_nullable())?;
781                // SAFETY: Arrow list views share one integer type for offsets and sizes, and every
782                // view lies within the values. The validity has one entry per list.
783                Ok(
784                    unsafe { ListViewArray::new_unchecked(elements, offsets, sizes, validity) }
785                        .into_array(),
786                )
787            }
788            DataType::Map(entries_field, keys_sorted) => {
789                let map = array.as_map();
790                let entries_array: ArrowArrayRef = Arc::new(map.entries().clone());
791                let entries = self.from_arrow_array_inner(entries_array, entries_field.as_ref())?;
792                map_from_arrow_parts(
793                    entries,
794                    map.offsets(),
795                    map.nulls(),
796                    *keys_sorted,
797                    field.is_nullable(),
798                )
799            }
800            DataType::RunEndEncoded(ends_field, values_field) => {
801                let values_field = run_end_values_field(values_field, field.is_nullable().into());
802                match ends_field.data_type() {
803                    DataType::Int16 => self.run_end_from_arrow::<Int16Type>(array, &values_field),
804                    DataType::Int32 => self.run_end_from_arrow::<Int32Type>(array, &values_field),
805                    DataType::Int64 => self.run_end_from_arrow::<Int64Type>(array, &values_field),
806                    ends_dt => vortex_bail!(
807                        "Arrow run-end array run ends must be Int16, Int32 or Int64, got {ends_dt}"
808                    ),
809                }
810            }
811            _ => from_arrow_dyn(array, field.is_nullable()),
812        }
813    }
814
815    /// Decode an Arrow run-end array, recursing into its values so extension metadata on the
816    /// values field reaches its importer.
817    #[allow(clippy::wrong_self_convention)]
818    fn run_end_from_arrow<R: RunEndIndexType>(
819        &self,
820        array: &dyn ArrowArray,
821        values_field: &Field,
822    ) -> VortexResult<ArrayRef>
823    where
824        R::Native: NativePType,
825    {
826        let run_array = array
827            .as_any()
828            .downcast_ref::<RunArray<R>>()
829            .ok_or_else(|| vortex_err!("expected an Arrow RunArray, got {}", array.data_type()))?;
830        let values =
831            self.from_arrow_array_inner(ArrowArrayRef::clone(run_array.values()), values_field)?;
832        run_end_from_arrow(run_array, values)
833    }
834
835    /// Decode an Arrow dictionary array into a [`DictArray`], importing its values with `field`'s
836    /// metadata so that an extension name on the dictionary field reaches its importer.
837    fn dictionary_from_arrow(
838        &self,
839        array: &dyn ArrowArray,
840        field: &Field,
841    ) -> VortexResult<ArrayRef> {
842        let dict = array.as_any_dictionary_opt().ok_or_else(|| {
843            vortex_err!(
844                "expected an Arrow DictionaryArray, got {}",
845                array.data_type()
846            )
847        })?;
848
849        let values_field = field
850            .clone()
851            .with_data_type(dict.values().data_type().clone());
852        let values =
853            self.from_arrow_array_inner(ArrowArrayRef::clone(dict.values()), &values_field)?;
854
855        let codes = dict.keys();
856        let codes = from_arrow_dyn(codes, codes.is_nullable())?;
857
858        // SAFETY: arrow-rs enforces the dictionary invariants on construction, so the codes are
859        // in-bounds for the values.
860        Ok(unsafe { DictArray::new_unchecked(codes, values) }.into_array())
861    }
862}
863
864/// The values field of an Arrow [`DataType::RunEndEncoded`], re-stamped with the run-end array's
865/// own nullability.
866fn run_end_values_field(values_field: &FieldRef, nullability: Nullability) -> Field {
867    values_field
868        .as_ref()
869        .clone()
870        .with_nullable(nullability.into())
871}
872
873impl SessionVar for ArrowSession {
874    fn as_any(&self) -> &dyn Any {
875        self
876    }
877
878    fn as_any_mut(&mut self) -> &mut dyn Any {
879        self
880    }
881}
882
883/// An [`ArrowSession`] bound to [`ArrowExportOptions`], created by [`ArrowSession::exporter`].
884#[derive(Clone, Copy, Debug)]
885pub struct ArrowExporter<'a> {
886    session: &'a ArrowSession,
887    options: &'a ArrowExportOptions,
888}
889
890impl ArrowExporter<'_> {
891    pub(crate) fn options(&self) -> &ArrowExportOptions {
892        self.options
893    }
894
895    /// Execute a Vortex array into an Arrow array with the bound options.
896    ///
897    /// Behaves like [`ArrowSession::execute_arrow`]. The options are propagated to nested arrays
898    /// and to registered export plugins.
899    #[expect(clippy::disallowed_methods, reason = "interning a dynamic id")]
900    pub fn execute_arrow(
901        &self,
902        array: ArrayRef,
903        target: Option<&Field>,
904        ctx: &mut ExecutionCtx,
905    ) -> VortexResult<ArrowArrayRef> {
906        // NOTE(aduffy): this looks strange, but we do this to keep target_field as &Field so
907        //  we can avoid cloning target when it is provided. It contains a HashMap internally that
908        //  can be expensive to copy.
909        let arrow_field;
910        let target_field = match target {
911            Some(field) => field,
912            None => {
913                arrow_field = self.session.to_arrow_field("", array.dtype())?;
914                &arrow_field
915            }
916        };
917
918        if let Some(arrow_ext_name) = target_field.metadata().get(EXTENSION_TYPE_NAME_KEY) {
919            // There can be multiple plugins that report support for a particular extension type.
920            // We try them in order until one of them reports a successful conversion.
921            let len = array.len();
922            let mut current = array;
923
924            for plugin in self.session.exporters(&Id::new(arrow_ext_name)).iter() {
925                trace!(
926                    plugin = ?plugin,
927                    extension_name = arrow_ext_name,
928                    "probing plugin for converting Arrow array"
929                );
930
931                match plugin.execute_arrow(current, target_field, self.options, ctx)? {
932                    ArrowExport::Exported(arrow) => {
933                        vortex_ensure_eq!(
934                            arrow.len(),
935                            len,
936                            "Arrow array length does not match Vortex array length after conversion to {:?}",
937                            arrow
938                        );
939                        return Ok(arrow);
940                    }
941                    ArrowExport::Unsupported(array) => current = array,
942                }
943            }
944
945            debug!(
946                extension_id = arrow_ext_name,
947                data_type = ?target_field.data_type(),
948                "unsupported Arrow extension type encountered, falling back to naive execution"
949            );
950
951            return execute_arrow_naive(current, Some(target_field.data_type()), self, ctx);
952        }
953
954        execute_arrow_naive(array, target.map(|field| field.data_type()), self, ctx)
955    }
956}
957
958/// Extension trait for accessing the [`ArrowSession`] on a Vortex session.
959pub trait ArrowSessionExt: SessionExt {
960    /// Get the Arrow session.
961    fn arrow(&self) -> SessionGuard<'_, ArrowSession>;
962}
963
964impl<S: SessionExt> ArrowSessionExt for S {
965    fn arrow(&self) -> SessionGuard<'_, ArrowSession> {
966        self.get::<ArrowSession>()
967    }
968}
969
970#[cfg(test)]
971mod tests {
972    use std::ops::Range;
973    use std::sync::Arc;
974    use std::sync::LazyLock;
975
976    use arrow_array::DictionaryArray;
977    use arrow_array::GenericListArray;
978    use arrow_array::GenericListViewArray;
979    use arrow_array::Int32Array;
980    use arrow_array::Int64Array;
981    use arrow_array::MapArray;
982    use arrow_array::StringArray;
983    use arrow_array::StructArray;
984    use arrow_array::types::Int32Type;
985    use arrow_buffer::OffsetBuffer;
986    use arrow_buffer::ScalarBuffer;
987    use arrow_schema::DataType;
988    use arrow_schema::Field;
989    use arrow_schema::FieldRef;
990    use arrow_schema::Fields;
991    use rstest::rstest;
992    use vortex_array::IntoArray;
993    use vortex_array::VortexSessionExecute as _;
994    use vortex_array::arrays::Dict;
995    use vortex_array::arrays::ListArray;
996    use vortex_array::arrays::PrimitiveArray;
997    use vortex_array::arrays::VarBinViewArray;
998    use vortex_array::assert_arrays_eq;
999    use vortex_array::dtype::DType;
1000    use vortex_array::dtype::Nullability;
1001    use vortex_array::dtype::PType;
1002    use vortex_array::validity::Validity;
1003    use vortex_error::VortexResult;
1004    use vortex_session::VortexSession;
1005    use vortex_session::registry::CachedId;
1006
1007    use super::*;
1008
1009    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
1010
1011    #[rstest]
1012    #[case::prefix(0, 2)]
1013    #[case::middle(500, 2)]
1014    #[case::empty(500, 0)]
1015    #[case::empty_at_end(1000, 0)]
1016    fn test_sliced_list_imports_only_its_rows(
1017        #[values(false, true)] large: bool,
1018        #[case] start: usize,
1019        #[case] len: usize,
1020    ) -> VortexResult<()> {
1021        let lists = |rows: Range<i64>| -> ArrowArrayRef {
1022            let values = Arc::new(Int64Array::from_iter_values(
1023                rows.flat_map(|row| [row, row + 1]),
1024            ));
1025            let len = values.len() / 2;
1026            let field = Arc::new(Field::new("item", DataType::Int64, false));
1027            if large {
1028                Arc::new(GenericListArray::<i64>::new(
1029                    field,
1030                    OffsetBuffer::from_repeated_length(2, len),
1031                    values,
1032                    None,
1033                ))
1034            } else {
1035                Arc::new(GenericListArray::<i32>::new(
1036                    field,
1037                    OffsetBuffer::from_repeated_length(2, len),
1038                    values,
1039                    None,
1040                ))
1041            }
1042        };
1043        let session = ArrowSession::default();
1044        let sliced = session.from_arrow_array(lists(0..1000).slice(start, len), false)?;
1045        let fresh = session.from_arrow_array(lists(start as i64..(start + len) as i64), false)?;
1046        assert_eq!(sliced.nbytes(), fresh.nbytes());
1047        let mut ctx = SESSION.create_execution_ctx();
1048        let expected = ListArray::new(
1049            PrimitiveArray::from_iter(
1050                (start as i64..(start + len) as i64).flat_map(|row| [row, row + 1]),
1051            )
1052            .into_array(),
1053            PrimitiveArray::from_iter((0..=len as u64).map(|row| row * 2)).into_array(),
1054            Validity::NonNullable,
1055            &mut ctx,
1056        );
1057        assert_arrays_eq!(sliced, expected, &mut ctx);
1058        assert_arrays_eq!(fresh, expected, &mut ctx);
1059        Ok(())
1060    }
1061
1062    #[test]
1063    fn from_arrow_fields_matches_schema_conversion() -> VortexResult<()> {
1064        let session = ArrowSession::default();
1065        let fields = Fields::from(vec![
1066            Field::new("a", DataType::Int32, false),
1067            Field::new("b", DataType::Utf8View, true),
1068        ]);
1069        let struct_fields = session.from_arrow_fields(&fields)?;
1070        let schema_dtype = session.from_arrow_schema(&Schema::new(fields))?;
1071        let expected = StructFields::from_iter([
1072            ("a", DType::Primitive(PType::I32, Nullability::NonNullable)),
1073            ("b", DType::Utf8(Nullability::Nullable)),
1074        ]);
1075        assert_eq!(struct_fields, expected);
1076        assert_eq!(
1077            schema_dtype,
1078            DType::Struct(struct_fields, Nullability::NonNullable)
1079        );
1080        Ok(())
1081    }
1082
1083    #[test]
1084    fn from_arrow_field_maps_variant_without_importer() -> VortexResult<()> {
1085        let session = ArrowSession::default();
1086        let storage = DataType::Struct(
1087            vec![
1088                Field::new("metadata", DataType::BinaryView, false),
1089                Field::new("value", DataType::BinaryView, true),
1090            ]
1091            .into(),
1092        );
1093        let field = Field::new("v", storage, true).with_metadata(
1094            [(
1095                "ARROW:extension:name".to_string(),
1096                "arrow.parquet.variant".to_string(),
1097            )]
1098            .into(),
1099        );
1100        assert_eq!(
1101            session.from_arrow_field(&field)?,
1102            DType::Variant(Nullability::Nullable)
1103        );
1104        Ok(())
1105    }
1106
1107    static REJECT_DICTIONARY_ID: CachedId = CachedId::new("test.reject_dictionary");
1108
1109    /// An importer that fails on an Arrow dictionary and imports anything else as its storage.
1110    #[derive(Debug)]
1111    struct DictionaryRejectingImporter;
1112
1113    impl ArrowImportVTable for DictionaryRejectingImporter {
1114        fn arrow_ext_id(&self) -> Id {
1115            *REJECT_DICTIONARY_ID
1116        }
1117
1118        fn from_arrow_field(
1119            &self,
1120            field: &Field,
1121            session: &ArrowSession,
1122        ) -> VortexResult<Option<DType>> {
1123            vortex_ensure!(
1124                !matches!(field.data_type(), DataType::Dictionary(..)),
1125                "an importer must never see a dictionary field, got {}",
1126                field.data_type()
1127            );
1128            session
1129                .from_arrow_datatype(field.data_type(), field.is_nullable().into())
1130                .map(Some)
1131        }
1132
1133        fn from_arrow_array(
1134            &self,
1135            array: ArrowArrayRef,
1136            field: &Field,
1137            _dtype: &DType,
1138            session: &ArrowSession,
1139        ) -> VortexResult<ArrowImport> {
1140            vortex_ensure!(
1141                !matches!(array.data_type(), DataType::Dictionary(..)),
1142                "an importer must never see a dictionary array, got {}",
1143                array.data_type()
1144            );
1145            session
1146                .from_arrow_array(array, field.is_nullable())
1147                .map(ArrowImport::Imported)
1148        }
1149    }
1150
1151    /// An Arrow dictionary imports as a Vortex `Dict` array over the dictionary values, matching
1152    /// the dtype the schema conversion reports. The session peels the dictionary before any
1153    /// importer runs, so a dictionary field named for an importer that fails on dictionaries still
1154    /// imports.
1155    #[rstest]
1156    #[case::plain(None)]
1157    #[case::extension_name(Some(*REJECT_DICTIONARY_ID))]
1158    fn dictionary_imports_as_dict_encoding(#[case] extension_name: Option<Id>) -> VortexResult<()> {
1159        let session = ArrowSession::default();
1160        session.register_importer(Arc::new(DictionaryRejectingImporter));
1161        let dict: ArrowArrayRef = Arc::new(DictionaryArray::<Int32Type>::try_new(
1162            Int32Array::from(vec![0, 1, 0, 1]),
1163            Arc::new(StringArray::from(vec!["a", "b"])),
1164        )?);
1165        let metadata = extension_name
1166            .map(|id| (EXTENSION_TYPE_NAME_KEY.to_string(), id.to_string()))
1167            .into_iter()
1168            .collect();
1169        let field = Field::new("s", dict.data_type().clone(), false).with_metadata(metadata);
1170
1171        let dtype = session.from_arrow_field(&field)?;
1172        assert_eq!(dtype, DType::Utf8(Nullability::NonNullable));
1173
1174        let array = session.from_arrow_array(dict, &field)?;
1175        assert!(array.is::<Dict>(), "expected a Dict encoding, got {array}");
1176        assert_eq!(array.dtype(), &dtype);
1177        assert_arrays_eq!(
1178            array,
1179            VarBinViewArray::from_iter_str(["a", "b", "a", "b"]),
1180            &mut SESSION.create_execution_ctx()
1181        );
1182        Ok(())
1183    }
1184
1185    static TRUNCATE_ID: CachedId = CachedId::new("test.truncate");
1186
1187    /// An importer that drops the last element of every array it is given, then either imports
1188    /// it or declines and hands it back.
1189    #[derive(Debug)]
1190    struct TruncatingImporter {
1191        decline: bool,
1192    }
1193
1194    impl ArrowImportVTable for TruncatingImporter {
1195        fn arrow_ext_id(&self) -> Id {
1196            *TRUNCATE_ID
1197        }
1198
1199        fn from_arrow_field(
1200            &self,
1201            field: &Field,
1202            session: &ArrowSession,
1203        ) -> VortexResult<Option<DType>> {
1204            session
1205                .from_arrow_datatype(field.data_type(), field.is_nullable().into())
1206                .map(Some)
1207        }
1208
1209        fn from_arrow_array(
1210            &self,
1211            array: ArrowArrayRef,
1212            field: &Field,
1213            _dtype: &DType,
1214            session: &ArrowSession,
1215        ) -> VortexResult<ArrowImport> {
1216            let truncated = array.slice(0, array.len() - 1);
1217            if self.decline {
1218                return Ok(ArrowImport::Unsupported(truncated));
1219            }
1220            session
1221                .from_arrow_array(truncated, field.is_nullable())
1222                .map(ArrowImport::Imported)
1223        }
1224    }
1225
1226    fn truncated_field(name: &str, data_type: DataType) -> FieldRef {
1227        Arc::new(
1228            Field::new(name, data_type, false).with_metadata(
1229                [(
1230                    EXTENSION_TYPE_NAME_KEY.to_string(),
1231                    "test.truncate".to_string(),
1232                )]
1233                .into(),
1234            ),
1235        )
1236    }
1237
1238    fn list_with_truncated_child() -> ArrowArrayRef {
1239        Arc::new(GenericListArray::<i32>::new(
1240            truncated_field("item", DataType::Int64),
1241            OffsetBuffer::new(vec![0, 5].into()),
1242            Arc::new(Int64Array::from_iter_values(0..5)),
1243            None,
1244        ))
1245    }
1246
1247    fn list_view_with_truncated_child() -> ArrowArrayRef {
1248        Arc::new(GenericListViewArray::<i32>::new(
1249            truncated_field("item", DataType::Int64),
1250            ScalarBuffer::from(vec![0]),
1251            ScalarBuffer::from(vec![5]),
1252            Arc::new(Int64Array::from_iter_values(0..5)),
1253            None,
1254        ))
1255    }
1256
1257    fn map_with_truncated_child() -> ArrowArrayRef {
1258        let key_field = Arc::new(Field::new("key", DataType::Int64, false));
1259        let value_field = Arc::new(Field::new("value", DataType::Int64, false));
1260        let entries = StructArray::new(
1261            Fields::from(vec![key_field, value_field]),
1262            vec![
1263                Arc::new(Int64Array::from_iter_values(0..5)),
1264                Arc::new(Int64Array::from_iter_values(5..10)),
1265            ],
1266            None,
1267        );
1268        Arc::new(MapArray::new(
1269            truncated_field("entries", entries.data_type().clone()),
1270            OffsetBuffer::new(vec![0, 5].into()),
1271            entries,
1272            None,
1273            false,
1274        ))
1275    }
1276
1277    #[rstest]
1278    #[case::list(list_with_truncated_child())]
1279    #[case::list_view(list_view_with_truncated_child())]
1280    #[case::map(map_with_truncated_child())]
1281    fn test_rejects_importer_that_changes_child_length(
1282        #[case] array: ArrowArrayRef,
1283        #[values(false, true)] decline: bool,
1284    ) {
1285        let session = ArrowSession::default();
1286        session.register_importer(Arc::new(TruncatingImporter { decline }));
1287
1288        let err = session
1289            .from_arrow_array(array, false)
1290            .expect_err("a child importer that drops elements must be rejected");
1291        assert!(
1292            err.to_string()
1293                .contains("returned 4 elements for an array of 5"),
1294            "unexpected error: {err}"
1295        );
1296    }
1297}