vortex-arrow 0.92.0

Apache Arrow interoperability for Vortex arrays
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright the Vortex contributors

//! Plugin layer for moving Arrow extension types in and out of Vortex.
//!
//! Vortex's canonical Arrow conversion (see [`crate::dtype`] and the executor in
//! [`crate::executor`]) handles every non-extension Arrow type and the builtin temporal
//! extensions. The plugins registered here cover the remaining case: **Arrow extension types**.
//!
//! * An [`ArrowExportVTable`] is dispatched purely by the **target Arrow extension Id** —
//!   the plugin is selected when the caller asks for an Arrow [`Field`] carrying matching
//!   `ARROW:extension:name` metadata. The Vortex source dtype/encoding is irrelevant to
//!   dispatch.
//! * An [`ArrowImportVTable`] is dispatched by the **source Arrow extension name** carried
//!   on the incoming [`Field`]. The plugin is responsible for both preserving extension
//!   identity and re-encoding storage if needed (e.g. Arrow `FixedSizeBinary[16]` for UUID
//!   becomes Vortex `FixedSizeList<u8; 16>`).
//!
//! Multiple plugins may register against the same key. They are tried in registration order;
//! each may return [`ArrowExport::Unsupported`] / [`ArrowImport::Unsupported`] to defer to
//! the next.
//!
//! A Vortex extension type that does not have a plugin exports its storage, plus Arrow extension
//! metadata that holds its Vortex ID. [`ArrowSession`] describes this format.

use std::any::Any;
use std::borrow::Cow;
use std::fmt::Debug;
use std::sync::Arc;

use arrow_array::Array as ArrowArray;
use arrow_array::ArrayRef as ArrowArrayRef;
use arrow_array::RecordBatch;
use arrow_array::RunArray;
use arrow_array::cast::AsArray;
use arrow_array::make_array;
use arrow_array::types::Int16Type;
use arrow_array::types::Int32Type;
use arrow_array::types::Int64Type;
use arrow_array::types::RunEndIndexType;
use arrow_schema::DataType;
use arrow_schema::Field;
use arrow_schema::FieldRef;
use arrow_schema::Fields;
use arrow_schema::Schema;
use arrow_schema::extension::EXTENSION_TYPE_METADATA_KEY;
use arrow_schema::extension::EXTENSION_TYPE_NAME_KEY;
use base64::Engine;
use base64::prelude::BASE64_STANDARD;
use tracing::debug;
use tracing::trace;
use vortex_array::ArrayRef;
use vortex_array::ExecutionCtx;
use vortex_array::IntoArray;
use vortex_array::arrays::DictArray;
use vortex_array::arrays::ExtensionArray;
use vortex_array::arrays::FixedSizeListArray;
use vortex_array::arrays::ListArray;
use vortex_array::arrays::ListViewArray;
use vortex_array::arrays::StructArray;
use vortex_array::arrays::extension::ExtensionArrayExt;
use vortex_array::dtype::DType;
use vortex_array::dtype::FieldName;
use vortex_array::dtype::FieldNames;
use vortex_array::dtype::NativePType;
use vortex_array::dtype::Nullability;
use vortex_array::dtype::StructFields;
use vortex_array::dtype::extension::ExtDTypeRef;
use vortex_array::dtype::extension::ExtId;
use vortex_array::dtype::session::DTypeSession;
use vortex_array::dtype::session::ExtDTypeRegistry;
use vortex_array::extension::datetime::AnyTemporal;
use vortex_array::validity::Validity;
use vortex_error::VortexResult;
use vortex_error::vortex_bail;
use vortex_error::vortex_ensure;
use vortex_error::vortex_ensure_eq;
use vortex_error::vortex_err;
use vortex_session::ArcSwapMap;
use vortex_session::SessionExt;
use vortex_session::SessionGuard;
use vortex_session::SessionVar;
use vortex_session::registry::Id;

use crate::ArrowExportOptions;
use crate::IntoVortexArray;
use crate::convert::from_arrow_dyn;
use crate::convert::map_from_arrow_parts;
use crate::convert::nulls;
use crate::convert::remove_nulls;
use crate::convert::trim_map_entries;
use crate::convert::trim_offsets;
use crate::dtype::from_arrow_data_type;
use crate::dtype::to_data_type_naive;
use crate::executor::execute_arrow_naive;
use crate::run_end_import::run_end_from_arrow;

/// Outcome of a successful call to [`ArrowExportVTable::execute_arrow`].
///
/// Plugins that don't handle the supplied array return [`Unsupported`][Self::Unsupported]
/// with ownership of the input so the session can probe the next plugin or fall back to the
/// canonical path. Errors are propagated through [`VortexResult`].
pub enum ArrowExport {
    /// The plugin does not handle this input; the session may try another plugin.
    Unsupported(ArrayRef),
    /// A successful export.
    Exported(ArrowArrayRef),
}

/// Outcome of a successful call to [`ArrowImportVTable::from_arrow_array`].
///
/// Plugins that don't handle the supplied array return [`Unsupported`][Self::Unsupported]
/// with ownership of the input so the session can probe the next plugin or fall back to the
/// canonical path. Errors are propagated through [`VortexResult`].
pub enum ArrowImport {
    /// The plugin does not handle this input; the session may try another plugin.
    Unsupported(ArrowArrayRef),
    /// A successful import.
    Imported(ArrayRef),
}

/// The Arrow type description of an array being imported by [`ArrowSession::from_arrow_array`].
///
/// Callers holding an Arrow [`Field`] (or [`FieldRef`]) should pass it: its
/// `ARROW:extension:name` metadata is what dispatches the array to a registered
/// [`ArrowImportVTable`].
///
/// An Arrow array can carry a validity (null) buffer regardless of whether its schema declares
/// the field nullable, so when no [`Field`] is in hand the caller passes the desired nullability
/// instead, as a [`bool`] or a [`Nullability`]. An anonymous field is then synthesized from the
/// array's own data type, which means no extension plugin is dispatched for the array itself;
/// fields nested inside container data types still carry their metadata and are routed through
/// their importers.
pub trait IntoArrowField<'a> {
    /// Resolve to the Arrow [`Field`] describing an array of `data_type`.
    fn into_arrow_field(self, data_type: &DataType) -> Cow<'a, Field>;
}

impl<'a> IntoArrowField<'a> for &'a Field {
    fn into_arrow_field(self, _data_type: &DataType) -> Cow<'a, Field> {
        Cow::Borrowed(self)
    }
}

impl<'a> IntoArrowField<'a> for &'a FieldRef {
    fn into_arrow_field(self, _data_type: &DataType) -> Cow<'a, Field> {
        Cow::Borrowed(self.as_ref())
    }
}

impl<'a> IntoArrowField<'a> for bool {
    fn into_arrow_field(self, data_type: &DataType) -> Cow<'a, Field> {
        Cow::Owned(Field::new("", data_type.clone(), self))
    }
}

impl<'a> IntoArrowField<'a> for Nullability {
    fn into_arrow_field(self, data_type: &DataType) -> Cow<'a, Field> {
        self.is_nullable().into_arrow_field(data_type)
    }
}

