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