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. [`ArrowImportVTable`] states when an importer may defer.
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::GenericListArray;
34use arrow_array::GenericListViewArray;
35use arrow_array::OffsetSizeTrait;
36use arrow_array::RecordBatch;
37use arrow_array::cast::AsArray;
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 vortex_array::ArrayRef;
45use vortex_array::ExecutionCtx;
46use vortex_array::IntoArray;
47use vortex_array::arrays::ExtensionArray;
48use vortex_array::arrays::FixedSizeListArray;
49use vortex_array::arrays::ListArray;
50use vortex_array::arrays::ListViewArray;
51use vortex_array::arrays::StructArray;
52use vortex_array::dtype::DType;
53use vortex_array::dtype::FieldName;
54use vortex_array::dtype::FieldNames;
55use vortex_array::dtype::IntegerPType;
56use vortex_array::dtype::NativePType;
57use vortex_array::dtype::Nullability;
58use vortex_array::dtype::StructFields;
59use vortex_array::dtype::extension::ExtDTypeRef;
60use vortex_array::dtype::extension::ExtId;
61use vortex_array::dtype::session::DTypeSession;
62use vortex_array::dtype::session::DTypeSessionExt;
63use vortex_array::dtype::session::ExtDTypeRegistry;
64use vortex_array::extension::datetime::AnyTemporal;
65use vortex_array::validity::Validity;
66use vortex_error::VortexResult;
67use vortex_error::vortex_bail;
68use vortex_error::vortex_ensure;
69use vortex_error::vortex_ensure_eq;
70use vortex_error::vortex_err;
71use vortex_session::ArcSwapMap;
72use vortex_session::SessionExt;
73use vortex_session::SessionGuard;
74use vortex_session::SessionVar;
75use vortex_session::registry::Id;
76
77use crate::ArrowExportOptions;
78use crate::IntoVortexArray;
79use crate::convert::from_arrow_dyn;
80use crate::convert::import_dictionary;
81use crate::convert::map_from_arrow_parts;
82use crate::convert::trim_map_entries;
83use crate::convert::trim_offsets;
84use crate::dtype::from_arrow_data_type;
85use crate::dtype::to_data_type_naive;
86use crate::ext_metadata::decode_arrow_ext_metadata;
87use crate::ext_metadata::encode_arrow_ext_metadata;
88use crate::import_nullability::level_validity;
89use crate::import_nullability::storage_import_field;
90use crate::run_end_import::run_end_from_arrow_dyn;
91
92/// Outcome of a successful call to [`ArrowExportVTable::execute_arrow`].
93///
94/// Plugins that don't handle the supplied array return [`Unsupported`][Self::Unsupported]
95/// with ownership of the input so the session can probe the next plugin or fall back to the
96/// canonical path. Errors are propagated through [`VortexResult`].
97pub enum ArrowExport {
98    /// The plugin does not handle this input; the session may try another plugin.
99    Unsupported(ArrayRef),
100    /// A successful export.
101    Exported(ArrowArrayRef),
102}
103
104/// Outcome of a successful call to [`ArrowImportVTable::from_arrow_array`].
105///
106/// A plugin that defers the supplied array returns [`Unsupported`][Self::Unsupported] with
107/// ownership of the input so the session can probe the next plugin or fall back to the canonical
108/// path. [`ArrowImportVTable`] states when a plugin may defer. Errors are propagated through
109/// [`VortexResult`].
110pub enum ArrowImport {
111    /// The plugin defers this input; the session may try another plugin.
112    Unsupported(ArrowArrayRef),
113    /// A successful import.
114    Imported(ArrayRef),
115}
116
117/// The Arrow type description of an array being imported by [`ArrowSession::from_arrow_array`].
118///
119/// Callers holding an Arrow [`Field`] (or [`FieldRef`]) should pass it: its
120/// `ARROW:extension:name` metadata is what dispatches the array to a registered
121/// [`ArrowImportVTable`].
122///
123/// An Arrow array can carry a validity (null) buffer regardless of whether its schema declares
124/// the field nullable, so when no [`Field`] is in hand the caller passes the desired nullability
125/// instead, as a [`bool`] or a [`Nullability`]. An anonymous field is then synthesized from the
126/// array's own data type, which means no extension plugin is dispatched for the array itself;
127/// fields nested inside container data types still carry their metadata and are routed through
128/// their importers.
129pub trait IntoArrowField<'a> {
130    /// Resolve to the Arrow [`Field`] describing an array of `data_type`.
131    fn into_arrow_field(self, data_type: &DataType) -> Cow<'a, Field>;
132}
133
134impl<'a> IntoArrowField<'a> for &'a Field {
135    fn into_arrow_field(self, _data_type: &DataType) -> Cow<'a, Field> {
136        Cow::Borrowed(self)
137    }
138}
139
140impl<'a> IntoArrowField<'a> for &'a FieldRef {
141    fn into_arrow_field(self, _data_type: &DataType) -> Cow<'a, Field> {
142        Cow::Borrowed(self.as_ref())
143    }
144}
145
146impl<'a> IntoArrowField<'a> for bool {
147    fn into_arrow_field(self, data_type: &DataType) -> Cow<'a, Field> {
148        Cow::Owned(Field::new("", data_type.clone(), self))
149    }
150}
151
152impl<'a> IntoArrowField<'a> for Nullability {
153    fn into_arrow_field(self, data_type: &DataType) -> Cow<'a, Field> {
154        self.is_nullable().into_arrow_field(data_type)
155    }
156}
157
158/// Plugin layer for exporting a Vortex array to an Arrow extension type.
159///
160/// A successful export **must** preserve the logical value of each row, including nulls. The
161/// physical layout can change. For example, a UUID stored as a fixed-size list of 16 bytes can
162/// export as Arrow `FixedSizeBinary(16)` with the same bytes.
163///
164/// Importing an inferred field with [`ArrowSession::from_arrow_field`] **must** recover the
165/// complete Vortex dtype passed to [`ArrowSession::to_arrow_field`], including extension IDs,
166/// metadata, storage, and nullability at every nesting level. Exporting and importing an array
167/// with that field **must** recover the original dtype and values. Several Arrow representations
168/// can import as the same Vortex dtype.
169///
170/// Prefer [`crate::ArrowExtVTable`] for automatic Vortex metadata transport.
171///
172/// This is purely an implementation trait, its methods should not be called directly. Instead,
173/// use [`ExecuteArrowExt`] to export an array, and the methods on [`ArrowSession`] to convert a
174/// dtype.
175///
176/// [`ExecuteArrowExt`]: crate::ExecuteArrowExt
177pub trait ArrowExportVTable: 'static + Send + Sync + Debug {
178    /// The Arrow extension ID this plugin produces.
179    fn arrow_ext_id(&self) -> Id;
180
181    /// The Vortex array or extension ID this plugin maps from. Used only for inference by
182    /// [`ArrowSession::to_arrow_field`] / [`ArrowSession::to_arrow_schema`]; never as a
183    /// dispatch key for [`execute_arrow`][Self::execute_arrow].
184    fn vortex_id(&self) -> Id;
185
186    /// Build the Arrow [`Field`] this plugin produces for the given Vortex extension
187    /// `dtype`. Used during schema inference.
188    fn to_arrow_field(
189        &self,
190        name: &str,
191        dtype: &DType,
192        session: &ArrowSession,
193    ) -> VortexResult<Option<Field>>;
194
195    /// Convert a Vortex array into an Arrow array shaped to `target`.
196    ///
197    /// Returns ownership of `array` via [`ArrowExport::Unsupported`] when the plugin cannot
198    /// handle the input. Plugins that export child or storage arrays must pass `options` on to
199    /// those exports, through [`ExecuteArrowExt::execute_arrow_with_options`]. The [`ArrowSession`]
200    /// of `ctx` is the session of the export, so a plugin that needs one must use it.
201    ///
202    /// # Exported values
203    ///
204    /// Every export **must** preserve the nulls of `array`.
205    ///
206    /// If `array` has an extension dtype and the output type supports the Arrow comparison kernels,
207    /// the export **must** preserve equality and order. Two non-null exported values compare the
208    /// same way in Arrow as their storage values compare in Vortex. Nested Arrow types only have
209    /// the null requirement.
210    ///
211    /// The comparison rule holds across batches in one Arrow representation. To push a comparison
212    /// down to Vortex storage, an engine also needs to know that both operands use compatible
213    /// representations. Two exporters can each preserve order and still encode equal storage
214    /// values differently. A round trip alone does not even ensure that one exporter preserves
215    /// order. An exporter can reverse the bytes of each value and undo that change on import.
216    ///
217    /// A plugin that breaks these rules gives incorrect query results instead of an error. It does
218    /// not cause memory unsafety. `test_harness::check_arrow` checks both rules for one array.
219    ///
220    /// [`ExecuteArrowExt::execute_arrow_with_options`]: crate::ExecuteArrowExt::execute_arrow_with_options
221    fn execute_arrow(
222        &self,
223        array: ArrayRef,
224        target: &Field,
225        options: &ArrowExportOptions,
226        ctx: &mut ExecutionCtx,
227    ) -> VortexResult<ArrowExport>;
228}
229
230/// Plugin layer for importing an Arrow extension-typed array into a Vortex array.
231///
232/// A successful import **must** preserve each logical Arrow value as described by the field,
233/// applying the [import nullability rules](ArrowSession::from_arrow_array) at each level.
234/// The returned array must have the dtype inferred from the field, as checked by [`ArrowSession`].
235/// See [`ArrowExportVTable`] for the Vortex-to-Arrow round-trip contract.
236///
237/// Prefer [`crate::ArrowExtVTable`] for automatic Vortex metadata transport.
238///
239/// Plugins are dispatched by `arrow_ext_id`. The session peels Arrow dictionaries before it
240/// dispatches. The session uses the dictionary field's metadata to import the values because
241/// Arrow gives dictionary values a bare [`DataType`]. It then wraps the imported values in a
242/// [`vortex_array::arrays::DictArray`] with the dictionary's codes. Run-end values carry their
243/// own [`Field`] and metadata.
244///
245/// A plugin **must** defer only an input that another plugin under the same Arrow extension name
246/// owns, by returning `None` from [`from_arrow_field`][Self::from_arrow_field] or
247/// [`ArrowImport::Unsupported`] from [`from_arrow_array`][Self::from_arrow_array]. An input that no
248/// plugin takes imports as plain storage and loses its type, so a field or array that names the
249/// plugin's type but falls outside its domain is an error instead. The `arrow.parquet.variant`
250/// importer is the known exception: it still defers a variant array that is not a struct.
251///
252/// Arrow stores dictionary values as a bare [`DataType`], so their extension metadata lives on
253/// the outer [`Field`]. Peeling the dictionary lets the importer see the value type described by
254/// that metadata. [`DataType::RunEndEncoded`] has a separate values field that can carry its own
255/// extension metadata, so its values use the normal nested-field import path.
256///
257/// This is purely an implementation trait, its methods should not be called directly. Instead,
258/// use the methods on [`ArrowSession`].
259pub trait ArrowImportVTable: 'static + Send + Sync + Debug {
260    /// The Arrow extension name this plugin handles.
261    fn arrow_ext_id(&self) -> Id;
262
263    /// Build the Vortex [`DType`] that corresponds to `field` (which carries this plugin's
264    /// Arrow extension metadata), or `None` to defer it.
265    ///
266    /// `session` is provided so plugins can resolve nested or storage fields through the
267    /// plugin-aware conversion (e.g. [`ArrowSession::from_arrow_datatype`]) instead of the
268    /// naive Arrow → Vortex mapping.
269    #[allow(clippy::wrong_self_convention)]
270    fn from_arrow_field(
271        &self,
272        field: &Field,
273        session: &ArrowSession,
274    ) -> VortexResult<Option<DType>>;
275
276    /// Convert an Arrow array into a Vortex array of `dtype`.
277    ///
278    /// Returns ownership of `array` via [`ArrowImport::Unsupported`] to defer it.
279    ///
280    /// The importer receives the Arrow nulls as supplied. It **must** apply the
281    /// [import nullability rules](ArrowSession::from_arrow_array) to each level it converts.
282    /// Use [`ArrowSession::from_arrow_storage`] when the Arrow layout matches the storage layout
283    /// of `dtype`. When importing storage with another layout, pass a nullability to
284    /// [`ArrowSession::from_arrow_array`] to avoid dispatching this plugin again.
285    #[allow(clippy::wrong_self_convention)]
286    fn from_arrow_array(
287        &self,
288        array: ArrowArrayRef,
289        field: &Field,
290        dtype: &DType,
291        session: &ArrowSession,
292    ) -> VortexResult<ArrowImport>;
293}
294
295pub type ArrowExportVTableRef = Arc<dyn ArrowExportVTable>;
296pub type ArrowImportVTableRef = Arc<dyn ArrowImportVTable>;
297
298/// Registry of Arrow exporters, keyed by target Arrow extension [`Id`].
299type ArrowExporterRegistry = ArcSwapMap<Id, Arc<[ArrowExportVTableRef]>>;
300/// Registry of Arrow exporters, keyed by source Vortex extension [`ExtId`].
301type VortexExporterRegistry = ArcSwapMap<ExtId, Arc<[ArrowExportVTableRef]>>;
302/// Registry of Arrow importers, keyed by source Arrow extension [`Id`].
303type ArrowImporterRegistry = ArcSwapMap<Id, Arc<[ArrowImportVTableRef]>>;
304
305/// Session-scoped registry of Arrow extension plugins.
306///
307/// The session checks inferred fields and the dtypes of successful plugin imports. See
308/// [`ArrowExportVTable`] and [`ArrowImportVTable`] for the conversion contracts. The importing
309/// session must register the owning dtype and any Arrow plugins used for the conversion.
310///
311/// An Arrow reader observes exported values before any Vortex importer runs.
312/// [`ArrowExportVTable::execute_arrow`] defines the null and comparison rules for those values.
313///
314/// Explicit export targets may request a different dtype. Unknown Vortex IDs import as storage.
315///
316/// A plugin converts one Vortex extension type to and from an Arrow extension type. The crate that
317/// owns the type registers its plugin, as `vortex-uuid` does. Temporal types need no plugin,
318/// because Arrow has native types for them.
319///
320/// Every [`ArrowSession`] belongs to a [`VortexSession`], which creates it on first use of
321/// [`ArrowSessionExt::arrow`]. An export takes no session, because it uses the session of its
322/// [`ExecutionCtx`] (see [`ExecuteArrowExt`]). So one export cannot mix the plugins of two sessions.
323///
324/// An extension type without a plugin exports as its storage, and the Arrow field records the type
325/// so that an import can restore it. `ARROW:extension:name` holds the Vortex ID, and
326/// `ARROW:extension:metadata` holds the metadata in base64, since Arrow metadata must be UTF-8
327/// ([`ext_metadata`] describes the format). DataFusion compares this metadata when it merges file
328/// schemas, so [`ExtDTypeRef::serialize_metadata`] must give equal bytes for equal types.
329///
330/// A caller can also export an array to a field that names its Vortex ID, such as a field from
331/// [`Self::to_arrow_storage_field`]. The export then checks that the field describes the type of
332/// the array. Registered importers read the field's metadata in the plugin's format and must infer
333/// the same dtype apart from outer nullability. Without a matching importer, the metadata must
334/// decode to the bytes returned by [`ExtDTypeRef::serialize_metadata`]. Its Arrow type must also
335/// import as the storage type (or as the type itself, such as an Arrow timestamp). Nested extension
336/// types count as their storage types in this check, and the export checks each nested field when
337/// it reaches it. Without these checks, values could silently change meaning, such as milliseconds
338/// that read back as seconds. For the same reason, an extension array cannot export to a field that
339/// names a different known Vortex ID.
340///
341/// On import, the plugins run first. If none applies, a field that names a known Vortex ID imports
342/// as that type over its storage, and a field with any other name imports as plain storage. A
343/// Vortex ID is known if its type is registered in the [`DTypeSession`] of the same
344/// [`VortexSession`], even after the first use of the Arrow session. The Arrow session keeps the
345/// registry of the [`DTypeSession`] that existed at its first use, so it does not see a new
346/// [`DTypeSession`] that later replaces it through [`VortexSession::register`].
347///
348/// A map's entries field only groups the key and value fields. Both dtype and array imports ignore
349/// its extension name so it remains a plain struct. Key and value fields still reach their
350/// importers.
351///
352/// [`ExecuteArrowExt`]: crate::ExecuteArrowExt
353/// [`ext_metadata`]: crate::ext_metadata
354/// [`VortexSession`]: vortex_session::VortexSession
355/// [`VortexSession::register`]: vortex_session::VortexSession::register
356#[derive(Clone, Debug)]
357pub struct ArrowSession {
358    exporters: ArrowExporterRegistry,
359    exporters_by_vortex: VortexExporterRegistry,
360    importers: ArrowImporterRegistry,
361    /// The extension dtypes that the session can look up by Vortex ID. This is the registry of a
362    /// [`DTypeSession`], so dtypes that are registered there later are also found.
363    ext_dtypes: ExtDTypeRegistry,
364}
365
366impl ArrowSession {
367    /// Create a session without plugins that can look up the extension dtypes of `dtype_session`
368    /// by Vortex ID.
369    fn new(dtype_session: &DTypeSession) -> Self {
370        Self {
371            exporters: ArrowExporterRegistry::default(),
372            exporters_by_vortex: VortexExporterRegistry::default(),
373            importers: ArrowImporterRegistry::default(),
374            ext_dtypes: dtype_session.registry().clone(),
375        }
376    }
377
378    /// Register an [`ArrowExportVTable`] under its target Arrow extension Id (for dispatch)
379    /// and its source Vortex extension Id (for schema inference).
380    pub fn register_exporter(&self, exporter: ArrowExportVTableRef) {
381        self.exporters.push(
382            exporter.arrow_ext_id(),
383            ArrowExportVTableRef::clone(&exporter),
384        );
385        self.exporters_by_vortex
386            .push(exporter.vortex_id(), exporter);
387    }
388
389    /// Register an [`ArrowImportVTable`] under its source Arrow extension name.
390    pub fn register_importer(&self, importer: ArrowImportVTableRef) {
391        self.importers.push(importer.arrow_ext_id(), importer);
392    }
393
394    pub(crate) fn exporters(&self, id: &Id) -> Arc<[ArrowExportVTableRef]> {
395        self.exporters.get(id).unwrap_or_else(|| Arc::from([]))
396    }
397
398    fn exporters_by_vortex(&self, id: &Id) -> Arc<[ArrowExportVTableRef]> {
399        self.exporters_by_vortex
400            .get(id)
401            .unwrap_or_else(|| Arc::from([]))
402    }
403
404    fn importers(&self, id: &Id) -> Arc<[ArrowImportVTableRef]> {
405        self.importers.get(id).unwrap_or_else(|| Arc::from([]))
406    }
407
408    /// Build the Arrow [`Field`] for a Vortex [`DType`].
409    ///
410    /// For [`DType::Extension`]s, plugins registered against the extension's `Id`
411    /// are tried in registration order; the first plugin to return `Some(field)` wins.
412    ///
413    /// An extension type without a plugin exports through [`Self::to_arrow_storage_field`].
414    pub fn to_arrow_field(&self, name: &str, dtype: &DType) -> VortexResult<Field> {
415        // Handle the structural encodings, which may have recursive types
416        match dtype {
417            DType::List(elem_dtype, nullability) => {
418                let elem_field = self.to_arrow_field(Field::LIST_FIELD_DEFAULT_NAME, elem_dtype)?;
419                Ok(Field::new_list(name, elem_field, nullability.is_nullable()))
420            }
421            DType::FixedSizeList(elem_dtype, elem_size, nullability) => {
422                let elem_field = self.to_arrow_field(Field::LIST_FIELD_DEFAULT_NAME, elem_dtype)?;
423                Ok(Field::new_fixed_size_list(
424                    name,
425                    elem_field,
426                    (*elem_size).try_into()?,
427                    nullability.is_nullable(),
428                ))
429            }
430            DType::Map(map_dtype, nullability) => {
431                let key = self.to_arrow_field("key", &map_dtype.key_dtype())?;
432                let value = self.to_arrow_field("value", &map_dtype.value_dtype())?;
433                let entries = Field::new_struct("entries", Fields::from(vec![key, value]), false);
434                Ok(Field::new(
435                    name,
436                    DataType::Map(Arc::new(entries), map_dtype.keys_sorted()),
437                    nullability.is_nullable(),
438                ))
439            }
440            DType::Struct(fields, nullability) => {
441                let arrow_fields = Fields::from_iter(
442                    fields
443                        .fields()
444                        .zip(fields.names().iter())
445                        .map(|(field, name)| self.to_arrow_field(name.as_ref(), &field))
446                        .collect::<VortexResult<Vec<_>>>()?,
447                );
448                Ok(Field::new_struct(
449                    name,
450                    arrow_fields,
451                    nullability.is_nullable(),
452                ))
453            }
454            DType::Extension(ext) if !ext.is::<AnyTemporal>() => {
455                match self.to_arrow_field_with_exporter(name, ext)? {
456                    Some(field) => Ok(field),
457                    None => self.to_arrow_storage_field(name, ext),
458                }
459            }
460            DType::Variant(_) => {
461                // TODO(Adam): This currently encodes information about parquet-variant
462                // at this level. Variant's complexity with being an essentially logical type
463                // with multiple physical layout complicates handling this correctly.
464                Ok(Field::new(
465                    name,
466                    DataType::Struct(
467                        vec![
468                            Field::new("metadata", DataType::BinaryView, dtype.is_nullable()),
469                            Field::new("value", DataType::BinaryView, dtype.is_nullable()),
470                        ]
471                        .into(),
472                    ),
473                    dtype.is_nullable(),
474                )
475                .with_metadata([(
476                    EXTENSION_TYPE_NAME_KEY.to_string(),
477                    "arrow.parquet.variant".to_string(),
478                )]))
479            }
480            _ => Ok(Field::new(
481                name,
482                to_data_type_naive(dtype)?,
483                dtype.is_nullable(),
484            )),
485        }
486    }
487
488    /// Build the Arrow [`Schema`] for a Vortex top-level [`DType::Struct`], dispatching
489    /// extension fields through registered export plugins for inference. Nested
490    /// extensions are preserved via [`Self::to_arrow_field`].
491    pub fn to_arrow_schema(&self, dtype: &DType) -> VortexResult<Schema> {
492        let DType::Struct(struct_dtype, _) = dtype else {
493            vortex_bail!("to_arrow_schema requires a top-level struct dtype, got {dtype}");
494        };
495        let mut fields = Vec::with_capacity(struct_dtype.names().len());
496        for (name, field_dtype) in struct_dtype.names().iter().zip(struct_dtype.fields()) {
497            fields.push(self.to_arrow_field(name.as_ref(), &field_dtype)?);
498        }
499        Ok(Schema::new(fields))
500    }
501
502    /// Returns the Arrow [`DataType`] that best corresponds to the given Vortex [`DType`],
503    /// dispatching [`DType::Extension`]s through registered export plugins.
504    ///
505    /// A [`DataType`] has no field metadata, so this fails for the same types that
506    /// [`Self::default_arrow_export_field`] rejects. Use [`Self::to_arrow_field`] to keep the
507    /// extension type.
508    pub fn to_arrow_datatype(&self, dtype: &DType) -> VortexResult<DataType> {
509        Ok(self.default_arrow_export_field(dtype)?.data_type().clone())
510    }
511
512    /// Returns the Arrow [`Field`] that an export without a target field uses.
513    ///
514    /// This is [`Self::to_arrow_field`] with an empty name, except that it fails for a _top-level_
515    /// extension type that does not have a plugin. The caller of an export without a target keeps
516    /// only the Arrow array or its [`DataType`], not this field. So the extension metadata on the
517    /// field would be lost, and with it the extension type. A nested extension type is fine,
518    /// because its child [`Field`] keeps the metadata. A top-level extension type with a plugin
519    /// still exports, but it loses its extension name, as it did before ([#11286]).
520    ///
521    /// [#11286]: https://github.com/vortex-data/vortex/issues/11286
522    pub fn default_arrow_export_field(&self, dtype: &DType) -> VortexResult<Field> {
523        match dtype {
524            DType::Extension(ext) if !ext.is::<AnyTemporal>() => {
525                self.to_arrow_field_with_exporter("", ext)?.ok_or_else(|| {
526                    vortex_err!(
527                        "an Arrow export without a target field needs an extension type with an Arrow plugin, got {ext}"
528                    )
529                })
530            }
531            _ => self.to_arrow_field("", dtype),
532        }
533    }
534
535    /// Returns the Arrow [`Field`] from the first exporter that accepts `ext_dtype`, or `None` if
536    /// no exporter accepts it.
537    fn to_arrow_field_with_exporter(
538        &self,
539        name: &str,
540        ext_dtype: &ExtDTypeRef,
541    ) -> VortexResult<Option<Field>> {
542        let dtype = DType::Extension(ext_dtype.clone());
543
544        for plugin in self.exporters_by_vortex(&ext_dtype.id()).iter() {
545            if let Some(field) = plugin.to_arrow_field(name, &dtype, self)? {
546                // Check the completed field through normal routing because another importer can
547                // take precedence over the exporter that inferred it.
548                vortex_ensure_eq!(
549                    self.from_arrow_field(&field)?,
550                    dtype,
551                    "Arrow field {:?} must preserve its Vortex dtype",
552                    name
553                );
554
555                return Ok(Some(field));
556            }
557        }
558
559        Ok(None)
560    }
561
562    /// Returns the storage field of `ext_dtype`, with field metadata that holds the extension type
563    /// ([`ext_metadata`] describes the format).
564    ///
565    /// A type with its own Arrow type can also export to this field, for example to export a
566    /// timestamp column as `Int64` and import it back as a timestamp.
567    ///
568    /// Fails if the storage field already has an Arrow extension name.
569    ///
570    /// [`ext_metadata`]: crate::ext_metadata
571    pub fn to_arrow_storage_field(
572        &self,
573        name: &str,
574        ext_dtype: &ExtDTypeRef,
575    ) -> VortexResult<Field> {
576        let mut field = self.to_arrow_field(name, ext_dtype.storage_dtype())?;
577        if let Some(storage_name) = field.extension_type_name() {
578            vortex_bail!(
579                "the Arrow storage of {ext_dtype} must not be an Arrow extension type, got {storage_name}"
580            );
581        }
582
583        field
584            .metadata_mut()
585            .extend(encode_arrow_ext_metadata(ext_dtype)?);
586
587        Ok(field)
588    }
589
590    /// Returns whether an export of `ext_dtype` to `field` produces exactly its storage.
591    ///
592    /// A caller can use the answer to plan reads into the storage without the array. The export
593    /// produces the storage only when `field` names the Vortex ID of `ext_dtype` and passes the
594    /// checks that the [`ArrowSession`] docs describe for such a field. A registered exporter can
595    /// produce any data for the same field, so a name with an exporter gives `false`.
596    ///
597    /// The answer covers only the top level of `field`. Each storage child exports to its own
598    /// field, which can name another exporter. [`Self::exports_without_plugins`] checks for
599    /// exporters at every depth.
600    #[expect(clippy::disallowed_methods, reason = "interning a dynamic id")]
601    pub fn exports_extension_storage(&self, ext_dtype: &ExtDTypeRef, field: &Field) -> bool {
602        // A dictionary or run-end encoded field holds the storage values behind an encoding, so
603        // its Arrow data is not the storage, even though it can import as the storage dtype.
604        if matches!(
605            field.data_type(),
606            DataType::Dictionary(..) | DataType::RunEndEncoded(..)
607        ) {
608            return false;
609        }
610
611        let Some(name) = field.extension_type_name() else {
612            return false;
613        };
614        let id = Id::new(name);
615
616        // The export tries the registered exporters before the storage route.
617        if !self.exporters(&id).is_empty() {
618            return false;
619        }
620
621        // The storage route needs a name that the session resolves to the Vortex ID of
622        // `ext_dtype`. The name can be an alias of that ID.
623        if self.known_vortex_id(&id) != Some(ext_dtype.id()) {
624            return false;
625        }
626
627        // The export fails unless the field describes `ext_dtype`.
628        if self.ensure_ext_storage_metadata(ext_dtype, field).is_err() {
629            return false;
630        }
631
632        // The export also accepts some Arrow types that import as another dtype, such as an Arrow
633        // timestamp, which imports as the extension type itself. Only an exact match means that
634        // the Arrow data has the type of the storage.
635        self.from_arrow_datatype(field.data_type(), ext_dtype.nullability())
636            .is_ok_and(|dtype| &dtype == ext_dtype.storage_dtype())
637    }
638
639    /// Returns whether exporting to `field` uses only the built-in conversions at every depth.
640    ///
641    /// A registered exporter can choose the Arrow representation even if the field also supports
642    /// a built-in conversion. The answer is conservative because the plugin can defer at runtime.
643    pub fn exports_without_plugins(&self, field: &Field) -> bool {
644        !field_uses_plugin(field, &|id| !self.exporters(id).is_empty())
645    }
646
647    /// Returns whether importing from `field` uses only the built-in conversions at every depth.
648    ///
649    /// A registered importer can transform values before Vortex sees them, even if the outer field
650    /// has no extension name.
651    pub fn imports_without_plugins(&self, field: &Field) -> bool {
652        !field_uses_plugin(field, &|id| !self.importers(id).is_empty())
653    }
654
655    /// Fails unless `field`, which names the Vortex ID of `ext_dtype`, describes `ext_dtype`.
656    ///
657    /// An importer that recognizes `field` reads its metadata in the plugin's format, so the check
658    /// asks the importer first, as [`Self::infer_field_dtype_with_importers`] explains. Without
659    /// one, the field must carry the metadata of `ext_dtype`.
660    pub(crate) fn ensure_ext_storage_metadata(
661        &self,
662        ext_dtype: &ExtDTypeRef,
663        field: &Field,
664    ) -> VortexResult<()> {
665        let Some(importer_dtype) = self.infer_field_dtype_with_importers(field)? else {
666            return ensure_ext_metadata(field, &decode_arrow_ext_metadata(field)?, ext_dtype);
667        };
668
669        vortex_ensure_eq!(
670            importer_dtype.as_nullable(),
671            DType::Extension(ext_dtype.with_nullability(Nullability::Nullable)),
672            "Arrow field {:?} must describe the source extension type",
673            field.name()
674        );
675
676        Ok(())
677    }
678
679    /// Returns the Vortex ID that the extension name `id` resolves to, or `None` if the session does
680    /// not know it. The registry can hold an alias, so the result can differ from `id`.
681    pub(crate) fn known_vortex_id(&self, id: &Id) -> Option<ExtId> {
682        self.ext_dtypes
683            .get(id)
684            .map(|ext_dtype_plugin| ext_dtype_plugin.id())
685    }
686
687    /// Returns the extension type that `field` names by Vortex ID, to wrap around `storage_dtype`.
688    ///
689    /// Returns `None` if the session does not know that Vortex ID, or if `storage_dtype` already is
690    /// that type, such as an Arrow timestamp that names `vortex.timestamp`. Fails if the metadata
691    /// of `field` does not fit the type.
692    fn ext_dtype_to_wrap(
693        &self,
694        field: &Field,
695        storage_dtype: &DType,
696    ) -> VortexResult<Option<ExtDTypeRef>> {
697        let Some(extension_name) = field.extension_type_name() else {
698            return Ok(None);
699        };
700        #[expect(clippy::disallowed_methods, reason = "interning a dynamic id")]
701        let Some(ext_dtype_plugin) = self.ext_dtypes.get(&Id::new(extension_name)) else {
702            return Ok(None);
703        };
704        let metadata = decode_arrow_ext_metadata(field)?;
705
706        // Wrapping a storage that already is the type would nest the type inside itself.
707        let existing_ext_dtype = storage_dtype
708            .as_extension_opt()
709            .filter(|ext_dtype| ext_dtype.id() == ext_dtype_plugin.id());
710        if let Some(existing_ext_dtype) = existing_ext_dtype {
711            ensure_ext_metadata(field, &metadata, existing_ext_dtype)?;
712            return Ok(None);
713        }
714
715        ext_dtype_plugin
716            .deserialize(&metadata, storage_dtype.clone())
717            .map(Some)
718    }
719
720    /// Build the Vortex [`DType`] for an Arrow [`Field`].
721    ///
722    /// A [`DataType::Dictionary`] field converts as its value field with the same metadata.
723    ///
724    /// Plugins registered against the field's Arrow extension name are tried in
725    /// registration order; the first plugin to return `Some(dtype)` wins. If no plugin is
726    /// registered, or every plugin defers the field as [`ArrowImportVTable`] allows, the builtin
727    /// `arrow.parquet.variant` extension maps to [`DType::Variant`], and any other field converts
728    /// through [`Self::from_arrow_datatype`] so extension metadata on nested element/struct
729    /// fields is preserved.
730    ///
731    /// If no plugin recognizes `field` and its extension name is a known Vortex ID, the result is
732    /// that extension type over the converted storage (see [`ArrowSession`]).
733    pub fn from_arrow_field(&self, field: &Field) -> VortexResult<DType> {
734        if let DataType::Dictionary(_, value_type) = field.data_type() {
735            return self
736                .from_arrow_field(&field.clone().with_data_type(value_type.as_ref().clone()));
737        }
738
739        if let Some(dtype) = self.infer_field_dtype_with_importers(field)? {
740            return Ok(dtype);
741        }
742
743        // Parquet Variant is understood even without a registered importer plugin.
744        if field.extension_type_name() == Some("arrow.parquet.variant") {
745            return Ok(DType::Variant(field.is_nullable().into()));
746        }
747
748        let storage_dtype =
749            self.from_arrow_datatype(field.data_type(), field.is_nullable().into())?;
750
751        Ok(match self.ext_dtype_to_wrap(field, &storage_dtype)? {
752            Some(ext_dtype) => DType::Extension(ext_dtype),
753            None => storage_dtype,
754        })
755    }
756
757    /// Returns the dtype that the importers registered for the extension name of `field` infer.
758    ///
759    /// Returns `None` if `field` has no extension name or if no importer recognizes it.
760    ///
761    /// An importer owns the format of its Arrow metadata, which can differ from the Vortex wire
762    /// metadata of the same type. For example, a plugin can store unmarked base64, which
763    /// [`decode_arrow_ext_metadata`] reads as UTF-8 text. So import and export both ask the
764    /// importer which type a field describes before they compare any metadata bytes.
765    #[expect(clippy::disallowed_methods, reason = "interning a dynamic id")]
766    pub(crate) fn infer_field_dtype_with_importers(
767        &self,
768        field: &Field,
769    ) -> VortexResult<Option<DType>> {
770        let Some(name) = field.extension_type_name() else {
771            return Ok(None);
772        };
773
774        for plugin in self.importers(&Id::new(name)).iter() {
775            let dtype = plugin.from_arrow_field(field, self).map_err(|err| {
776                err.with_context(format!(
777                    "Failed to import Arrow field {:?} as {name}",
778                    field.name()
779                ))
780            })?;
781            if let Some(dtype) = dtype {
782                return Ok(Some(dtype));
783            }
784        }
785
786        Ok(None)
787    }
788
789    /// Build the Vortex [`DType`] for an Arrow [`DataType`].
790    ///
791    /// Recurses into container types ([`DataType::List`] family, [`DataType::FixedSizeList`],
792    /// [`DataType::Struct`], [`DataType::Map`], [`DataType::RunEndEncoded`]) via
793    /// [`Self::from_arrow_field`] so extension metadata on nested fields dispatches through
794    /// registered import plugins. Leaf types use the canonical Arrow → Vortex mapping.
795    ///
796    /// [`DataType::Dictionary`] is a partial exception: Arrow models its values as a bare
797    /// [`DataType`] rather than a [`Field`], so the values themselves cannot carry an extension
798    /// name. Fields nested *inside* that data type still do, and are dispatched normally.
799    pub fn from_arrow_datatype(
800        &self,
801        data_type: &DataType,
802        nullability: Nullability,
803    ) -> VortexResult<DType> {
804        Ok(match data_type {
805            DataType::List(elem)
806            | DataType::LargeList(elem)
807            | DataType::ListView(elem)
808            | DataType::LargeListView(elem) => {
809                DType::List(Arc::new(self.from_arrow_field(elem.as_ref())?), nullability)
810            }
811            DataType::FixedSizeList(elem, size) => DType::FixedSizeList(
812                Arc::new(self.from_arrow_field(elem.as_ref())?),
813                *size as u32,
814                nullability,
815            ),
816            DataType::Map(entries, keys_sorted) => {
817                vortex_ensure!(
818                    !entries.is_nullable(),
819                    "Arrow map entries field must be non-nullable"
820                );
821                let DataType::Struct(fields) = entries.data_type() else {
822                    vortex_bail!(
823                        "Arrow map entries field must have Struct type, got {:?}",
824                        entries.data_type()
825                    );
826                };
827                vortex_ensure_eq!(
828                    fields.len(),
829                    2,
830                    "Arrow map entries struct must contain exactly two fields"
831                );
832                vortex_ensure!(
833                    !fields[0].is_nullable(),
834                    "Arrow map key field must be non-nullable"
835                );
836                DType::map(
837                    self.from_arrow_field(fields[0].as_ref())?,
838                    self.from_arrow_field(fields[1].as_ref())?,
839                    *keys_sorted,
840                    nullability,
841                )?
842            }
843            DataType::Struct(fields) => DType::Struct(self.from_arrow_fields(fields)?, nullability),
844            DataType::Dictionary(_, value_type) => {
845                self.from_arrow_datatype(value_type.as_ref(), nullability)?
846            }
847            DataType::RunEndEncoded(_, value_field) => {
848                self.from_arrow_field(&run_end_values_field(value_field, nullability))?
849            }
850            _ => from_arrow_data_type(data_type, nullability)?,
851        })
852    }
853
854    /// Build Vortex [`StructFields`] for Arrow [`Fields`], dispatching each field through
855    /// [`Self::from_arrow_field`].
856    pub fn from_arrow_fields(&self, fields: &Fields) -> VortexResult<StructFields> {
857        fields
858            .iter()
859            .map(|f| {
860                self.from_arrow_field(f)
861                    .map(|dt| (FieldName::from(f.name().as_str()), dt))
862            })
863            .collect::<VortexResult<StructFields>>()
864    }
865
866    /// Build the Vortex [`DType`] for an Arrow [`Schema`], dispatching extension fields
867    /// through registered import plugins. The result is a top-level non-nullable struct
868    /// matching the schema's fields.
869    pub fn from_arrow_schema(&self, schema: &Schema) -> VortexResult<DType> {
870        Ok(DType::Struct(
871            self.from_arrow_fields(schema.fields())?,
872            Nullability::NonNullable,
873        ))
874    }
875
876    /// Decode an Arrow [`RecordBatch`] into a Vortex struct array, dispatching each
877    /// extension column through its registered import plugin.
878    ///
879    /// `schema` is the authoritative Arrow schema used for dispatch — the columns are
880    /// consumed positionally. Pass an external schema (rather than relying on
881    /// `batch.schema()`) when upstream DataFusion plumbing may have stripped Field-level
882    /// extension metadata from the runtime RecordBatch.
883    pub fn from_arrow_record_batch(
884        &self,
885        batch: RecordBatch,
886        schema: &Schema,
887    ) -> VortexResult<ArrayRef> {
888        vortex_ensure_eq!(batch.num_columns(), schema.fields().len());
889        let length = batch.num_rows();
890        let names = FieldNames::from_iter(
891            schema
892                .fields()
893                .iter()
894                .map(|f| FieldName::from(f.name().as_str())),
895        );
896        let mut columns = Vec::with_capacity(schema.fields().len());
897        for (col, field) in batch.columns().iter().zip(schema.fields().iter()) {
898            columns.push(self.from_arrow_array_inner(ArrowArrayRef::clone(col), field)?);
899        }
900        Ok(StructArray::try_new(names, columns, length, Validity::NonNullable)?.into_array())
901    }
902
903    /// Decode an Arrow array into a Vortex array.
904    ///
905    /// Pass a [`Field`] to supply the Arrow schema and its extension metadata. Pass a `bool`
906    /// or [`Nullability`] to use the array's data type and set the root nullability. See
907    /// [`IntoArrowField`].
908    ///
909    /// For a field with a registered Arrow extension name, the session tries its importers in
910    /// registration order until one handles the array or all return [`ArrowImport::Unsupported`].
911    /// Nested fields also reach their importers when the session converts a container.
912    ///
913    /// If no plugin imports the array and the extension name of `field` is a known Vortex ID,
914    /// the import wraps the converted storage in that extension type (see [`ArrowSession`]).
915    ///
916    /// Each level follows its own declared nullability. Nullable levels keep their validity.
917    /// Non-nullable storage leaves fill nulls with the zero of their type, such as `0`, `false`,
918    /// or `""`. Non-nullable containers drop their validity and keep their contents, so a null
919    /// list with no elements becomes an empty list. Each child follows its own field, even under
920    /// a null parent row.
921    ///
922    /// The fill uses the storage type's zero even when it falls outside the extension's domain.
923    /// For example, a JSON slot can become `""`.
924    ///
925    /// A non-nullable dictionary imports null keys as references to entry zero. If there are
926    /// keys but no values, the import adds one entry by importing a single null Arrow row of the
927    /// value type under these rules. So a leaf value is its zero, and a struct value is a valid
928    /// row whose nullable fields stay null.
929    /// A run-end encoded array applies the requested nullability to its run values.
930    ///
931    /// # Errors
932    ///
933    /// Returns an error for unsupported Arrow types, including Arrow `Null` with a non-nullable
934    /// request, or if an import plugin rejects the field or array.
935    pub fn from_arrow_array<'a>(
936        &self,
937        array: ArrowArrayRef,
938        field: impl IntoArrowField<'a>,
939    ) -> VortexResult<ArrayRef> {
940        let field = field.into_arrow_field(array.data_type());
941        self.from_arrow_array_inner(array, field.as_ref())
942    }
943
944    /// Import `array`, which holds the Arrow form of the storage of `ext`, as an array of `ext`.
945    ///
946    /// Use this when the Arrow layout matches the Vortex storage layout. The storage dtype
947    /// supplies the nullability of each level for the rules in [`Self::from_arrow_array`].
948    ///
949    /// # Errors
950    ///
951    /// Returns an error if the Arrow layout and the storage dtype differ in field names, field
952    /// order, or types, or if converting the storage fails.
953    pub fn from_arrow_storage(
954        &self,
955        array: ArrowArrayRef,
956        ext: &ExtDTypeRef,
957    ) -> VortexResult<ArrayRef> {
958        let storage_dtype = ext.storage_dtype();
959        let arrow_dtype =
960            self.from_arrow_datatype(array.data_type(), storage_dtype.nullability())?;
961        vortex_ensure!(
962            arrow_dtype.eq_ignore_nullability(storage_dtype),
963            "Arrow storage of {} must convert to {storage_dtype} apart from nullability, got {arrow_dtype}",
964            ext.id()
965        );
966
967        let field = Field::new("", array.data_type().clone(), storage_dtype.is_nullable());
968        let field = storage_import_field(&field, storage_dtype);
969        let storage = self.from_arrow_array_canonical(array, &field)?;
970        Ok(ExtensionArray::try_new(ext.clone(), storage)?.into_array())
971    }
972
973    /// Import a nested array or root array with a resolved Arrow [`Field`].
974    #[allow(clippy::wrong_self_convention)]
975    fn from_arrow_array_inner(
976        &self,
977        array: ArrowArrayRef,
978        field: &Field,
979    ) -> VortexResult<ArrayRef> {
980        if let DataType::Dictionary(_, values_type) = field.data_type() {
981            return self.import_dictionary_values(array.as_ref(), field, values_type);
982        }
983
984        // A plugin import is final, because `from_arrow_array_with_importers` already checked that
985        // it has the dtype inferred from `field`. It must not reach `ext_dtype_to_wrap`, which
986        // reads the metadata of `field` as Vortex wire metadata. A plugin can encode its metadata
987        // differently, so that check would reject a valid array.
988        let storage = match self.from_arrow_array_with_importers(array, field)? {
989            ArrowImport::Imported(imported) => return Ok(imported),
990            ArrowImport::Unsupported(storage) => storage,
991        };
992        let imported = self.from_arrow_array_canonical(storage, field)?;
993
994        match self.ext_dtype_to_wrap(field, imported.dtype())? {
995            Some(ext_dtype) => Ok(ExtensionArray::try_new(ext_dtype, imported)?.into_array()),
996            None => Ok(imported),
997        }
998    }
999
1000    /// Probe registered importers, checking imported dtypes and all returned array lengths.
1001    ///
1002    /// If every plugin declines, return [`ArrowImport::Unsupported`] with the remaining array.
1003    /// Canonical conversion and Vortex ID wrapping belong to [`Self::from_arrow_array_inner`].
1004    #[allow(clippy::wrong_self_convention)]
1005    fn from_arrow_array_with_importers(
1006        &self,
1007        mut array: ArrowArrayRef,
1008        field: &Field,
1009    ) -> VortexResult<ArrowImport> {
1010        if let Some(extension_name) = field.metadata().get(EXTENSION_TYPE_NAME_KEY) {
1011            #[expect(clippy::disallowed_methods, reason = "interning a dynamic id")]
1012            let importers = self.importers(&Id::new(extension_name));
1013            if !importers.is_empty() {
1014                let dtype = self.from_arrow_field(field)?;
1015                let len = array.len();
1016                for plugin in importers.iter() {
1017                    match plugin.from_arrow_array(array, field, &dtype, self)? {
1018                        // Parents such as lists reuse the Arrow offsets into this array without
1019                        // checking them again, so a plugin must preserve its length, both in what
1020                        // it imports and in what it hands back when it declines.
1021                        ArrowImport::Imported(arr) => {
1022                            vortex_ensure_eq!(
1023                                arr.len(),
1024                                len,
1025                                "Arrow importer {} returned {} elements for an array of {}",
1026                                plugin.arrow_ext_id(),
1027                                arr.len(),
1028                                len
1029                            );
1030                            vortex_ensure_eq!(
1031                                arr.dtype(),
1032                                &dtype,
1033                                "Arrow importer must preserve the dtype inferred from its field"
1034                            );
1035
1036                            return Ok(ArrowImport::Imported(arr));
1037                        }
1038                        ArrowImport::Unsupported(arr) => {
1039                            vortex_ensure_eq!(
1040                                arr.len(),
1041                                len,
1042                                "Arrow importer {} declined and returned {} elements for an array of {}",
1043                                plugin.arrow_ext_id(),
1044                                arr.len(),
1045                                len
1046                            );
1047                            array = arr;
1048                        }
1049                    }
1050                }
1051            }
1052        }
1053
1054        Ok(ArrowImport::Unsupported(array))
1055    }
1056
1057    /// Convert an Arrow array using the resolved field's data type and nullability.
1058    ///
1059    /// The caller handles the root extension. Recursive calls still dispatch to importers for
1060    /// nested fields.
1061    #[allow(clippy::wrong_self_convention)]
1062    fn from_arrow_array_canonical(
1063        &self,
1064        array: ArrowArrayRef,
1065        field: &Field,
1066    ) -> VortexResult<ArrayRef> {
1067        match field.data_type() {
1068            DataType::Struct(fields) => {
1069                let arrow_struct = array.as_struct();
1070                let names = FieldNames::from_iter(
1071                    fields.iter().map(|f| FieldName::from(f.name().as_str())),
1072                );
1073                let columns = arrow_struct
1074                    .columns()
1075                    .iter()
1076                    .zip(fields.iter())
1077                    .map(|(col, child_field)| {
1078                        self.from_arrow_array_inner(ArrowArrayRef::clone(col), child_field.as_ref())
1079                    })
1080                    .collect::<VortexResult<Vec<_>>>()?;
1081                let validity = level_validity(arrow_struct.nulls(), field.is_nullable())?;
1082
1083                Ok(
1084                    StructArray::try_new(names, columns, arrow_struct.len(), validity)?
1085                        .into_array(),
1086                )
1087            }
1088            DataType::List(elem_field) => {
1089                self.import_list(array.as_list::<i32>(), elem_field, field.is_nullable())
1090            }
1091            DataType::LargeList(elem_field) => {
1092                self.import_list(array.as_list::<i64>(), elem_field, field.is_nullable())
1093            }
1094            DataType::FixedSizeList(elem_field, list_size) => {
1095                let list = array.as_fixed_size_list();
1096                let elements =
1097                    self.from_arrow_array_inner(ArrowArrayRef::clone(list.values()), elem_field)?;
1098                let validity = level_validity(list.nulls(), field.is_nullable())?;
1099
1100                Ok(
1101                    FixedSizeListArray::try_new(elements, *list_size as u32, validity, list.len())?
1102                        .into_array(),
1103                )
1104            }
1105            DataType::ListView(elem_field) => {
1106                self.import_list_view(array.as_list_view::<i32>(), elem_field, field.is_nullable())
1107            }
1108            DataType::LargeListView(elem_field) => {
1109                self.import_list_view(array.as_list_view::<i64>(), elem_field, field.is_nullable())
1110            }
1111            DataType::Map(entries_field, keys_sorted) => {
1112                let map = array.as_map();
1113                let (entries, offsets) = trim_map_entries(map);
1114
1115                // Match schema import by treating the entries field as a plain struct. Its key
1116                // and value fields still reach their importers.
1117                let entries =
1118                    self.from_arrow_array_canonical(Arc::new(entries), entries_field.as_ref())?;
1119
1120                map_from_arrow_parts(
1121                    entries,
1122                    &offsets,
1123                    map.nulls(),
1124                    *keys_sorted,
1125                    field.is_nullable(),
1126                )
1127            }
1128            DataType::RunEndEncoded(ends_field, values_field) => {
1129                let values_field = run_end_values_field(values_field, field.is_nullable().into());
1130                run_end_from_arrow_dyn(array.as_ref(), ends_field.data_type(), |values| {
1131                    self.from_arrow_array_inner(values, &values_field)
1132                })
1133            }
1134            DataType::Dictionary(_, values_type) => {
1135                self.import_dictionary_values(array.as_ref(), field, values_type)
1136            }
1137            _ => from_arrow_dyn(array.as_ref(), field.is_nullable()),
1138        }
1139    }
1140
1141    fn import_list<O: OffsetSizeTrait + IntegerPType>(
1142        &self,
1143        list: &GenericListArray<O>,
1144        element_field: &Field,
1145        nullable: bool,
1146    ) -> VortexResult<ArrayRef> {
1147        let (offsets, referenced) = trim_offsets(list.offsets());
1148        let values = list.values().slice(referenced.start, referenced.len());
1149        let elements = self.from_arrow_array_inner(values, element_field)?;
1150        let offsets = offsets.into_array();
1151        let validity = level_validity(list.nulls(), nullable)?;
1152
1153        // SAFETY: Arrow supplies at least one non-negative, sorted integer offset. `trim_offsets`
1154        // rebases the offsets to the value slice, whose length the import preserves. The validity
1155        // comes from the same lists.
1156        Ok(unsafe { ListArray::new_unchecked(elements, offsets, validity) }.into_array())
1157    }
1158
1159    fn import_list_view<O: OffsetSizeTrait + NativePType>(
1160        &self,
1161        list: &GenericListViewArray<O>,
1162        element_field: &Field,
1163        nullable: bool,
1164    ) -> VortexResult<ArrayRef> {
1165        let elements =
1166            self.from_arrow_array_inner(ArrowArrayRef::clone(list.values()), element_field)?;
1167        let offsets = list.offsets().clone().into_array();
1168        let sizes = list.sizes().clone().into_array();
1169        let validity = level_validity(list.nulls(), nullable)?;
1170
1171        // SAFETY: Arrow supplies equally sized integer buffers whose ranges lie within the values.
1172        // The import preserves the value count, and the validity comes from the same views.
1173        Ok(
1174            unsafe { ListViewArray::new_unchecked(elements, offsets, sizes, validity) }
1175                .into_array(),
1176        )
1177    }
1178
1179    /// Import the dictionary values with the dictionary field's extension metadata.
1180    fn import_dictionary_values(
1181        &self,
1182        array: &dyn ArrowArray,
1183        field: &Field,
1184        values_type: &DataType,
1185    ) -> VortexResult<ArrayRef> {
1186        let dict = array.as_any_dictionary_opt().ok_or_else(|| {
1187            vortex_err!(
1188                "Arrow dictionary import requires a DictionaryArray, got {}",
1189                array.data_type()
1190            )
1191        })?;
1192
1193        let values_field = field.clone().with_data_type(values_type.clone());
1194
1195        Ok(import_dictionary(dict, field.is_nullable(), |values| {
1196            self.from_arrow_array_inner(values, &values_field)
1197        })?
1198        .into_array())
1199    }
1200}
1201
1202/// The values field of an Arrow [`DataType::RunEndEncoded`], re-stamped with the run-end array's
1203/// own nullability.
1204fn run_end_values_field(values_field: &FieldRef, nullability: Nullability) -> Field {
1205    values_field
1206        .as_ref()
1207        .clone()
1208        .with_nullable(nullability.into())
1209}
1210
1211impl SessionVar for ArrowSession {
1212    fn as_any(&self) -> &dyn Any {
1213        self
1214    }
1215
1216    fn as_any_mut(&mut self) -> &mut dyn Any {
1217        self
1218    }
1219}
1220
1221/// Fails unless `metadata`, the extension metadata of `field`, is the metadata of `ext_dtype`.
1222pub(crate) fn ensure_ext_metadata(
1223    field: &Field,
1224    metadata: &[u8],
1225    ext_dtype: &ExtDTypeRef,
1226) -> VortexResult<()> {
1227    vortex_ensure!(
1228        metadata == ext_dtype.serialize_metadata()?,
1229        "Arrow field {:?} must carry the metadata of {ext_dtype}, got {metadata:?}",
1230        field.name()
1231    );
1232
1233    Ok(())
1234}
1235
1236#[expect(clippy::disallowed_methods, reason = "interning a dynamic id")]
1237fn field_uses_plugin(field: &Field, is_registered: &impl Fn(&Id) -> bool) -> bool {
1238    field
1239        .extension_type_name()
1240        .is_some_and(|name| is_registered(&Id::new(name)))
1241        || child_uses_plugin(field.data_type(), is_registered)
1242}
1243
1244fn child_uses_plugin(data_type: &DataType, is_registered: &impl Fn(&Id) -> bool) -> bool {
1245    match data_type {
1246        DataType::Struct(fields) => fields
1247            .iter()
1248            .any(|field| field_uses_plugin(field, is_registered)),
1249        DataType::Union(fields, _) => fields
1250            .iter()
1251            .any(|(_, field)| field_uses_plugin(field, is_registered)),
1252        DataType::List(field)
1253        | DataType::LargeList(field)
1254        | DataType::ListView(field)
1255        | DataType::LargeListView(field)
1256        | DataType::FixedSizeList(field, _)
1257        | DataType::Map(field, _)
1258        | DataType::RunEndEncoded(_, field) => field_uses_plugin(field, is_registered),
1259        // A dictionary carries its value field's metadata on the outer field, checked above.
1260        DataType::Dictionary(_, values) => child_uses_plugin(values, is_registered),
1261        _ => false,
1262    }
1263}
1264
1265/// Extension trait for accessing the [`ArrowSession`] on a Vortex session.
1266pub trait ArrowSessionExt: SessionExt {
1267    /// Get the Arrow session, creating it on first use.
1268    ///
1269    /// The new session has no plugins, and it can look up the extension types of
1270    /// [`DTypeSessionExt::dtypes`] by Vortex ID.
1271    fn arrow(&self) -> SessionGuard<'_, ArrowSession>;
1272}
1273
1274impl<S: SessionExt> ArrowSessionExt for S {
1275    fn arrow(&self) -> SessionGuard<'_, ArrowSession> {
1276        self.get_or_insert_with(|| ArrowSession::new(&self.dtypes()))
1277    }
1278}
1279
1280#[cfg(test)]
1281mod tests {
1282    use std::ops::Range;
1283    use std::sync::Arc;
1284    use std::sync::LazyLock;
1285
1286    use arrow_array::DictionaryArray;
1287    use arrow_array::FixedSizeListArray as ArrowFixedSizeListArray;
1288    use arrow_array::GenericListArray;
1289    use arrow_array::GenericListViewArray;
1290    use arrow_array::Int32Array;
1291    use arrow_array::Int64Array;
1292    use arrow_array::MapArray;
1293    use arrow_array::StringArray;
1294    use arrow_array::StructArray;
1295    use arrow_array::new_null_array;
1296    use arrow_array::types::Int32Type;
1297    use arrow_buffer::NullBuffer;
1298    use arrow_buffer::OffsetBuffer;
1299    use arrow_buffer::ScalarBuffer;
1300    use arrow_schema::DataType;
1301    use arrow_schema::Field;
1302    use arrow_schema::FieldRef;
1303    use arrow_schema::Fields;
1304    use arrow_schema::Metadata;
1305    use rstest::rstest;
1306    use vortex_array::IntoArray;
1307    use vortex_array::VortexSessionExecute as _;
1308    use vortex_array::arrays::Dict;
1309    use vortex_array::arrays::FixedSizeList;
1310    use vortex_array::arrays::ListArray;
1311    use vortex_array::arrays::PrimitiveArray;
1312    use vortex_array::arrays::StructArray as VortexStructArray;
1313    use vortex_array::arrays::VarBinViewArray;
1314    use vortex_array::arrays::fixed_size_list::FixedSizeListArraySlotsExt;
1315    use vortex_array::assert_arrays_eq;
1316    use vortex_array::dtype::DType;
1317    use vortex_array::dtype::Nullability;
1318    use vortex_array::dtype::PType;
1319    use vortex_array::dtype::extension::ExtDType;
1320    use vortex_array::dtype::extension::ExtVTable;
1321    use vortex_array::scalar::ScalarValue;
1322    use vortex_array::validity::Validity;
1323    use vortex_buffer::buffer;
1324    use vortex_error::VortexResult;
1325    use vortex_session::VortexSession;
1326    use vortex_session::registry::CachedId;
1327
1328    use super::*;
1329
1330    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
1331
1332    #[rstest]
1333    #[case::prefix(0, 2)]
1334    #[case::middle(500, 2)]
1335    #[case::empty(500, 0)]
1336    #[case::empty_at_end(1000, 0)]
1337    fn test_sliced_list_imports_only_its_rows(
1338        #[values(false, true)] large: bool,
1339        #[case] start: usize,
1340        #[case] len: usize,
1341    ) -> VortexResult<()> {
1342        let lists = |rows: Range<i64>| -> ArrowArrayRef {
1343            let values = Arc::new(Int64Array::from_iter_values(
1344                rows.flat_map(|row| [row, row + 1]),
1345            ));
1346            let len = values.len() / 2;
1347            let field = Arc::new(Field::new("item", DataType::Int64, false));
1348            if large {
1349                Arc::new(GenericListArray::<i64>::new(
1350                    field,
1351                    OffsetBuffer::from_repeated_length(2, len),
1352                    values,
1353                    None,
1354                ))
1355            } else {
1356                Arc::new(GenericListArray::<i32>::new(
1357                    field,
1358                    OffsetBuffer::from_repeated_length(2, len),
1359                    values,
1360                    None,
1361                ))
1362            }
1363        };
1364        let session = SESSION.arrow();
1365        let sliced = session.from_arrow_array(lists(0..1000).slice(start, len), false)?;
1366        let fresh = session.from_arrow_array(lists(start as i64..(start + len) as i64), false)?;
1367        assert_eq!(sliced.nbytes(), fresh.nbytes());
1368        let mut ctx = SESSION.create_execution_ctx();
1369        let expected = ListArray::new(
1370            PrimitiveArray::from_iter(
1371                (start as i64..(start + len) as i64).flat_map(|row| [row, row + 1]),
1372            )
1373            .into_array(),
1374            PrimitiveArray::from_iter((0..=len as u64).map(|row| row * 2)).into_array(),
1375            Validity::NonNullable,
1376            &mut ctx,
1377        );
1378        assert_arrays_eq!(sliced, expected, &mut ctx);
1379        assert_arrays_eq!(fresh, expected, &mut ctx);
1380        Ok(())
1381    }
1382
1383    #[test]
1384    fn from_arrow_fields_matches_schema_conversion() -> VortexResult<()> {
1385        let session = SESSION.arrow();
1386        let fields = Fields::from(vec![
1387            Field::new("a", DataType::Int32, false),
1388            Field::new("b", DataType::Utf8View, true),
1389        ]);
1390        let struct_fields = session.from_arrow_fields(&fields)?;
1391        let schema_dtype = session.from_arrow_schema(&Schema::new(fields))?;
1392        let expected = StructFields::from_iter([
1393            ("a", DType::Primitive(PType::I32, Nullability::NonNullable)),
1394            ("b", DType::Utf8(Nullability::Nullable)),
1395        ]);
1396        assert_eq!(struct_fields, expected);
1397        assert_eq!(
1398            schema_dtype,
1399            DType::Struct(struct_fields, Nullability::NonNullable)
1400        );
1401        Ok(())
1402    }
1403
1404    #[test]
1405    fn from_arrow_field_maps_variant_without_importer() -> VortexResult<()> {
1406        let session = SESSION.arrow();
1407        let storage = DataType::Struct(
1408            vec![
1409                Field::new("metadata", DataType::BinaryView, false),
1410                Field::new("value", DataType::BinaryView, true),
1411            ]
1412            .into(),
1413        );
1414        let field = Field::new("v", storage, true).with_metadata([(
1415            "ARROW:extension:name".to_string(),
1416            "arrow.parquet.variant".to_string(),
1417        )]);
1418        assert_eq!(
1419            session.from_arrow_field(&field)?,
1420            DType::Variant(Nullability::Nullable)
1421        );
1422        Ok(())
1423    }
1424
1425    static REJECT_DICTIONARY_ID: CachedId = CachedId::new("test.reject_dictionary");
1426
1427    /// An importer that fails on an Arrow dictionary and imports anything else as its storage.
1428    #[derive(Debug)]
1429    struct DictionaryRejectingImporter;
1430
1431    impl ArrowImportVTable for DictionaryRejectingImporter {
1432        fn arrow_ext_id(&self) -> Id {
1433            *REJECT_DICTIONARY_ID
1434        }
1435
1436        fn from_arrow_field(
1437            &self,
1438            field: &Field,
1439            session: &ArrowSession,
1440        ) -> VortexResult<Option<DType>> {
1441            vortex_ensure!(
1442                !matches!(field.data_type(), DataType::Dictionary(..)),
1443                "an importer must never see a dictionary field, got {}",
1444                field.data_type()
1445            );
1446            session
1447                .from_arrow_datatype(field.data_type(), field.is_nullable().into())
1448                .map(Some)
1449        }
1450
1451        fn from_arrow_array(
1452            &self,
1453            array: ArrowArrayRef,
1454            field: &Field,
1455            _dtype: &DType,
1456            session: &ArrowSession,
1457        ) -> VortexResult<ArrowImport> {
1458            vortex_ensure!(
1459                !matches!(array.data_type(), DataType::Dictionary(..)),
1460                "an importer must never see a dictionary array, got {}",
1461                array.data_type()
1462            );
1463            session
1464                .from_arrow_array(array, field.is_nullable())
1465                .map(ArrowImport::Imported)
1466        }
1467    }
1468
1469    /// An Arrow dictionary imports as a Vortex `Dict` array over the dictionary values, matching
1470    /// the dtype the schema conversion reports. The session peels the dictionary before any
1471    /// importer runs, so a dictionary field named for an importer that fails on dictionaries still
1472    /// imports.
1473    #[rstest]
1474    #[case::plain(None)]
1475    #[case::extension_name(Some(*REJECT_DICTIONARY_ID))]
1476    fn dictionary_imports_as_dict_encoding(#[case] extension_name: Option<Id>) -> VortexResult<()> {
1477        let vortex_session = VortexSession::empty();
1478        let session = vortex_session.arrow();
1479        session.register_importer(Arc::new(DictionaryRejectingImporter));
1480        let dict: ArrowArrayRef = Arc::new(DictionaryArray::<Int32Type>::try_new(
1481            Int32Array::from(vec![0, 1, 0, 1]),
1482            Arc::new(StringArray::from(vec!["a", "b"])),
1483        )?);
1484        let metadata = extension_name
1485            .map(|id| (EXTENSION_TYPE_NAME_KEY.to_string(), id.to_string()))
1486            .into_iter()
1487            .collect::<Metadata>();
1488        let field = Field::new("s", dict.data_type().clone(), false).with_metadata(metadata);
1489
1490        let dtype = session.from_arrow_field(&field)?;
1491        assert_eq!(dtype, DType::Utf8(Nullability::NonNullable));
1492
1493        let array = session.from_arrow_array(dict, &field)?;
1494        assert!(array.is::<Dict>(), "expected a Dict encoding, got {array}");
1495        assert_eq!(array.dtype(), &dtype);
1496        assert_arrays_eq!(
1497            array,
1498            VarBinViewArray::from_iter_str(["a", "b", "a", "b"]),
1499            &mut SESSION.create_execution_ctx()
1500        );
1501        Ok(())
1502    }
1503
1504    static TRUNCATE_ID: CachedId = CachedId::new("test.truncate");
1505
1506    /// An importer that drops the last element of every array it is given, then either imports
1507    /// it or declines and hands it back.
1508    #[derive(Debug)]
1509    struct TruncatingImporter {
1510        decline: bool,
1511    }
1512
1513    impl ArrowImportVTable for TruncatingImporter {
1514        fn arrow_ext_id(&self) -> Id {
1515            *TRUNCATE_ID
1516        }
1517
1518        fn from_arrow_field(
1519            &self,
1520            field: &Field,
1521            session: &ArrowSession,
1522        ) -> VortexResult<Option<DType>> {
1523            session
1524                .from_arrow_datatype(field.data_type(), field.is_nullable().into())
1525                .map(Some)
1526        }
1527
1528        fn from_arrow_array(
1529            &self,
1530            array: ArrowArrayRef,
1531            field: &Field,
1532            _dtype: &DType,
1533            session: &ArrowSession,
1534        ) -> VortexResult<ArrowImport> {
1535            let truncated = array.slice(0, array.len() - 1);
1536            if self.decline {
1537                return Ok(ArrowImport::Unsupported(truncated));
1538            }
1539            session
1540                .from_arrow_array(truncated, field.is_nullable())
1541                .map(ArrowImport::Imported)
1542        }
1543    }
1544
1545    fn truncated_field(name: &str, data_type: DataType) -> FieldRef {
1546        Arc::new(Field::new(name, data_type, false).with_metadata([(
1547            EXTENSION_TYPE_NAME_KEY.to_string(),
1548            "test.truncate".to_string(),
1549        )]))
1550    }
1551
1552    fn list_with_truncated_child() -> ArrowArrayRef {
1553        Arc::new(GenericListArray::<i32>::new(
1554            truncated_field("item", DataType::Int64),
1555            OffsetBuffer::new(vec![0, 5].into()),
1556            Arc::new(Int64Array::from_iter_values(0..5)),
1557            None,
1558        ))
1559    }
1560
1561    fn list_view_with_truncated_child() -> ArrowArrayRef {
1562        Arc::new(GenericListViewArray::<i32>::new(
1563            truncated_field("item", DataType::Int64),
1564            ScalarBuffer::from(vec![0]),
1565            ScalarBuffer::from(vec![5]),
1566            Arc::new(Int64Array::from_iter_values(0..5)),
1567            None,
1568        ))
1569    }
1570
1571    fn map_entries_with_value_field(value_field: FieldRef) -> StructArray {
1572        let key_field = Arc::new(Field::new("key", DataType::Int64, false));
1573
1574        StructArray::new(
1575            Fields::from(vec![key_field, value_field]),
1576            vec![
1577                Arc::new(Int64Array::from_iter_values(0..5)),
1578                Arc::new(Int64Array::from_iter_values(5..10)),
1579            ],
1580            None,
1581        )
1582    }
1583
1584    fn map_with_truncated_child() -> ArrowArrayRef {
1585        let entries = map_entries_with_value_field(truncated_field("value", DataType::Int64));
1586        Arc::new(MapArray::new(
1587            Arc::new(Field::new("entries", entries.data_type().clone(), false)),
1588            OffsetBuffer::new(vec![0, 5].into()),
1589            entries,
1590            None,
1591            false,
1592        ))
1593    }
1594
1595    #[test]
1596    fn test_map_entries_ignore_import_plugins() -> VortexResult<()> {
1597        let vortex_session = VortexSession::empty();
1598        let session = vortex_session.arrow();
1599        session.register_importer(Arc::new(TruncatingImporter { decline: false }));
1600
1601        let value_field = Arc::new(Field::new("value", DataType::Int64, false));
1602        let entries = map_entries_with_value_field(value_field);
1603        let map = MapArray::new(
1604            truncated_field("entries", entries.data_type().clone()),
1605            OffsetBuffer::new(vec![0, 5].into()),
1606            entries,
1607            None,
1608            false,
1609        );
1610        let field = Field::new("map", map.data_type().clone(), false);
1611        let expected_dtype = session.from_arrow_field(&field)?;
1612
1613        let imported = session.from_arrow_array(Arc::new(map), &field)?;
1614        assert_eq!(imported.dtype(), &expected_dtype);
1615
1616        Ok(())
1617    }
1618
1619    #[rstest]
1620    #[case::list(list_with_truncated_child())]
1621    #[case::list_view(list_view_with_truncated_child())]
1622    #[case::map(map_with_truncated_child())]
1623    fn test_rejects_importer_that_changes_child_length(
1624        #[case] array: ArrowArrayRef,
1625        #[values(false, true)] decline: bool,
1626    ) {
1627        let vortex_session = VortexSession::empty();
1628        let session = vortex_session.arrow();
1629        session.register_importer(Arc::new(TruncatingImporter { decline }));
1630
1631        let err = session
1632            .from_arrow_array(array, false)
1633            .expect_err("a child importer that drops elements must be rejected");
1634        assert!(
1635            err.to_string()
1636                .contains("returned 4 elements for an array of 5"),
1637            "unexpected error: {err}"
1638        );
1639    }
1640
1641    #[test]
1642    fn test_import_struct_with_non_nullable_descendants_under_null_row() -> VortexResult<()> {
1643        let row_nulls = NullBuffer::from(vec![true, false]);
1644        let inner = StructArray::try_new(
1645            Fields::from(vec![Field::new("x", DataType::Int32, false)]),
1646            vec![Arc::new(Int32Array::from(vec![Some(1), None]))],
1647            Some(row_nulls.clone()),
1648        )?;
1649        let outer = StructArray::try_new(
1650            Fields::from(vec![Field::new("inner", inner.data_type().clone(), false)]),
1651            vec![Arc::new(inner)],
1652            Some(row_nulls),
1653        )?;
1654        let imported = SESSION.arrow().from_arrow_array(Arc::new(outer), true)?;
1655
1656        let inner = VortexStructArray::from_fields(&[("x", buffer![1i32, 0].into_array())])?;
1657        let expected = VortexStructArray::try_new(
1658            FieldNames::from(["inner"]),
1659            vec![inner.into_array()],
1660            2,
1661            Validity::from_iter([true, false]),
1662        )?;
1663        assert_arrays_eq!(imported, expected, &mut SESSION.create_execution_ctx());
1664        Ok(())
1665    }
1666
1667    /// A list element field of nullable `i32` values.
1668    fn nullable_item() -> FieldRef {
1669        Arc::new(Field::new_list_field(DataType::Int32, true))
1670    }
1671
1672    /// A map from `i32` keys to nullable `i32` values.
1673    fn int_map_type() -> DataType {
1674        let entries = Field::new_struct(
1675            "entries",
1676            vec![
1677                Field::new("key", DataType::Int32, false),
1678                Field::new("value", DataType::Int32, true),
1679            ],
1680            false,
1681        );
1682        DataType::Map(Arc::new(entries), false)
1683    }
1684
1685    /// Create a dictionary with one null key and one available value.
1686    fn dictionary_with_null_key() -> ArrowArrayRef {
1687        Arc::new(DictionaryArray::<Int32Type>::new(
1688            Int32Array::new_null(1),
1689            Arc::new(StringArray::from(vec!["a"])),
1690        ))
1691    }
1692
1693    /// Outer joins can produce null rows with nulls in declared non-nullable fields.
1694    #[rstest]
1695    #[case::list(new_null_array(&DataType::List(nullable_item()), 1))]
1696    #[case::large_list(new_null_array(&DataType::LargeList(nullable_item()), 1))]
1697    #[case::fixed_size_list(new_null_array(&DataType::FixedSizeList(nullable_item(), 2), 1))]
1698    #[case::list_view(new_null_array(&DataType::ListView(nullable_item()), 1))]
1699    #[case::large_list_view(new_null_array(&DataType::LargeListView(nullable_item()), 1))]
1700    #[case::map(new_null_array(&int_map_type(), 1))]
1701    #[case::dictionary(dictionary_with_null_key())]
1702    fn test_struct_with_null_children_preserves_declared_dtype(
1703        #[case] child: ArrowArrayRef,
1704    ) -> VortexResult<()> {
1705        let row = StructArray::try_new(
1706            Fields::from(vec![Field::new("c", child.data_type().clone(), false)]),
1707            vec![child],
1708            Some(NullBuffer::new_null(1)),
1709        )?;
1710        let field = Field::new("s", row.data_type().clone(), true);
1711        let session = SESSION.arrow();
1712        let imported = session.from_arrow_array(Arc::new(row), &field)?;
1713        assert_eq!(imported.dtype(), &session.from_arrow_field(&field)?);
1714        Ok(())
1715    }
1716
1717    #[test]
1718    fn test_dictionary_without_values_in_null_list_gets_zero_entry() -> VortexResult<()> {
1719        let dictionary = DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8));
1720        let element = Arc::new(Field::new_list_field(dictionary, false));
1721        let lists = new_null_array(&DataType::FixedSizeList(element, 2), 1);
1722        let imported = SESSION.arrow().from_arrow_array(lists, true)?;
1723
1724        let expected = VarBinViewArray::from_iter_str(["", ""]);
1725        let imported = imported.as_::<FixedSizeList>();
1726        assert_arrays_eq!(
1727            imported.elements(),
1728            expected,
1729            &mut SESSION.create_execution_ctx()
1730        );
1731        Ok(())
1732    }
1733
1734    /// Build the structs `[{x: null}, null]` and a field that declares `x` non-nullable.
1735    fn struct_with_null_in_valid_row() -> (ArrowArrayRef, Field) {
1736        let rows = StructArray::new(
1737            Fields::from(vec![Field::new("x", DataType::Int32, true)]),
1738            vec![Arc::new(Int32Array::from(vec![None, Some(5)]))],
1739            Some(NullBuffer::from(vec![true, false])),
1740        );
1741        let field = Field::new_struct("s", vec![Field::new("x", DataType::Int32, false)], true);
1742        (Arc::new(rows), field)
1743    }
1744
1745    /// Build the lists `[[1, null], null]` and a field that declares the elements non-nullable.
1746    fn fixed_size_list_with_null_in_valid_row() -> (ArrowArrayRef, Field) {
1747        let lists = ArrowFixedSizeListArray::new(
1748            nullable_item(),
1749            2,
1750            Arc::new(Int32Array::from(vec![Some(1), None, Some(3), Some(4)])),
1751            Some(NullBuffer::from(vec![true, false])),
1752        );
1753        let element = Field::new_list_field(DataType::Int32, false);
1754        let field = Field::new_fixed_size_list("l", element, 2, true);
1755        (Arc::new(lists), field)
1756    }
1757
1758    #[rstest]
1759    #[case::struct_field(
1760        struct_with_null_in_valid_row(),
1761        VortexStructArray::new(
1762            FieldNames::from(["x"]),
1763            vec![buffer![0i32, 5].into_array()],
1764            2,
1765            Validity::from_iter([true, false]),
1766        ).into_array(),
1767    )]
1768    #[case::fixed_size_list_element(
1769        fixed_size_list_with_null_in_valid_row(),
1770        FixedSizeListArray::new(
1771            buffer![1i32, 0, 3, 4].into_array(),
1772            2,
1773            Validity::from_iter([true, false]),
1774            2,
1775        ).into_array(),
1776    )]
1777    fn test_declared_non_nullable_leaf_fills_null_in_valid_row(
1778        #[case] input: (ArrowArrayRef, Field),
1779        #[case] expected: ArrayRef,
1780    ) -> VortexResult<()> {
1781        let (array, field) = input;
1782        let imported = SESSION.arrow().from_arrow_array(array, &field)?;
1783        assert_arrays_eq!(imported, expected, &mut SESSION.create_execution_ctx());
1784        Ok(())
1785    }
1786
1787    /// An extension type over any storage dtype.
1788    ///
1789    /// Its metadata is the storage dtype that it declares, which it reads back from the stored
1790    /// storage, so its serialized metadata is empty.
1791    #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
1792    struct AnyStorage;
1793
1794    impl ExtVTable for AnyStorage {
1795        type Metadata = DType;
1796        type StoredMetadata = ();
1797        type NativeValue<'a> = &'a ScalarValue;
1798
1799        fn id(&self) -> ExtId {
1800            static ID: CachedId = CachedId::new("test.any_storage");
1801            *ID
1802        }
1803
1804        fn serialize_metadata(&self, _metadata: &DType) -> VortexResult<Vec<u8>> {
1805            Ok(Vec::new())
1806        }
1807
1808        fn deserialize_metadata(&self, _metadata: &[u8]) -> VortexResult<()> {
1809            Ok(())
1810        }
1811
1812        fn metadata_from_storage(
1813            &self,
1814            _stored_metadata: (),
1815            storage_dtype: &DType,
1816        ) -> VortexResult<DType> {
1817            Ok(storage_dtype.clone())
1818        }
1819
1820        fn storage_dtype(metadata: &DType) -> DType {
1821            metadata.clone()
1822        }
1823
1824        fn unpack_native<'a>(
1825            _ext_dtype: &'a ExtDType<Self>,
1826            storage_value: &'a ScalarValue,
1827        ) -> VortexResult<&'a ScalarValue> {
1828            Ok(storage_value)
1829        }
1830    }
1831
1832    /// An [`AnyStorage`] dtype over `storage`.
1833    fn any_storage(storage: DType) -> VortexResult<ExtDTypeRef> {
1834        Ok(ExtDType::try_from_storage_with_vtable(AnyStorage, (), storage)?.erased())
1835    }
1836
1837    /// The Arrow lists `[[{x: 1}], [{x: null}]]` with nullable fields at every level, where
1838    /// `list_nulls` is the validity of the two lists.
1839    fn lists_of_points(list_nulls: Option<NullBuffer>) -> ArrowArrayRef {
1840        let points = StructArray::new(
1841            Fields::from(vec![Field::new("x", DataType::Int32, true)]),
1842            vec![Arc::new(Int32Array::from(vec![Some(1), None]))],
1843            None,
1844        );
1845        Arc::new(GenericListArray::<i32>::new(
1846            Arc::new(Field::new("item", points.data_type().clone(), true)),
1847            OffsetBuffer::new(vec![0, 1, 2].into()),
1848            Arc::new(points),
1849            list_nulls,
1850        ))
1851    }
1852
1853    /// Nullable lists of `{x: i32}` points, non-nullable below the lists.
1854    fn lists_of_points_dtype() -> DType {
1855        let x = DType::Primitive(PType::I32, Nullability::NonNullable);
1856        let point = DType::Struct(
1857            StructFields::from_iter([("x", x)]),
1858            Nullability::NonNullable,
1859        );
1860        DType::List(Arc::new(point), Nullability::Nullable)
1861    }
1862
1863    #[rstest]
1864    #[case::valid_rows(lists_of_points(None), &[1, 0], &[0, 1, 2], Validity::AllValid)]
1865    #[case::under_null_row(
1866        lists_of_points(Some(NullBuffer::from(vec![true, false]))),
1867        &[1, 0],
1868        &[0, 1, 2],
1869        Validity::from_iter([true, false]),
1870    )]
1871    #[case::outside_sliced_rows(
1872        lists_of_points(None).slice(0, 1),
1873        &[1],
1874        &[0, 1],
1875        Validity::AllValid,
1876    )]
1877    fn test_from_arrow_storage_fills_null_coordinates(
1878        #[case] lists: ArrowArrayRef,
1879        #[case] expected_coordinates: &[i32],
1880        #[case] expected_offsets: &[i32],
1881        #[case] validity: Validity,
1882    ) -> VortexResult<()> {
1883        let ext = any_storage(lists_of_points_dtype())?;
1884        let imported = SESSION.arrow().from_arrow_storage(lists, &ext)?;
1885
1886        let mut ctx = SESSION.create_execution_ctx();
1887        let coordinates = PrimitiveArray::from_iter(expected_coordinates.iter().copied());
1888        let points = VortexStructArray::from_fields(&[("x", coordinates.into_array())])?;
1889        let lists = ListArray::try_new(
1890            points.into_array(),
1891            PrimitiveArray::from_iter(expected_offsets.iter().copied()).into_array(),
1892            validity,
1893            &mut ctx,
1894        )?;
1895        let expected = ExtensionArray::try_new(ext, lists.into_array())?;
1896        assert_arrays_eq!(imported, expected, &mut ctx);
1897        Ok(())
1898    }
1899
1900    /// Arrow storage `{x: i32, y: i32}` against declared storage with other field names, field
1901    /// order, or types.
1902    #[rstest]
1903    #[case::names(["x", "z"], [PType::I32, PType::I32])]
1904    #[case::order(["y", "x"], [PType::I32, PType::I32])]
1905    #[case::types(["x", "y"], [PType::I64, PType::I32])]
1906    fn test_from_arrow_storage_rejects_other_fields(
1907        #[case] names: [&str; 2],
1908        #[case] ptypes: [PType; 2],
1909    ) -> VortexResult<()> {
1910        let point: ArrowArrayRef = Arc::new(StructArray::from(vec![
1911            (
1912                Arc::new(Field::new("x", DataType::Int32, false)),
1913                Arc::new(Int32Array::from(vec![1])) as ArrowArrayRef,
1914            ),
1915            (
1916                Arc::new(Field::new("y", DataType::Int32, false)),
1917                Arc::new(Int32Array::from(vec![2])) as ArrowArrayRef,
1918            ),
1919        ]));
1920        let fields = ptypes.map(|ptype| DType::Primitive(ptype, Nullability::NonNullable));
1921        let storage = DType::Struct(
1922            StructFields::new(FieldNames::from(names), fields.to_vec()),
1923            Nullability::NonNullable,
1924        );
1925
1926        let err = SESSION
1927            .arrow()
1928            .from_arrow_storage(point, &any_storage(storage)?)
1929            .expect_err("storage with other fields must fail the import");
1930        assert!(
1931            err.to_string()
1932                .contains("Arrow storage of test.any_storage must convert to"),
1933            "unexpected error: {err}"
1934        );
1935        Ok(())
1936    }
1937
1938    const EXPORTER_NAME: &str = "test.exporter";
1939    static EXPORTER_ID: CachedId = CachedId::new(EXPORTER_NAME);
1940
1941    /// Declines every array, because the tests only need an exporter registered under its name.
1942    #[derive(Debug)]
1943    struct DecliningExporter;
1944
1945    impl ArrowExportVTable for DecliningExporter {
1946        fn arrow_ext_id(&self) -> Id {
1947            *EXPORTER_ID
1948        }
1949
1950        fn vortex_id(&self) -> Id {
1951            *EXPORTER_ID
1952        }
1953
1954        fn to_arrow_field(
1955            &self,
1956            _name: &str,
1957            _dtype: &DType,
1958            _session: &ArrowSession,
1959        ) -> VortexResult<Option<Field>> {
1960            Ok(None)
1961        }
1962
1963        fn execute_arrow(
1964            &self,
1965            array: ArrayRef,
1966            _target: &Field,
1967            _options: &ArrowExportOptions,
1968            _ctx: &mut ExecutionCtx,
1969        ) -> VortexResult<ArrowExport> {
1970            Ok(ArrowExport::Unsupported(array))
1971        }
1972    }
1973
1974    /// An `Int32` field that names `extension_name`, or a plain one without it.
1975    fn leaf(extension_name: Option<&str>) -> FieldRef {
1976        let mut leaf = Field::new("leaf", DataType::Int32, true);
1977        if let Some(name) = extension_name {
1978            leaf = leaf.with_metadata(Metadata::from_iter([(
1979                EXTENSION_TYPE_NAME_KEY.to_string(),
1980                name.to_string(),
1981            )]));
1982        }
1983
1984        Arc::new(leaf)
1985    }
1986
1987    /// Only a leaf that names a registered exporter makes an export call a plugin, at any depth.
1988    #[rstest]
1989    #[case::top_level(     |leaf: FieldRef| leaf.as_ref().clone())]
1990    #[case::struct_child(  |leaf: FieldRef| Field::new_struct("a", vec![leaf], true))]
1991    #[case::list_item(     |leaf: FieldRef| Field::new_list("a", leaf, true))]
1992    #[case::run_end_values(|leaf: FieldRef| {
1993        let run_ends = Arc::new(Field::new("run_ends", DataType::Int32, false));
1994        Field::new("a", DataType::RunEndEncoded(run_ends, leaf), true)
1995    })]
1996    #[case::dictionary_values(|leaf: FieldRef| {
1997        Field::new_dictionary("a", DataType::Int32, DataType::Struct(vec![leaf].into()), true)
1998    })]
1999    fn test_exports_without_plugins_finds_exporters_at_any_depth(
2000        #[case] wrap: fn(FieldRef) -> Field,
2001        #[values(None, Some("test.unregistered"), Some(EXPORTER_NAME))] leaf_name: Option<&str>,
2002    ) {
2003        let vortex_session = VortexSession::empty();
2004        let session = vortex_session.arrow();
2005        session.register_exporter(Arc::new(DecliningExporter));
2006
2007        let field = wrap(leaf(leaf_name));
2008        let leaf_names_exporter = leaf_name == Some(EXPORTER_NAME);
2009
2010        assert_eq!(
2011            session.exports_without_plugins(&field),
2012            !leaf_names_exporter
2013        );
2014    }
2015}