/// Plugin layer for exporting a Vortex array to an Arrow extension type.
///
/// This is purely an implementation trait, its methods should not be called directly. Instead,
/// use the methods on [`ArrowSession`].
pub trait ArrowExportVTable: 'static + Send + Sync + Debug {
    /// The Arrow extension ID this plugin produces.
    fn arrow_ext_id(&self) -> Id;

    /// The Vortex array or extension ID this plugin maps from. Used only for inference by
    /// [`ArrowSession::to_arrow_field`] / [`ArrowSession::to_arrow_schema`]; never as a
    /// dispatch key for [`execute_arrow`][Self::execute_arrow].
    fn vortex_id(&self) -> Id;

    /// Build the Arrow [`Field`] this plugin produces for the given Vortex extension
    /// `dtype`. Used during schema inference.
    fn to_arrow_field(
        &self,
        name: &str,
        dtype: &DType,
        session: &ArrowSession,
    ) -> VortexResult<Option<Field>>;

    /// Convert a Vortex array into an Arrow array shaped to `target`.
    ///
    /// Returns ownership of `array` via [`ArrowExport::Unsupported`] when the plugin cannot
    /// handle the input. Plugins that export child or storage arrays must pass `options` on to
    /// those exports.
    fn execute_arrow(
        &self,
        array: ArrayRef,
        target: &Field,
        options: &ArrowExportOptions,
        ctx: &mut ExecutionCtx,
    ) -> VortexResult<ArrowExport>;
}

/// Plugin layer for importing an Arrow extension-typed array into a Vortex array.
///
/// Plugins are dispatched by `arrow_ext_id`. The session peels Arrow dictionaries before it
/// dispatches, so a plugin never sees a [`DataType::Dictionary`] field or array. It sees the value
/// field, with the dictionary field's metadata, and the values array. The session then wraps the
/// plugin's result in a [`DictArray`] with the dictionary's codes.
///
/// Arrow stores dictionary values as a bare [`DataType`], so their extension metadata lives on
/// the outer [`Field`]. Peeling the dictionary lets the importer see the value type described by
/// that metadata. [`DataType::RunEndEncoded`] has a separate values field that can carry its own
/// extension metadata, so its values use the normal nested-field import path.
///
/// This is purely an implementation trait, its methods should not be called directly. Instead,
/// use the methods on [`ArrowSession`].
pub trait ArrowImportVTable: 'static + Send + Sync + Debug {
    /// The Arrow extension name this plugin handles.
    fn arrow_ext_id(&self) -> Id;

    /// Build the Vortex [`DType`] that corresponds to `field` (which carries this plugin's
    /// Arrow extension metadata).
    ///
    /// `session` is provided so plugins can resolve nested or storage fields through the
    /// plugin-aware conversion (e.g. [`ArrowSession::from_arrow_datatype`]) instead of the
    /// naive Arrow → Vortex mapping.
    #[allow(clippy::wrong_self_convention)]
    fn from_arrow_field(
        &self,
        field: &Field,
        session: &ArrowSession,
    ) -> VortexResult<Option<DType>>;

    /// Convert an Arrow array into a Vortex array of `dtype`.
    ///
    /// Returns ownership of `array` via [`ArrowImport::Unsupported`] when the plugin cannot
    /// handle the input.
    ///
    /// `session` is provided so plugins can convert storage or nested arrays through the
    /// session (e.g. [`ArrowSession::from_arrow_array`], passing a nullability rather than a
    /// [`Field`] so the plugin is not dispatched again).
    #[allow(clippy::wrong_self_convention)]
    fn from_arrow_array(
        &self,
        array: ArrowArrayRef,
        field: &Field,
        dtype: &DType,
        session: &ArrowSession,
    ) -> VortexResult<ArrowImport>;
}

pub type ArrowExportVTableRef = Arc<dyn ArrowExportVTable>;
pub type ArrowImportVTableRef = Arc<dyn ArrowImportVTable>;

/// Registry of Arrow exporters, keyed by target Arrow extension [`Id`].
type ArrowExporterRegistry = ArcSwapMap<Id, Arc<[ArrowExportVTableRef]>>;
/// Registry of Arrow exporters, keyed by source Vortex extension [`ExtId`].
type VortexExporterRegistry = ArcSwapMap<ExtId, Arc<[ArrowExportVTableRef]>>;
/// Registry of Arrow importers, keyed by source Arrow extension [`Id`].
type ArrowImporterRegistry = ArcSwapMap<Id, Arc<[ArrowImportVTableRef]>>;

/// Session-scoped registry of Arrow extension plugins.
///
/// Exporters are stored in two indices: one keyed by Arrow extension Id (used for
/// `execute_arrow` dispatch) and one keyed by Vortex extension Id (used **only** by
/// `to_arrow_field` / `to_arrow_schema` inference, when callers need to translate a Vortex
/// extension `DType` into an Arrow `Field` with no target schema in hand). Importers are
/// keyed by Arrow extension name. Extension plugins are registered by the crate that owns the
/// extension type (for example `vortex-uuid`); temporal extensions are handled by the canonical
/// Arrow ↔ Vortex path and do not need plugins.
///
/// An extension type that does not have an exporter exports its storage field, with two Arrow
/// metadata keys added: `ARROW:extension:name` holds its Vortex ID, and `ARROW:extension:metadata`
/// holds its serialized metadata in standard padded base64. The metadata is base64 because Arrow
/// field metadata must be UTF-8, which is also how Parquet stores `ARROW:schema`. DataFusion
/// compares these strings when it merges file schemas, so [`ExtDTypeRef::serialize_metadata`] must
/// give equal bytes for equal dtypes. The export fails if the storage field already has an Arrow
/// extension name, because one field cannot have two.
///
/// A caller can also export to such a field directly. If no exporter accepts the target, but its
/// extension name is the Vortex ID of the array, the array exports its storage. This works for
/// every extension type, so a caller can export a timestamp column as `Int64` without losing its
/// type. However, the target must have the same metadata as the array, because different metadata
/// would give the values a different meaning, such as a different time unit for a timestamp. To
/// check this, a session that knows the Vortex ID rebuilds the dtype from the target and compares
/// the dtypes, and any other session compares the metadata bytes.
///
/// On import, the importers run first. If none of them accepts the field, but its extension name is
/// a Vortex ID that the session knows (see [`initialize`]), the field imports as that extension
/// type over its storage. In that case, the import fails if the type rejects the metadata or the
/// storage. A field with any other extension name imports as plain storage.
///
/// [`initialize`]: crate::initialize
#[derive(Clone, Debug, Default)]
pub struct ArrowSession {
    exporters: ArrowExporterRegistry,
    exporters_by_vortex: VortexExporterRegistry,
    importers: ArrowImporterRegistry,
    /// The extension dtypes that the session can look up by Vortex ID. [`Self::new`] shares the
    /// registry of a [`DTypeSession`], so dtypes that are registered there later are also found.
    /// The default session has none.
    ext_dtypes: ExtDTypeRegistry,
}

impl ArrowSession {
    /// Create a session that can look up the extension dtypes of `dtype_session` by Vortex ID.
    pub(crate) fn new(dtype_session: &DTypeSession) -> Self {
        Self {
            ext_dtypes: dtype_session.registry().clone(),
            ..Self::default()
        }
    }

    /// Register an [`ArrowExportVTable`] under its target Arrow extension Id (for dispatch)
    /// and its source Vortex extension Id (for schema inference).
    pub fn register_exporter(&self, exporter: ArrowExportVTableRef) {
        self.exporters.push(
            exporter.arrow_ext_id(),
            ArrowExportVTableRef::clone(&exporter),
        );
        self.exporters_by_vortex
            .push(exporter.vortex_id(), exporter);
    }

    /// Register an [`ArrowImportVTable`] under its source Arrow extension name.
    pub fn register_importer(&self, importer: ArrowImportVTableRef) {
        self.importers.push(importer.arrow_ext_id(), importer);
    }

    fn exporters(&self, id: &Id) -> Arc<[ArrowExportVTableRef]> {
        self.exporters.get(id).unwrap_or_else(|| Arc::from([]))
    }

    fn exporters_by_vortex(&self, id: &Id) -> Arc<[ArrowExportVTableRef]> {
        self.exporters_by_vortex
            .get(id)
            .unwrap_or_else(|| Arc::from([]))
    }

    fn importers(&self, id: &Id) -> Arc<[ArrowImportVTableRef]> {
        self.importers.get(id).unwrap_or_else(|| Arc::from([]))
    }

    /// Build the Arrow [`Field`] for a Vortex [`DType`].
    ///
    /// For [`DType::Extension`]s, plugins registered against the extension's `Id`
    /// are tried in registration order; the first plugin to return `Some(field)` wins.
    ///
    /// An extension type without a plugin exports its storage field, plus Arrow extension metadata
    /// that holds its Vortex ID (see [`ArrowSession`]).
    pub fn to_arrow_field(&self, name: &str, dtype: &DType) -> VortexResult<Field> {
        // Handle the structural encodings, which may have recursive types
        match dtype {
            DType::List(elem_dtype, nullability) => {
                let elem_field = self.to_arrow_field(Field::LIST_FIELD_DEFAULT_NAME, elem_dtype)?;
                Ok(Field::new_list(name, elem_field, nullability.is_nullable()))
            }
            DType::FixedSizeList(elem_dtype, elem_size, nullability) => {
                let elem_field = self.to_arrow_field(Field::LIST_FIELD_DEFAULT_NAME, elem_dtype)?;
                Ok(Field::new_fixed_size_list(
                    name,
                    elem_field,
                    (*elem_size).try_into()?,
                    nullability.is_nullable(),
                ))
            }
            DType::Map(map_dtype, nullability) => {
                let key = self.to_arrow_field("key", &map_dtype.key_dtype())?;
                let value = self.to_arrow_field("value", &map_dtype.value_dtype())?;
                let entries = Field::new_struct("entries", Fields::from(vec![key, value]), false);
                Ok(Field::new(
                    name,
                    DataType::Map(Arc::new(entries), map_dtype.keys_sorted()),
                    nullability.is_nullable(),
                ))
            }
            DType::Struct(fields, nullability) => {
                let arrow_fields = Fields::from_iter(
                    fields
                        .fields()
                        .zip(fields.names().iter())
                        .map(|(field, name)| self.to_arrow_field(name.as_ref(), &field))
                        .collect::<VortexResult<Vec<_>>>()?,
                );
                Ok(Field::new_struct(
                    name,
                    arrow_fields,
                    nullability.is_nullable(),
                ))
            }
            DType::Extension(ext) if !ext.is::<AnyTemporal>() => {
                match self.to_arrow_field_with_exporter(name, ext)? {
                    Some(field) => Ok(field),
                    None => self.to_arrow_field_without_exporter(name, ext),
                }
            }
            DType::Variant(_) => {
                // TODO(Adam): This currently encodes information about parquet-variant
                // at this level. Variant's complexity with being an essentially logical type
                // with multiple physical layout complicates handling this correctly.
                Ok(Field::new(
                    name,
                    DataType::Struct(
                        vec![
                            Field::new("metadata", DataType::BinaryView, dtype.is_nullable()),
                            Field::new("value", DataType::BinaryView, dtype.is_nullable()),
                        ]
                        .into(),
                    ),
                    dtype.is_nullable(),
                )
                .with_metadata(
                    [(
                        EXTENSION_TYPE_NAME_KEY.to_string(),
                        "arrow.parquet.variant".to_string(),
                    )]
                    .into(),
                ))
            }
            _ => Ok(Field::new(
                name,
                to_data_type_naive(dtype)?,
                dtype.is_nullable(),
            )),
        }
    }

    /// Build the Arrow [`Schema`] for a Vortex top-level [`DType::Struct`], dispatching
    /// extension fields through registered export plugins for inference. Nested
    /// extensions are preserved via [`Self::to_arrow_field`].
    pub fn to_arrow_schema(&self, dtype: &DType) -> VortexResult<Schema> {
        let DType::Struct(struct_dtype, _) = dtype else {
            vortex_bail!("to_arrow_schema requires a top-level struct dtype, got {dtype}");
        };
        let mut fields = Vec::with_capacity(struct_dtype.names().len());
        for (name, field_dtype) in struct_dtype.names().iter().zip(struct_dtype.fields()) {
            fields.push(self.to_arrow_field(name.as_ref(), &field_dtype)?);
        }
        Ok(Schema::new(fields))
    }

    /// Returns the Arrow [`DataType`] that best corresponds to the given Vortex [`DType`],
    /// dispatching [`DType::Extension`]s through registered export plugins.
    ///
    /// A [`DataType`] has no field metadata, so this fails for the same types that
    /// [`Self::default_arrow_export_field`] rejects. Use [`Self::to_arrow_field`] to keep the
    /// extension type.
    pub fn to_arrow_datatype(&self, dtype: &DType) -> VortexResult<DataType> {
        Ok(self.default_arrow_export_field(dtype)?.data_type().clone())
    }

    /// Returns the Arrow [`Field`] that an export without a target field uses.
    ///
    /// This is [`Self::to_arrow_field`] with an empty name, except that it fails for a _top-level_
    /// extension type that does not have a plugin. The caller of an export without a target keeps
    /// only the Arrow array or its [`DataType`], not this field. So the extension metadata on the
    /// field would be lost, and with it the extension type. A nested extension type is fine,
    /// because its child [`Field`] keeps the metadata. A top-level extension type with a plugin
    /// still exports, but it loses its extension name, as it did before ([#11286]).
    ///
    /// [#11286]: https://github.com/vortex-data/vortex/issues/11286
    pub fn default_arrow_export_field(&self, dtype: &DType) -> VortexResult<Field> {
        match dtype {
            DType::Extension(ext) if !ext.is::<AnyTemporal>() => {
                self.to_arrow_field_with_exporter("", ext)?.ok_or_else(|| {
                    vortex_err!(
                        "an Arrow export without a target field needs an extension type with an Arrow plugin, got {ext}"
                    )
                })
            }
            _ => self.to_arrow_field("", dtype),
        }
    }

    /// Returns the Arrow [`Field`] from the first exporter that accepts `ext_dtype`, or `None` if
    /// no exporter accepts it.
    fn to_arrow_field_with_exporter(
        &self,
        name: &str,
        ext_dtype: &ExtDTypeRef,
    ) -> VortexResult<Option<Field>> {
        let dtype = DType::Extension(ext_dtype.clone());

        for plugin in self.exporters_by_vortex(&ext_dtype.id()).iter() {
            if let Some(field) = plugin.to_arrow_field(name, &dtype, self)? {
                return Ok(Some(field));
            }
        }

        Ok(None)
    }

    /// Build the storage field of an extension type without an exporter, and add the Arrow
    /// extension metadata that holds its Vortex ID and its metadata.
    fn to_arrow_field_without_exporter(
        &self,
        name: &str,
        ext_dtype: &ExtDTypeRef,
    ) -> VortexResult<Field> {
        let mut field = self.to_arrow_field(name, ext_dtype.storage_dtype())?;
        if let Some(storage_name) = field.extension_type_name() {
            vortex_bail!(
                "the Arrow storage of {ext_dtype} must not be an Arrow extension type, got {storage_name}"
            );
        }

        let metadata = BASE64_STANDARD.encode(ext_dtype.serialize_metadata()?);
        field.metadata_mut().extend([
            (
                EXTENSION_TYPE_NAME_KEY.to_owned(),
                ext_dtype.id().to_string(),
            ),
            (EXTENSION_TYPE_METADATA_KEY.to_owned(), metadata),
        ]);

        Ok(field)
    }

    /// Rebuild the extension dtype whose Vortex ID is the extension name of `field`, with
    /// `storage_dtype` as its storage.
    ///
    /// Returns `None` if the session does not know that Vortex ID, and an error if the metadata of
    /// `field` is not valid for that dtype.
    #[expect(clippy::disallowed_methods, reason = "interning a dynamic id")]
    fn rebuild_ext_dtype_by_vortex_id(
        &self,
        field: &Field,
        storage_dtype: &DType,
    ) -> VortexResult<Option<ExtDTypeRef>> {
        let Some(dtype_plugin) = field
            .extension_type_name()
            .and_then(|name| self.ext_dtypes.get(&Id::new(name)))
        else {
            return Ok(None);
        };

        dtype_plugin
            .deserialize(&decode_ext_metadata(field)?, storage_dtype.clone())
            .map(Some)
    }

    /// Build the Vortex [`DType`] for an Arrow [`Field`].
    ///
    /// A [`DataType::Dictionary`] field converts as its value field with the same metadata.
    ///
    /// Plugins registered against the field's Arrow extension name are tried in
    /// registration order; the first plugin to return `Some(dtype)` wins. If none
    /// match (or all return `None`), the builtin `arrow.parquet.variant` extension maps
    /// to [`DType::Variant`], and any other field converts through
    /// [`Self::from_arrow_datatype`] so extension metadata on nested element/struct
    /// fields is preserved.
    ///
    /// If the extension name of `field` is a Vortex ID that the session knows, the result is that
    /// extension type over the converted storage (see [`ArrowSession`]).
    #[expect(clippy::disallowed_methods, reason = "interning a dynamic id")]
    pub fn from_arrow_field(&self, field: &Field) -> VortexResult<DType> {
        if let DataType::Dictionary(_, value_type) = field.data_type() {
            return self
                .from_arrow_field(&field.clone().with_data_type(value_type.as_ref().clone()));
        }

        if let Some(name) = field.metadata().get(EXTENSION_TYPE_NAME_KEY) {
            for plugin in self.importers(&Id::new(name)).iter() {
                if let Some(dtype) = plugin.from_arrow_field(field, self)? {
                    return Ok(dtype);
                }
            }
            // Parquet Variant is understood even without a registered importer plugin.
            if name == "arrow.parquet.variant" {
                return Ok(DType::Variant(field.is_nullable().into()));
            }
        }

        let storage_dtype =
            self.from_arrow_datatype(field.data_type(), field.is_nullable().into())?;

        Ok(
            match self.rebuild_ext_dtype_by_vortex_id(field, &storage_dtype)? {
                Some(ext_dtype) => DType::Extension(ext_dtype),
                None => storage_dtype,
            },
        )
    }

    /// Build the Vortex [`DType`] for an Arrow [`DataType`].
    ///
    /// Recurses into container types ([`DataType::List`] family, [`DataType::FixedSizeList`],
    /// [`DataType::Struct`], [`DataType::Map`], [`DataType::RunEndEncoded`]) via
    /// [`Self::from_arrow_field`] so extension metadata on nested fields dispatches through
    /// registered import plugins. Leaf types use the canonical Arrow → Vortex mapping.
    ///
    /// [`DataType::Dictionary`] is a partial exception: Arrow models its values as a bare
    /// [`DataType`] rather than a [`Field`], so the values themselves cannot carry an extension
    /// name. Fields nested *inside* that data type still do, and are dispatched normally.
    pub fn from_arrow_datatype(
        &self,
        data_type: &DataType,
        nullability: Nullability,
    ) -> VortexResult<DType> {
        Ok(match data_type {
            DataType::List(elem)
            | DataType::LargeList(elem)
            | DataType::ListView(elem)
            | DataType::LargeListView(elem) => {
                DType::List(Arc::new(self.from_arrow_field(elem.as_ref())?), nullability)
            }
            DataType::FixedSizeList(elem, size) => DType::FixedSizeList(
                Arc::new(self.from_arrow_field(elem.as_ref())?),
                *size as u32,
                nullability,
            ),
            DataType::Map(entries, keys_sorted) => {
                vortex_ensure!(
                    !entries.is_nullable(),
                    "Arrow map entries field must be non-nullable"
                );
                let DataType::Struct(fields) = entries.data_type() else {
                    vortex_bail!(
                        "Arrow map entries field must have Struct type, got {:?}",
                        entries.data_type()
                    );
                };
                vortex_ensure_eq!(
                    fields.len(),
                    2,
                    "Arrow map entries struct must contain exactly two fields"
                );
                vortex_ensure!(
                    !fields[0].is_nullable(),
                    "Arrow map key field must be non-nullable"
                );
                DType::map(
                    self.from_arrow_field(fields[0].as_ref())?,
                    self.from_arrow_field(fields[1].as_ref())?,
                    *keys_sorted,
                    nullability,
                )?
            }
            DataType::Struct(fields) => DType::Struct(self.from_arrow_fields(fields)?, nullability),
            DataType::Dictionary(_, value_type) => {
                self.from_arrow_datatype(value_type.as_ref(), nullability)?
            }
            DataType::RunEndEncoded(_, value_field) => {
                self.from_arrow_field(&run_end_values_field(value_field, nullability))?
            }
            _ => from_arrow_data_type(data_type, nullability)?,
        })
    }

    /// Build Vortex [`StructFields`] for Arrow [`Fields`], dispatching each field through
    /// [`Self::from_arrow_field`].
    pub fn from_arrow_fields(&self, fields: &Fields) -> VortexResult<StructFields> {
        fields
            .iter()
            .map(|f| {
                self.from_arrow_field(f)
                    .map(|dt| (FieldName::from(f.name().as_str()), dt))
            })
            .collect::<VortexResult<StructFields>>()
    }

    /// Build the Vortex [`DType`] for an Arrow [`Schema`], dispatching extension fields
    /// through registered import plugins. The result is a top-level non-nullable struct
    /// matching the schema's fields.
    pub fn from_arrow_schema(&self, schema: &Schema) -> VortexResult<DType> {
        Ok(DType::Struct(
            self.from_arrow_fields(schema.fields())?,
            Nullability::NonNullable,
        ))
    }

    /// Decode an Arrow [`RecordBatch`] into a Vortex struct array, dispatching each
    /// extension column through its registered import plugin.
    ///
    /// `schema` is the authoritative Arrow schema used for dispatch — the columns are
    /// consumed positionally. Pass an external schema (rather than relying on
    /// `batch.schema()`) when upstream DataFusion plumbing may have stripped Field-level
    /// extension metadata from the runtime RecordBatch.
    pub fn from_arrow_record_batch(
        &self,
        batch: RecordBatch,
        schema: &Schema,
    ) -> VortexResult<ArrayRef> {
        vortex_ensure_eq!(batch.num_columns(), schema.fields().len());
        let length = batch.num_rows();
        let names = FieldNames::from_iter(
            schema
                .fields()
                .iter()
                .map(|f| FieldName::from(f.name().as_str())),
        );
        let mut columns = Vec::with_capacity(schema.fields().len());
        for (col, field) in batch.columns().iter().zip(schema.fields().iter()) {
            columns.push(self.from_arrow_array_inner(ArrowArrayRef::clone(col), field)?);
        }
        Ok(StructArray::try_new(names, columns, length, Validity::NonNullable)?.into_array())
    }

    /// Execute a Vortex array into an Arrow array.
    ///
    /// If `target` carries an `ARROW:extension:name`, the plugin registry is probed for one that
    /// can support executing to the target extension type. If no plugin accepts it, but the
    /// extension name is the Vortex ID of the array, the array exports its storage (see
    /// [`ArrowSession`]).
    ///
    /// With `target = None`, the export uses the field from [`Self::default_arrow_export_field`],
    /// so it fails for the same types. If that field has an Arrow extension name, the plugins
    /// export the array to it, as above. Otherwise, the array exports to its preferred Arrow type,
    /// and each nested extension type exports through its plugin, or as its storage plus Arrow
    /// extension metadata.
    ///
    /// Uses the default [`ArrowExportOptions`]; see [`exporter`](Self::exporter) to
    /// change them.
    pub fn execute_arrow(
        &self,
        array: ArrayRef,
        target: Option<&Field>,
        ctx: &mut ExecutionCtx,
    ) -> VortexResult<ArrowArrayRef> {
        self.exporter(&ArrowExportOptions::default())
            .execute_arrow(array, target, ctx)
    }

    /// Return an exporter that applies `options` to its exports.
    ///
    /// ```
    /// use arrow_array::Array;
    /// use vortex_array::IntoArray;
    /// use vortex_array::VortexSessionExecute;
    /// use vortex_session::VortexSession;
    /// use vortex_array::arrays::VarBinViewArray;
    /// use vortex_arrow::ArrowExportOptions;
    /// use vortex_arrow::ArrowSessionExt;
    /// use vortex_arrow::CompactBuffers;
    ///
    /// let session = VortexSession::empty();
    /// let array = VarBinViewArray::from_iter_str(["a", "b"]).into_array();
    /// let options = ArrowExportOptions::default().with(CompactBuffers(false));
    /// let arrow = session.arrow().exporter(&options).execute_arrow(
    ///     array,
    ///     None,
    ///     &mut session.create_execution_ctx(),
    /// )?;
    /// assert_eq!(arrow.len(), 2);
    /// # Ok::<(), vortex_error::VortexError>(())
    /// ```
    pub fn exporter<'a>(&'a self, options: &'a ArrowExportOptions) -> ArrowExporter<'a> {
        ArrowExporter {
            session: self,
            options,
        }
    }

    /// Decode an Arrow array into a Vortex array.
    ///
    /// `field` describes the Arrow type the array is imported from: pass an Arrow [`Field`] when
    /// one is available, or just the desired nullability (`true` / `false` /
    /// [`Nullability`]) to synthesize an anonymous field from the array's own data type. See
    /// [`IntoArrowField`] for the trade-off between the two.
    ///
    /// Routes through the registered import plugin if `field` carries an Arrow extension
    /// name we recognize, probing each plugin in registration order until one handles the
    /// input or all return [`ArrowImport::Unsupported`]. Otherwise recurses into container
    /// arrays ([`arrow_array::StructArray`], [`arrow_array::GenericListArray`],
    /// [`arrow_array::FixedSizeListArray`], [`arrow_array::GenericListViewArray`]) so
    /// extension fields nested inside containers reach their importers; leaf types fall
    /// through to the canonical Arrow → Vortex array conversion.
    ///
    /// If the extension name of `field` is a Vortex ID that the session knows, the import wraps the
    /// converted array in that extension type (see [`ArrowSession`]).
    ///
    /// A dictionary array imports as a [`DictArray`]. Its values import as described above, with
    /// `field`'s metadata.
    ///
    /// # Errors
    ///
    /// Returns an error if the field (or requested nullability) is non-nullable but the array
    /// physically contains nulls, or if the Arrow data type is unsupported.
    pub fn from_arrow_array<'a>(
        &self,
        array: ArrowArrayRef,
        field: impl IntoArrowField<'a>,
    ) -> VortexResult<ArrayRef> {
        let field = field.into_arrow_field(array.data_type());
        self.from_arrow_array_inner(array, field.as_ref())
    }

    /// [`Self::from_arrow_array`] with the Arrow [`Field`] already resolved: peel a dictionary,
    /// probe the import plugins registered for the field's extension name, then fall back to the
    /// canonical conversion. If the extension name of the field is a Vortex ID that the session
    /// knows, the result is wrapped in that extension type. Also the recursion point for nested
    /// fields, which already have a [`Field`].
    #[allow(clippy::wrong_self_convention)]
    fn from_arrow_array_inner(
        &self,
        array: ArrowArrayRef,
        field: &Field,
    ) -> VortexResult<ArrayRef> {
        if let DataType::Dictionary(..) = field.data_type() {
            return self.dictionary_from_arrow(array.as_ref(), field);
        }

        let mut current = array;

        if let Some(extension_name) = field.metadata().get(EXTENSION_TYPE_NAME_KEY) {
            #[expect(clippy::disallowed_methods, reason = "interning a dynamic id")]
            let importers = self.importers(&Id::new(extension_name));
            if !importers.is_empty() {
                let dtype = self.from_arrow_field(field)?;
                let len = current.len();

                for plugin in importers.iter() {
                    match plugin.from_arrow_array(current, field, &dtype, self)? {
                        // Parents such as lists reuse the Arrow offsets into this array without
                        // checking them again, so a plugin must preserve its length, both in what
                        // it imports and in what it hands back when it declines.
                        ArrowImport::Imported(arr) => {
                            vortex_ensure_eq!(
                                arr.len(),
                                len,
                                "Arrow importer {} returned {} elements for an array of {}",
                                plugin.arrow_ext_id(),
                                arr.len(),
                                len
                            );
                            return Ok(arr);
                        }
                        ArrowImport::Unsupported(arr) => {
                            vortex_ensure_eq!(
                                arr.len(),
                                len,
                                "Arrow importer {} declined and returned {} elements for an array of {}",
                                plugin.arrow_ext_id(),
                                arr.len(),
                                len
                            );
                            current = arr;
                        }
                    }
                }
            }
        }

        let imported = self.from_arrow_array_canonical(current.as_ref(), field)?;

        match self.rebuild_ext_dtype_by_vortex_id(field, imported.dtype())? {
            Some(ext_dtype) => Ok(ExtensionArray::try_new(ext_dtype, imported)?.into_array()),
            None => Ok(imported),
        }
    }

    /// Recurse into Arrow container arrays so nested fields with extension metadata reach
    /// their importers, falling through to the canonical conversion for leaf types.
    #[allow(clippy::wrong_self_convention)]
    fn from_arrow_array_canonical(
        &self,
        array: &dyn ArrowArray,
        field: &Field,
    ) -> VortexResult<ArrayRef> {
        match field.data_type() {
            DataType::Struct(fields) => {
                let arrow_struct = array.as_struct();
                let names = FieldNames::from_iter(
                    fields.iter().map(|f| FieldName::from(f.name().as_str())),
                );
                let columns = arrow_struct
                    .columns()
                    .iter()
                    .zip(fields.iter())
                    .map(|(col, child_field)| {
                        // Arrow pushes nulls into non-nullable fields; strip before recursing
                        // so Vortex's stricter validity invariants are upheld.
                        let inner = if col.null_count() > 0 && !child_field.is_nullable() {
                            make_array(remove_nulls(col.to_data())?)
                        } else {
                            ArrowArrayRef::clone(col)
                        };
                        self.from_arrow_array_inner(inner, child_field.as_ref())
                    })
                    .collect::<VortexResult<Vec<_>>>()?;
                let validity = nulls(arrow_struct.nulls(), field.is_nullable())?;
                Ok(
                    StructArray::try_new(names, columns, arrow_struct.len(), validity)?
                        .into_array(),
                )
            }
            DataType::List(elem_field) => {
                let list = array.as_list::<i32>();
                let (offsets, referenced) = trim_offsets(list.offsets());
                let elements = self.from_arrow_array(
                    list.values().slice(referenced.start, referenced.len()),
                    elem_field.as_ref(),
                )?;
                let validity = nulls(list.nulls(), field.is_nullable())?;
                // SAFETY: Arrow offsets are non-negative and sorted, and `trim_offsets` rebases
                // them onto the referenced values. The validity has one entry per list.
                Ok(
                    unsafe { ListArray::new_unchecked(elements, offsets.into_array(), validity) }
                        .into_array(),
                )
            }
            DataType::LargeList(elem_field) => {
                let list = array.as_list::<i64>();
                let (offsets, referenced) = trim_offsets(list.offsets());
                let elements = self.from_arrow_array(
                    list.values().slice(referenced.start, referenced.len()),
                    elem_field.as_ref(),
                )?;
                let validity = nulls(list.nulls(), field.is_nullable())?;
                // SAFETY: Arrow offsets are non-negative and sorted, and `trim_offsets` rebases
                // them onto the referenced values. The validity has one entry per list.
                Ok(
                    unsafe { ListArray::new_unchecked(elements, offsets.into_array(), validity) }
                        .into_array(),
                )
            }
            DataType::FixedSizeList(elem_field, list_size) => {
                let fsl = array.as_fixed_size_list();
                let elements = self.from_arrow_array_inner(
                    ArrowArrayRef::clone(fsl.values()),
                    elem_field.as_ref(),
                )?;
                let validity = nulls(fsl.nulls(), field.is_nullable())?;
                Ok(
                    FixedSizeListArray::try_new(elements, *list_size as u32, validity, fsl.len())?
                        .into_array(),
                )
            }
            DataType::ListView(elem_field) => {
                let list = array.as_list_view::<i32>();
                let elements = self
                    .from_arrow_array(ArrowArrayRef::clone(list.values()), elem_field.as_ref())?;
                let offsets = list.offsets().clone().into_array();
                let sizes = list.sizes().clone().into_array();
                let validity = nulls(list.nulls(), field.is_nullable())?;
                // SAFETY: Arrow list views share one integer type for offsets and sizes, and every
                // view lies within the values. The validity has one entry per list.
                Ok(
                    unsafe { ListViewArray::new_unchecked(elements, offsets, sizes, validity) }
                        .into_array(),
                )
            }
            DataType::LargeListView(elem_field) => {
                let list = array.as_list_view::<i64>();
                let elements = self
                    .from_arrow_array(ArrowArrayRef::clone(list.values()), elem_field.as_ref())?;
                let offsets = list.offsets().clone().into_array();
                let sizes = list.sizes().clone().into_array();
                let validity = nulls(list.nulls(), field.is_nullable())?;
                // SAFETY: Arrow list views share one integer type for offsets and sizes, and every
                // view lies within the values. The validity has one entry per list.
                Ok(
                    unsafe { ListViewArray::new_unchecked(elements, offsets, sizes, validity) }
                        .into_array(),
                )
            }
            DataType::Map(entries_field, keys_sorted) => {
                let map = array.as_map();
                let (entries, offsets) = trim_map_entries(map);
                let entries_array: ArrowArrayRef = Arc::new(entries);
                let entries = self.from_arrow_array_inner(entries_array, entries_field.as_ref())?;
                map_from_arrow_parts(
                    entries,
                    &offsets,
                    map.nulls(),
                    *keys_sorted,
                    field.is_nullable(),
                )
            }
            DataType::RunEndEncoded(ends_field, values_field) => {
                let values_field = run_end_values_field(values_field, field.is_nullable().into());
                match ends_field.data_type() {
                    DataType::Int16 => self.run_end_from_arrow::<Int16Type>(array, &values_field),
                    DataType::Int32 => self.run_end_from_arrow::<Int32Type>(array, &values_field),
                    DataType::Int64 => self.run_end_from_arrow::<Int64Type>(array, &values_field),
                    ends_dt => vortex_bail!(
                        "Arrow run-end array run ends must be Int16, Int32 or Int64, got {ends_dt}"
                    ),
                }
            }
            _ => from_arrow_dyn(array, field.is_nullable()),
        }
    }

    /// Decode an Arrow run-end array, recursing into its values so extension metadata on the
    /// values field reaches its importer.
    #[allow(clippy::wrong_self_convention)]
    fn run_end_from_arrow<R: RunEndIndexType>(
        &self,
        array: &dyn ArrowArray,
        values_field: &Field,
    ) -> VortexResult<ArrayRef>
    where
        R::Native: NativePType,
    {
        let run_array = array
            .as_any()
            .downcast_ref::<RunArray<R>>()
            .ok_or_else(|| vortex_err!("expected an Arrow RunArray, got {}", array.data_type()))?;
        run_end_from_arrow(run_array, |values| {
            self.from_arrow_array_inner(values, values_field)
        })
    }

    /// Decode an Arrow dictionary array into a [`DictArray`], importing its values with `field`'s
    /// metadata so that an extension name on the dictionary field reaches its importer.
    fn dictionary_from_arrow(
        &self,
        array: &dyn ArrowArray,
        field: &Field,
    ) -> VortexResult<ArrayRef> {
        let dict = array.as_any_dictionary_opt().ok_or_else(|| {
            vortex_err!(
                "expected an Arrow DictionaryArray, got {}",
                array.data_type()
            )
        })?;

        let values_field = field
            .clone()
            .with_data_type(dict.values().data_type().clone());
        let values =
            self.from_arrow_array_inner(ArrowArrayRef::clone(dict.values()), &values_field)?;

        let codes = dict.keys();
        let codes = from_arrow_dyn(codes, codes.is_nullable())?;

        // SAFETY: arrow-rs enforces the dictionary invariants on construction, so the codes are
        // in-bounds for the values.
        Ok(unsafe { DictArray::new_unchecked(codes, values) }.into_array())
    }
}

/// The values field of an Arrow [`DataType::RunEndEncoded`], re-stamped with the run-end array's
/// own nullability.
fn run_end_values_field(values_field: &FieldRef, nullability: Nullability) -> Field {
    values_field
        .as_ref()
        .clone()
        .with_nullable(nullability.into())
}

/// Decode the base64 `ARROW:extension:metadata` of a field whose extension name is a Vortex ID.
///
/// A field without that key has empty metadata, as Arrow allows.
fn decode_ext_metadata(field: &Field) -> VortexResult<Vec<u8>> {
    let encoded = field.extension_type_metadata().unwrap_or_default();

    BASE64_STANDARD.decode(encoded).map_err(|err| {
        vortex_err!(
            "Arrow field {:?} must carry base64 extension metadata, got {encoded:?}: {err}",
            field.name()
        )
    })
}

impl SessionVar for ArrowSession {
    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }
}

/// An [`ArrowSession`] bound to [`ArrowExportOptions`], created by [`ArrowSession::exporter`].
#[derive(Clone, Copy, Debug)]
pub struct ArrowExporter<'a> {
    session: &'a ArrowSession,
    options: &'a ArrowExportOptions,
}

impl ArrowExporter<'_> {
    pub(crate) fn options(&self) -> &ArrowExportOptions {
        self.options
    }

    /// Execute a Vortex array into an Arrow array with the bound options.
    ///
    /// Behaves like [`ArrowSession::execute_arrow`]. The options are propagated to nested arrays
    /// and to registered export plugins.
    #[expect(clippy::disallowed_methods, reason = "interning a dynamic id")]
    pub fn execute_arrow(
        &self,
        array: ArrayRef,
        target: Option<&Field>,
        ctx: &mut ExecutionCtx,
    ) -> VortexResult<ArrowArrayRef> {
        // NOTE(aduffy): this looks strange, but we do this to keep target_field as &Field so
        //  we can avoid cloning target when it is provided. It contains a HashMap internally that
        //  can be expensive to copy.
        let arrow_field;
        let target_field = match target {
            Some(field) => field,
            None => {
                arrow_field = self.session.default_arrow_export_field(array.dtype())?;
                &arrow_field
            }
        };

        if let Some(arrow_ext_name) = target_field.metadata().get(EXTENSION_TYPE_NAME_KEY) {
            let arrow_ext_id = Id::new(arrow_ext_name);

            // There can be multiple plugins that report support for a particular extension type.
            // We try them in order until one of them reports a successful conversion.
            let len = array.len();
            let mut current = array;

            for plugin in self.session.exporters(&arrow_ext_id).iter() {
                trace!(
                    plugin = ?plugin,
                    extension_name = arrow_ext_name,
                    "probing plugin for converting Arrow array"
                );

                match plugin.execute_arrow(current, target_field, self.options, ctx)? {
                    ArrowExport::Exported(arrow) => {
                        vortex_ensure_eq!(
                            arrow.len(),
                            len,
                            "Arrow array length does not match Vortex array length after conversion to {:?}",
                            arrow
                        );
                        return Ok(arrow);
                    }
                    ArrowExport::Unsupported(array) => current = array,
                }
            }

            if let Some(ext_dtype) = current
                .dtype()
                .as_extension_opt()
                .filter(|ext_dtype| ext_dtype.id() == arrow_ext_id)
                .cloned()
            {
                return self.execute_arrow_ext_storage(current, &ext_dtype, target_field, ctx);
            }

            debug!(
                extension_id = arrow_ext_name,
                data_type = ?target_field.data_type(),
                "unsupported Arrow extension type encountered, falling back to naive execution"
            );

            return execute_arrow_naive(current, Some(target_field.data_type()), self, ctx);
        }

        execute_arrow_naive(array, target.map(|field| field.data_type()), self, ctx)
    }

    /// Export the storage of `array` to `target`, whose extension name is the Vortex ID of
    /// `ext_dtype`. Fails if `target` does not have the metadata of `ext_dtype`.
    fn execute_arrow_ext_storage(
        &self,
        array: ArrayRef,
        ext_dtype: &ExtDTypeRef,
        target: &Field,
        ctx: &mut ExecutionCtx,
    ) -> VortexResult<ArrowArrayRef> {
        match self
            .session
            .rebuild_ext_dtype_by_vortex_id(target, ext_dtype.storage_dtype())?
        {
            Some(target_dtype) => vortex_ensure!(
                target_dtype == *ext_dtype,
                "Arrow field {:?} must name {ext_dtype}, got {target_dtype}",
                target.name()
            ),
            None => vortex_ensure!(
                decode_ext_metadata(target)? == ext_dtype.serialize_metadata()?,
                "Arrow field {:?} must carry the metadata of {ext_dtype}, got {:?}",
                target.name(),
                target.extension_type_metadata().unwrap_or_default()
            ),
        }

        let storage = array
            .execute::<ExtensionArray>(ctx)?
            .storage_array()
            .clone();

        execute_arrow_naive(storage, Some(target.data_type()), self, ctx)
    }
}

/// Extension trait for accessing the [`ArrowSession`] on a Vortex session.
pub trait ArrowSessionExt: SessionExt {
    /// Get the Arrow session.
    fn arrow(&self) -> SessionGuard<'_, ArrowSession>;
}

impl<S: SessionExt> ArrowSessionExt for S {
    fn arrow(&self) -> SessionGuard<'_, ArrowSession> {
        self.get::<ArrowSession>()
    }
}

#[cfg(test)]
mod tests {
    use std::ops::Range;
    use std::sync::Arc;
    use std::sync::LazyLock;

    use arrow_array::DictionaryArray;
    use arrow_array::GenericListArray;
    use arrow_array::GenericListViewArray;
    use arrow_array::Int32Array;
    use arrow_array::Int64Array;
    use arrow_array::MapArray;
    use arrow_array::StringArray;
    use arrow_array::StructArray;
    use arrow_array::types::Int32Type;
    use arrow_buffer::OffsetBuffer;
    use arrow_buffer::ScalarBuffer;
    use arrow_schema::DataType;
    use arrow_schema::Field;
    use arrow_schema::FieldRef;
    use arrow_schema::Fields;
    use rstest::rstest;
    use vortex_array::IntoArray;
    use vortex_array::VortexSessionExecute as _;
    use vortex_array::arrays::Dict;
    use vortex_array::arrays::ListArray;
    use vortex_array::arrays::PrimitiveArray;
    use vortex_array::arrays::VarBinViewArray;
    use vortex_array::assert_arrays_eq;
    use vortex_array::dtype::DType;
    use vortex_array::dtype::Nullability;
    use vortex_array::dtype::PType;
    use vortex_array::validity::Validity;
    use vortex_error::VortexResult;
    use vortex_session::VortexSession;
    use vortex_session::registry::CachedId;

    use super::*;

    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);

    #[rstest]
    #[case::prefix(0, 2)]
    #[case::middle(500, 2)]
    #[case::empty(500, 0)]
    #[case::empty_at_end(1000, 0)]
    fn test_sliced_list_imports_only_its_rows(
        #[values(false, true)] large: bool,
        #[case] start: usize,
        #[case] len: usize,
    ) -> VortexResult<()> {
        let lists = |rows: Range<i64>| -> ArrowArrayRef {
            let values = Arc::new(Int64Array::from_iter_values(
                rows.flat_map(|row| [row, row + 1]),
            ));
            let len = values.len() / 2;
            let field = Arc::new(Field::new("item", DataType::Int64, false));
            if large {
                Arc::new(GenericListArray::<i64>::new(
                    field,
                    OffsetBuffer::from_repeated_length(2, len),
                    values,
                    None,
                ))
            } else {
                Arc::new(GenericListArray::<i32>::new(
                    field,
                    OffsetBuffer::from_repeated_length(2, len),
                    values,
                    None,
                ))
            }
        };
        let session = ArrowSession::default();
        let sliced = session.from_arrow_array(lists(0..1000).slice(start, len), false)?;
        let fresh = session.from_arrow_array(lists(start as i64..(start + len) as i64), false)?;
        assert_eq!(sliced.nbytes(), fresh.nbytes());
        let mut ctx = SESSION.create_execution_ctx();
        let expected = ListArray::new(
            PrimitiveArray::from_iter(
                (start as i64..(start + len) as i64).flat_map(|row| [row, row + 1]),
            )
            .into_array(),
            PrimitiveArray::from_iter((0..=len as u64).map(|row| row * 2)).into_array(),
            Validity::NonNullable,
            &mut ctx,
        );
        assert_arrays_eq!(sliced, expected, &mut ctx);
        assert_arrays_eq!(fresh, expected, &mut ctx);
        Ok(())
    }

    #[test]
    fn from_arrow_fields_matches_schema_conversion() -> VortexResult<()> {
        let session = ArrowSession::default();
        let fields = Fields::from(vec![
            Field::new("a", DataType::Int32, false),
            Field::new("b", DataType::Utf8View, true),
        ]);
        let struct_fields = session.from_arrow_fields(&fields)?;
        let schema_dtype = session.from_arrow_schema(&Schema::new(fields))?;
        let expected = StructFields::from_iter([
            ("a", DType::Primitive(PType::I32, Nullability::NonNullable)),
            ("b", DType::Utf8(Nullability::Nullable)),
        ]);
        assert_eq!(struct_fields, expected);
        assert_eq!(
            schema_dtype,
            DType::Struct(struct_fields, Nullability::NonNullable)
        );
        Ok(())
    }

    #[test]
    fn from_arrow_field_maps_variant_without_importer() -> VortexResult<()> {
        let session = ArrowSession::default();
        let storage = DataType::Struct(
            vec![
                Field::new("metadata", DataType::BinaryView, false),
                Field::new("value", DataType::BinaryView, true),
            ]
            .into(),
        );
        let field = Field::new("v", storage, true).with_metadata(
            [(
                "ARROW:extension:name".to_string(),
                "arrow.parquet.variant".to_string(),
            )]
            .into(),
        );
        assert_eq!(
            session.from_arrow_field(&field)?,
            DType::Variant(Nullability::Nullable)
        );
        Ok(())
    }

    static REJECT_DICTIONARY_ID: CachedId = CachedId::new("test.reject_dictionary");

    /// An importer that fails on an Arrow dictionary and imports anything else as its storage.
    #[derive(Debug)]
    struct DictionaryRejectingImporter;

    impl ArrowImportVTable for DictionaryRejectingImporter {
        fn arrow_ext_id(&self) -> Id {
            *REJECT_DICTIONARY_ID
        }

        fn from_arrow_field(
            &self,
            field: &Field,
            session: &ArrowSession,
        ) -> VortexResult<Option<DType>> {
            vortex_ensure!(
                !matches!(field.data_type(), DataType::Dictionary(..)),
                "an importer must never see a dictionary field, got {}",
                field.data_type()
            );
            session
                .from_arrow_datatype(field.data_type(), field.is_nullable().into())
                .map(Some)
        }

        fn from_arrow_array(
            &self,
            array: ArrowArrayRef,
            field: &Field,
            _dtype: &DType,
            session: &ArrowSession,
        ) -> VortexResult<ArrowImport> {
            vortex_ensure!(
                !matches!(array.data_type(), DataType::Dictionary(..)),
                "an importer must never see a dictionary array, got {}",
                array.data_type()
            );
            session
                .from_arrow_array(array, field.is_nullable())
                .map(ArrowImport::Imported)
        }
    }

    /// An Arrow dictionary imports as a Vortex `Dict` array over the dictionary values, matching
    /// the dtype the schema conversion reports. The session peels the dictionary before any
    /// importer runs, so a dictionary field named for an importer that fails on dictionaries still
    /// imports.
    #[rstest]
    #[case::plain(None)]
    #[case::extension_name(Some(*REJECT_DICTIONARY_ID))]
    fn dictionary_imports_as_dict_encoding(#[case] extension_name: Option<Id>) -> VortexResult<()> {
        let session = ArrowSession::default();
        session.register_importer(Arc::new(DictionaryRejectingImporter));
        let dict: ArrowArrayRef = Arc::new(DictionaryArray::<Int32Type>::try_new(
            Int32Array::from(vec![0, 1, 0, 1]),
            Arc::new(StringArray::from(vec!["a", "b"])),
        )?);
        let metadata = extension_name
            .map(|id| (EXTENSION_TYPE_NAME_KEY.to_string(), id.to_string()))
            .into_iter()
            .collect();
        let field = Field::new("s", dict.data_type().clone(), false).with_metadata(metadata);

        let dtype = session.from_arrow_field(&field)?;
        assert_eq!(dtype, DType::Utf8(Nullability::NonNullable));

        let array = session.from_arrow_array(dict, &field)?;
        assert!(array.is::<Dict>(), "expected a Dict encoding, got {array}");
        assert_eq!(array.dtype(), &dtype);
        assert_arrays_eq!(
            array,
            VarBinViewArray::from_iter_str(["a", "b", "a", "b"]),
            &mut SESSION.create_execution_ctx()
        );
        Ok(())
    }

    static TRUNCATE_ID: CachedId = CachedId::new("test.truncate");

    /// An importer that drops the last element of every array it is given, then either imports
    /// it or declines and hands it back.
    #[derive(Debug)]
    struct TruncatingImporter {
        decline: bool,
    }

    impl ArrowImportVTable for TruncatingImporter {
        fn arrow_ext_id(&self) -> Id {
            *TRUNCATE_ID
        }

        fn from_arrow_field(
            &self,
            field: &Field,
            session: &ArrowSession,
        ) -> VortexResult<Option<DType>> {
            session
                .from_arrow_datatype(field.data_type(), field.is_nullable().into())
                .map(Some)
        }

        fn from_arrow_array(
            &self,
            array: ArrowArrayRef,
            field: &Field,
            _dtype: &DType,
            session: &ArrowSession,
        ) -> VortexResult<ArrowImport> {
            let truncated = array.slice(0, array.len() - 1);
            if self.decline {
                return Ok(ArrowImport::Unsupported(truncated));
            }
            session
                .from_arrow_array(truncated, field.is_nullable())
                .map(ArrowImport::Imported)
        }
    }

    fn truncated_field(name: &str, data_type: DataType) -> FieldRef {
        Arc::new(
            Field::new(name, data_type, false).with_metadata(
                [(
                    EXTENSION_TYPE_NAME_KEY.to_string(),
                    "test.truncate".to_string(),
                )]
                .into(),
            ),
        )
    }

    fn list_with_truncated_child() -> ArrowArrayRef {
        Arc::new(GenericListArray::<i32>::new(
            truncated_field("item", DataType::Int64),
            OffsetBuffer::new(vec![0, 5].into()),
            Arc::new(Int64Array::from_iter_values(0..5)),
            None,
        ))
    }

    fn list_view_with_truncated_child() -> ArrowArrayRef {
        Arc::new(GenericListViewArray::<i32>::new(
            truncated_field("item", DataType::Int64),
            ScalarBuffer::from(vec![0]),
            ScalarBuffer::from(vec![5]),
            Arc::new(Int64Array::from_iter_values(0..5)),
            None,
        ))
    }

    fn map_with_truncated_child() -> ArrowArrayRef {
        let key_field = Arc::new(Field::new("key", DataType::Int64, false));
        let value_field = Arc::new(Field::new("value", DataType::Int64, false));
        let entries = StructArray::new(
            Fields::from(vec![key_field, value_field]),
            vec![
                Arc::new(Int64Array::from_iter_values(0..5)),
                Arc::new(Int64Array::from_iter_values(5..10)),
            ],
            None,
        );
        Arc::new(MapArray::new(
            truncated_field("entries", entries.data_type().clone()),
            OffsetBuffer::new(vec![0, 5].into()),
            entries,
            None,
            false,
        ))
    }

    #[rstest]
    #[case::list(list_with_truncated_child())]
    #[case::list_view(list_view_with_truncated_child())]
    #[case::map(map_with_truncated_child())]
    fn test_rejects_importer_that_changes_child_length(
        #[case] array: ArrowArrayRef,
        #[values(false, true)] decline: bool,
    ) {
        let session = ArrowSession::default();
        session.register_importer(Arc::new(TruncatingImporter { decline }));

        let err = session
            .from_arrow_array(array, false)
            .expect_err("a child importer that drops elements must be rejected");
        assert!(
            err.to_string()
                .contains("returned 4 elements for an array of 5"),
            "unexpected error: {err}"
        );
    }
}