vortex-arrow 0.94.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
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
// 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. [`ArrowImportVTable`] states when an importer may defer.
//!
//! 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::GenericListArray;
use arrow_array::GenericListViewArray;
use arrow_array::OffsetSizeTrait;
use arrow_array::RecordBatch;
use arrow_array::cast::AsArray;
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_NAME_KEY;
use vortex_array::ArrayRef;
use vortex_array::ExecutionCtx;
use vortex_array::IntoArray;
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::dtype::DType;
use vortex_array::dtype::FieldName;
use vortex_array::dtype::FieldNames;
use vortex_array::dtype::IntegerPType;
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::DTypeSessionExt;
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::import_dictionary;
use crate::convert::map_from_arrow_parts;
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::ext_metadata::decode_arrow_ext_metadata;
use crate::ext_metadata::encode_arrow_ext_metadata;
use crate::import_nullability::level_validity;
use crate::import_nullability::storage_import_field;
use crate::run_end_import::run_end_from_arrow_dyn;

/// 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`].
///
/// A plugin that defers the supplied array returns [`Unsupported`][Self::Unsupported] with
/// ownership of the input so the session can probe the next plugin or fall back to the canonical
/// path. [`ArrowImportVTable`] states when a plugin may defer. Errors are propagated through
/// [`VortexResult`].
pub enum ArrowImport {
    /// The plugin defers 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.
///
/// A successful export **must** preserve the logical value of each row, including nulls. The
/// physical layout can change. For example, a UUID stored as a fixed-size list of 16 bytes can
/// export as Arrow `FixedSizeBinary(16)` with the same bytes.
///
/// Importing an inferred field with [`ArrowSession::from_arrow_field`] **must** recover the
/// complete Vortex dtype passed to [`ArrowSession::to_arrow_field`], including extension IDs,
/// metadata, storage, and nullability at every nesting level. Exporting and importing an array
/// with that field **must** recover the original dtype and values. Several Arrow representations
/// can import as the same Vortex dtype.
///
/// Prefer [`crate::ArrowExtVTable`] for automatic Vortex metadata transport.
///
/// This is purely an implementation trait, its methods should not be called directly. Instead,
/// use [`ExecuteArrowExt`] to export an array, and the methods on [`ArrowSession`] to convert a
/// dtype.
///
/// [`ExecuteArrowExt`]: crate::ExecuteArrowExt
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, through [`ExecuteArrowExt::execute_arrow_with_options`]. The [`ArrowSession`]
    /// of `ctx` is the session of the export, so a plugin that needs one must use it.
    ///
    /// # Exported values
    ///
    /// Every export **must** preserve the nulls of `array`.
    ///
    /// If `array` has an extension dtype and the output type supports the Arrow comparison kernels,
    /// the export **must** preserve equality and order. Two non-null exported values compare the
    /// same way in Arrow as their storage values compare in Vortex. Nested Arrow types only have
    /// the null requirement.
    ///
    /// The comparison rule holds across batches in one Arrow representation. To push a comparison
    /// down to Vortex storage, an engine also needs to know that both operands use compatible
    /// representations. Two exporters can each preserve order and still encode equal storage
    /// values differently. A round trip alone does not even ensure that one exporter preserves
    /// order. An exporter can reverse the bytes of each value and undo that change on import.
    ///
    /// A plugin that breaks these rules gives incorrect query results instead of an error. It does
    /// not cause memory unsafety. `test_harness::check_arrow` checks both rules for one array.
    ///
    /// [`ExecuteArrowExt::execute_arrow_with_options`]: crate::ExecuteArrowExt::execute_arrow_with_options
    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.
///
/// A successful import **must** preserve each logical Arrow value as described by the field,
/// applying the [import nullability rules](ArrowSession::from_arrow_array) at each level.
/// The returned array must have the dtype inferred from the field, as checked by [`ArrowSession`].
/// See [`ArrowExportVTable`] for the Vortex-to-Arrow round-trip contract.
///
/// Prefer [`crate::ArrowExtVTable`] for automatic Vortex metadata transport.
///
/// Plugins are dispatched by `arrow_ext_id`. The session peels Arrow dictionaries before it
/// dispatches. The session uses the dictionary field's metadata to import the values because
/// Arrow gives dictionary values a bare [`DataType`]. It then wraps the imported values in a
/// [`vortex_array::arrays::DictArray`] with the dictionary's codes. Run-end values carry their
/// own [`Field`] and metadata.
///
/// A plugin **must** defer only an input that another plugin under the same Arrow extension name
/// owns, by returning `None` from [`from_arrow_field`][Self::from_arrow_field] or
/// [`ArrowImport::Unsupported`] from [`from_arrow_array`][Self::from_arrow_array]. An input that no
/// plugin takes imports as plain storage and loses its type, so a field or array that names the
/// plugin's type but falls outside its domain is an error instead. The `arrow.parquet.variant`
/// importer is the known exception: it still defers a variant array that is not a struct.
///
/// 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), or `None` to defer it.
    ///
    /// `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`] to defer it.
    ///
    /// The importer receives the Arrow nulls as supplied. It **must** apply the
    /// [import nullability rules](ArrowSession::from_arrow_array) to each level it converts.
    /// Use [`ArrowSession::from_arrow_storage`] when the Arrow layout matches the storage layout
    /// of `dtype`. When importing storage with another layout, pass a nullability to
    /// [`ArrowSession::from_arrow_array`] to avoid dispatching this plugin 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.
///
/// The session checks inferred fields and the dtypes of successful plugin imports. See
/// [`ArrowExportVTable`] and [`ArrowImportVTable`] for the conversion contracts. The importing
/// session must register the owning dtype and any Arrow plugins used for the conversion.
///
/// An Arrow reader observes exported values before any Vortex importer runs.
/// [`ArrowExportVTable::execute_arrow`] defines the null and comparison rules for those values.
///
/// Explicit export targets may request a different dtype. Unknown Vortex IDs import as storage.
///
/// A plugin converts one Vortex extension type to and from an Arrow extension type. The crate that
/// owns the type registers its plugin, as `vortex-uuid` does. Temporal types need no plugin,
/// because Arrow has native types for them.
///
/// Every [`ArrowSession`] belongs to a [`VortexSession`], which creates it on first use of
/// [`ArrowSessionExt::arrow`]. An export takes no session, because it uses the session of its
/// [`ExecutionCtx`] (see [`ExecuteArrowExt`]). So one export cannot mix the plugins of two sessions.
///
/// An extension type without a plugin exports as its storage, and the Arrow field records the type
/// so that an import can restore it. `ARROW:extension:name` holds the Vortex ID, and
/// `ARROW:extension:metadata` holds the metadata in base64, since Arrow metadata must be UTF-8
/// ([`ext_metadata`] describes the format). DataFusion compares this metadata when it merges file
/// schemas, so [`ExtDTypeRef::serialize_metadata`] must give equal bytes for equal types.
///
/// A caller can also export an array to a field that names its Vortex ID, such as a field from
/// [`Self::to_arrow_storage_field`]. The export then checks that the field describes the type of
/// the array. Registered importers read the field's metadata in the plugin's format and must infer
/// the same dtype apart from outer nullability. Without a matching importer, the metadata must
/// decode to the bytes returned by [`ExtDTypeRef::serialize_metadata`]. Its Arrow type must also
/// import as the storage type (or as the type itself, such as an Arrow timestamp). Nested extension
/// types count as their storage types in this check, and the export checks each nested field when
/// it reaches it. Without these checks, values could silently change meaning, such as milliseconds
/// that read back as seconds. For the same reason, an extension array cannot export to a field that
/// names a different known Vortex ID.
///
/// On import, the plugins run first. If none applies, a field that names a known Vortex ID imports
/// as that type over its storage, and a field with any other name imports as plain storage. A
/// Vortex ID is known if its type is registered in the [`DTypeSession`] of the same
/// [`VortexSession`], even after the first use of the Arrow session. The Arrow session keeps the
/// registry of the [`DTypeSession`] that existed at its first use, so it does not see a new
/// [`DTypeSession`] that later replaces it through [`VortexSession::register`].
///
/// A map's entries field only groups the key and value fields. Both dtype and array imports ignore
/// its extension name so it remains a plain struct. Key and value fields still reach their
/// importers.
///
/// [`ExecuteArrowExt`]: crate::ExecuteArrowExt
/// [`ext_metadata`]: crate::ext_metadata
/// [`VortexSession`]: vortex_session::VortexSession
/// [`VortexSession::register`]: vortex_session::VortexSession::register
#[derive(Clone, Debug)]
pub struct ArrowSession {
    exporters: ArrowExporterRegistry,
    exporters_by_vortex: VortexExporterRegistry,
    importers: ArrowImporterRegistry,
    /// The extension dtypes that the session can look up by Vortex ID. This is the registry of a
    /// [`DTypeSession`], so dtypes that are registered there later are also found.
    ext_dtypes: ExtDTypeRegistry,
}

impl ArrowSession {
    /// Create a session without plugins that can look up the extension dtypes of `dtype_session`
    /// by Vortex ID.
    fn new(dtype_session: &DTypeSession) -> Self {
        Self {
            exporters: ArrowExporterRegistry::default(),
            exporters_by_vortex: VortexExporterRegistry::default(),
            importers: ArrowImporterRegistry::default(),
            ext_dtypes: dtype_session.registry().clone(),
        }
    }

    /// 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);
    }

    pub(crate) 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 through [`Self::to_arrow_storage_field`].
    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_storage_field(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(),
                )]))
            }
            _ => 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)? {
                // Check the completed field through normal routing because another importer can
                // take precedence over the exporter that inferred it.
                vortex_ensure_eq!(
                    self.from_arrow_field(&field)?,
                    dtype,
                    "Arrow field {:?} must preserve its Vortex dtype",
                    name
                );

                return Ok(Some(field));
            }
        }

        Ok(None)
    }

    /// Returns the storage field of `ext_dtype`, with field metadata that holds the extension type
    /// ([`ext_metadata`] describes the format).
    ///
    /// A type with its own Arrow type can also export to this field, for example to export a
    /// timestamp column as `Int64` and import it back as a timestamp.
    ///
    /// Fails if the storage field already has an Arrow extension name.
    ///
    /// [`ext_metadata`]: crate::ext_metadata
    pub fn to_arrow_storage_field(
        &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}"
            );
        }

        field
            .metadata_mut()
            .extend(encode_arrow_ext_metadata(ext_dtype)?);

        Ok(field)
    }

    /// Returns whether an export of `ext_dtype` to `field` produces exactly its storage.
    ///
    /// A caller can use the answer to plan reads into the storage without the array. The export
    /// produces the storage only when `field` names the Vortex ID of `ext_dtype` and passes the
    /// checks that the [`ArrowSession`] docs describe for such a field. A registered exporter can
    /// produce any data for the same field, so a name with an exporter gives `false`.
    ///
    /// The answer covers only the top level of `field`. Each storage child exports to its own
    /// field, which can name another exporter. [`Self::exports_without_plugins`] checks for
    /// exporters at every depth.
    #[expect(clippy::disallowed_methods, reason = "interning a dynamic id")]
    pub fn exports_extension_storage(&self, ext_dtype: &ExtDTypeRef, field: &Field) -> bool {
        // A dictionary or run-end encoded field holds the storage values behind an encoding, so
        // its Arrow data is not the storage, even though it can import as the storage dtype.
        if matches!(
            field.data_type(),
            DataType::Dictionary(..) | DataType::RunEndEncoded(..)
        ) {
            return false;
        }

        let Some(name) = field.extension_type_name() else {
            return false;
        };
        let id = Id::new(name);

        // The export tries the registered exporters before the storage route.
        if !self.exporters(&id).is_empty() {
            return false;
        }

        // The storage route needs a name that the session resolves to the Vortex ID of
        // `ext_dtype`. The name can be an alias of that ID.
        if self.known_vortex_id(&id) != Some(ext_dtype.id()) {
            return false;
        }

        // The export fails unless the field describes `ext_dtype`.
        if self.ensure_ext_storage_metadata(ext_dtype, field).is_err() {
            return false;
        }

        // The export also accepts some Arrow types that import as another dtype, such as an Arrow
        // timestamp, which imports as the extension type itself. Only an exact match means that
        // the Arrow data has the type of the storage.
        self.from_arrow_datatype(field.data_type(), ext_dtype.nullability())
            .is_ok_and(|dtype| &dtype == ext_dtype.storage_dtype())
    }

    /// Returns whether exporting to `field` uses only the built-in conversions at every depth.
    ///
    /// A registered exporter can choose the Arrow representation even if the field also supports
    /// a built-in conversion. The answer is conservative because the plugin can defer at runtime.
    pub fn exports_without_plugins(&self, field: &Field) -> bool {
        !field_uses_plugin(field, &|id| !self.exporters(id).is_empty())
    }

    /// Returns whether importing from `field` uses only the built-in conversions at every depth.
    ///
    /// A registered importer can transform values before Vortex sees them, even if the outer field
    /// has no extension name.
    pub fn imports_without_plugins(&self, field: &Field) -> bool {
        !field_uses_plugin(field, &|id| !self.importers(id).is_empty())
    }

    /// Fails unless `field`, which names the Vortex ID of `ext_dtype`, describes `ext_dtype`.
    ///
    /// An importer that recognizes `field` reads its metadata in the plugin's format, so the check
    /// asks the importer first, as [`Self::infer_field_dtype_with_importers`] explains. Without
    /// one, the field must carry the metadata of `ext_dtype`.
    pub(crate) fn ensure_ext_storage_metadata(
        &self,
        ext_dtype: &ExtDTypeRef,
        field: &Field,
    ) -> VortexResult<()> {
        let Some(importer_dtype) = self.infer_field_dtype_with_importers(field)? else {
            return ensure_ext_metadata(field, &decode_arrow_ext_metadata(field)?, ext_dtype);
        };

        vortex_ensure_eq!(
            importer_dtype.as_nullable(),
            DType::Extension(ext_dtype.with_nullability(Nullability::Nullable)),
            "Arrow field {:?} must describe the source extension type",
            field.name()
        );

        Ok(())
    }

    /// Returns the Vortex ID that the extension name `id` resolves to, or `None` if the session does
    /// not know it. The registry can hold an alias, so the result can differ from `id`.
    pub(crate) fn known_vortex_id(&self, id: &Id) -> Option<ExtId> {
        self.ext_dtypes
            .get(id)
            .map(|ext_dtype_plugin| ext_dtype_plugin.id())
    }

    /// Returns the extension type that `field` names by Vortex ID, to wrap around `storage_dtype`.
    ///
    /// Returns `None` if the session does not know that Vortex ID, or if `storage_dtype` already is
    /// that type, such as an Arrow timestamp that names `vortex.timestamp`. Fails if the metadata
    /// of `field` does not fit the type.
    fn ext_dtype_to_wrap(
        &self,
        field: &Field,
        storage_dtype: &DType,
    ) -> VortexResult<Option<ExtDTypeRef>> {
        let Some(extension_name) = field.extension_type_name() else {
            return Ok(None);
        };
        #[expect(clippy::disallowed_methods, reason = "interning a dynamic id")]
        let Some(ext_dtype_plugin) = self.ext_dtypes.get(&Id::new(extension_name)) else {
            return Ok(None);
        };
        let metadata = decode_arrow_ext_metadata(field)?;

        // Wrapping a storage that already is the type would nest the type inside itself.
        let existing_ext_dtype = storage_dtype
            .as_extension_opt()
            .filter(|ext_dtype| ext_dtype.id() == ext_dtype_plugin.id());
        if let Some(existing_ext_dtype) = existing_ext_dtype {
            ensure_ext_metadata(field, &metadata, existing_ext_dtype)?;
            return Ok(None);
        }

        ext_dtype_plugin
            .deserialize(&metadata, 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 no plugin is
    /// registered, or every plugin defers the field as [`ArrowImportVTable`] allows, 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 no plugin recognizes `field` and its extension name is a known Vortex ID, the result is
    /// that extension type over the converted storage (see [`ArrowSession`]).
    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(dtype) = self.infer_field_dtype_with_importers(field)? {
            return Ok(dtype);
        }

        // Parquet Variant is understood even without a registered importer plugin.
        if field.extension_type_name() == Some("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.ext_dtype_to_wrap(field, &storage_dtype)? {
            Some(ext_dtype) => DType::Extension(ext_dtype),
            None => storage_dtype,
        })
    }

    /// Returns the dtype that the importers registered for the extension name of `field` infer.
    ///
    /// Returns `None` if `field` has no extension name or if no importer recognizes it.
    ///
    /// An importer owns the format of its Arrow metadata, which can differ from the Vortex wire
    /// metadata of the same type. For example, a plugin can store unmarked base64, which
    /// [`decode_arrow_ext_metadata`] reads as UTF-8 text. So import and export both ask the
    /// importer which type a field describes before they compare any metadata bytes.
    #[expect(clippy::disallowed_methods, reason = "interning a dynamic id")]
    pub(crate) fn infer_field_dtype_with_importers(
        &self,
        field: &Field,
    ) -> VortexResult<Option<DType>> {
        let Some(name) = field.extension_type_name() else {
            return Ok(None);
        };

        for plugin in self.importers(&Id::new(name)).iter() {
            let dtype = plugin.from_arrow_field(field, self).map_err(|err| {
                err.with_context(format!(
                    "Failed to import Arrow field {:?} as {name}",
                    field.name()
                ))
            })?;
            if let Some(dtype) = dtype {
                return Ok(Some(dtype));
            }
        }

        Ok(None)
    }

    /// 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())
    }

    /// Decode an Arrow array into a Vortex array.
    ///
    /// Pass a [`Field`] to supply the Arrow schema and its extension metadata. Pass a `bool`
    /// or [`Nullability`] to use the array's data type and set the root nullability. See
    /// [`IntoArrowField`].
    ///
    /// For a field with a registered Arrow extension name, the session tries its importers in
    /// registration order until one handles the array or all return [`ArrowImport::Unsupported`].
    /// Nested fields also reach their importers when the session converts a container.
    ///
    /// If no plugin imports the array and the extension name of `field` is a known Vortex ID,
    /// the import wraps the converted storage in that extension type (see [`ArrowSession`]).
    ///
    /// Each level follows its own declared nullability. Nullable levels keep their validity.
    /// Non-nullable storage leaves fill nulls with the zero of their type, such as `0`, `false`,
    /// or `""`. Non-nullable containers drop their validity and keep their contents, so a null
    /// list with no elements becomes an empty list. Each child follows its own field, even under
    /// a null parent row.
    ///
    /// The fill uses the storage type's zero even when it falls outside the extension's domain.
    /// For example, a JSON slot can become `""`.
    ///
    /// A non-nullable dictionary imports null keys as references to entry zero. If there are
    /// keys but no values, the import adds one entry by importing a single null Arrow row of the
    /// value type under these rules. So a leaf value is its zero, and a struct value is a valid
    /// row whose nullable fields stay null.
    /// A run-end encoded array applies the requested nullability to its run values.
    ///
    /// # Errors
    ///
    /// Returns an error for unsupported Arrow types, including Arrow `Null` with a non-nullable
    /// request, or if an import plugin rejects the field or array.
    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())
    }

    /// Import `array`, which holds the Arrow form of the storage of `ext`, as an array of `ext`.
    ///
    /// Use this when the Arrow layout matches the Vortex storage layout. The storage dtype
    /// supplies the nullability of each level for the rules in [`Self::from_arrow_array`].
    ///
    /// # Errors
    ///
    /// Returns an error if the Arrow layout and the storage dtype differ in field names, field
    /// order, or types, or if converting the storage fails.
    pub fn from_arrow_storage(
        &self,
        array: ArrowArrayRef,
        ext: &ExtDTypeRef,
    ) -> VortexResult<ArrayRef> {
        let storage_dtype = ext.storage_dtype();
        let arrow_dtype =
            self.from_arrow_datatype(array.data_type(), storage_dtype.nullability())?;
        vortex_ensure!(
            arrow_dtype.eq_ignore_nullability(storage_dtype),
            "Arrow storage of {} must convert to {storage_dtype} apart from nullability, got {arrow_dtype}",
            ext.id()
        );

        let field = Field::new("", array.data_type().clone(), storage_dtype.is_nullable());
        let field = storage_import_field(&field, storage_dtype);
        let storage = self.from_arrow_array_canonical(array, &field)?;
        Ok(ExtensionArray::try_new(ext.clone(), storage)?.into_array())
    }

    /// Import a nested array or root array with a resolved Arrow [`Field`].
    #[allow(clippy::wrong_self_convention)]
    fn from_arrow_array_inner(
        &self,
        array: ArrowArrayRef,
        field: &Field,
    ) -> VortexResult<ArrayRef> {
        if let DataType::Dictionary(_, values_type) = field.data_type() {
            return self.import_dictionary_values(array.as_ref(), field, values_type);
        }

        // A plugin import is final, because `from_arrow_array_with_importers` already checked that
        // it has the dtype inferred from `field`. It must not reach `ext_dtype_to_wrap`, which
        // reads the metadata of `field` as Vortex wire metadata. A plugin can encode its metadata
        // differently, so that check would reject a valid array.
        let storage = match self.from_arrow_array_with_importers(array, field)? {
            ArrowImport::Imported(imported) => return Ok(imported),
            ArrowImport::Unsupported(storage) => storage,
        };
        let imported = self.from_arrow_array_canonical(storage, field)?;

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

    /// Probe registered importers, checking imported dtypes and all returned array lengths.
    ///
    /// If every plugin declines, return [`ArrowImport::Unsupported`] with the remaining array.
    /// Canonical conversion and Vortex ID wrapping belong to [`Self::from_arrow_array_inner`].
    #[allow(clippy::wrong_self_convention)]
    fn from_arrow_array_with_importers(
        &self,
        mut array: ArrowArrayRef,
        field: &Field,
    ) -> VortexResult<ArrowImport> {
        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 = array.len();
                for plugin in importers.iter() {
                    match plugin.from_arrow_array(array, 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
                            );
                            vortex_ensure_eq!(
                                arr.dtype(),
                                &dtype,
                                "Arrow importer must preserve the dtype inferred from its field"
                            );

                            return Ok(ArrowImport::Imported(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
                            );
                            array = arr;
                        }
                    }
                }
            }
        }

        Ok(ArrowImport::Unsupported(array))
    }

    /// Convert an Arrow array using the resolved field's data type and nullability.
    ///
    /// The caller handles the root extension. Recursive calls still dispatch to importers for
    /// nested fields.
    #[allow(clippy::wrong_self_convention)]
    fn from_arrow_array_canonical(
        &self,
        array: ArrowArrayRef,
        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)| {
                        self.from_arrow_array_inner(ArrowArrayRef::clone(col), child_field.as_ref())
                    })
                    .collect::<VortexResult<Vec<_>>>()?;
                let validity = level_validity(arrow_struct.nulls(), field.is_nullable())?;

                Ok(
                    StructArray::try_new(names, columns, arrow_struct.len(), validity)?
                        .into_array(),
                )
            }
            DataType::List(elem_field) => {
                self.import_list(array.as_list::<i32>(), elem_field, field.is_nullable())
            }
            DataType::LargeList(elem_field) => {
                self.import_list(array.as_list::<i64>(), elem_field, field.is_nullable())
            }
            DataType::FixedSizeList(elem_field, list_size) => {
                let list = array.as_fixed_size_list();
                let elements =
                    self.from_arrow_array_inner(ArrowArrayRef::clone(list.values()), elem_field)?;
                let validity = level_validity(list.nulls(), field.is_nullable())?;

                Ok(
                    FixedSizeListArray::try_new(elements, *list_size as u32, validity, list.len())?
                        .into_array(),
                )
            }
            DataType::ListView(elem_field) => {
                self.import_list_view(array.as_list_view::<i32>(), elem_field, field.is_nullable())
            }
            DataType::LargeListView(elem_field) => {
                self.import_list_view(array.as_list_view::<i64>(), elem_field, field.is_nullable())
            }
            DataType::Map(entries_field, keys_sorted) => {
                let map = array.as_map();
                let (entries, offsets) = trim_map_entries(map);

                // Match schema import by treating the entries field as a plain struct. Its key
                // and value fields still reach their importers.
                let entries =
                    self.from_arrow_array_canonical(Arc::new(entries), 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());
                run_end_from_arrow_dyn(array.as_ref(), ends_field.data_type(), |values| {
                    self.from_arrow_array_inner(values, &values_field)
                })
            }
            DataType::Dictionary(_, values_type) => {
                self.import_dictionary_values(array.as_ref(), field, values_type)
            }
            _ => from_arrow_dyn(array.as_ref(), field.is_nullable()),
        }
    }

    fn import_list<O: OffsetSizeTrait + IntegerPType>(
        &self,
        list: &GenericListArray<O>,
        element_field: &Field,
        nullable: bool,
    ) -> VortexResult<ArrayRef> {
        let (offsets, referenced) = trim_offsets(list.offsets());
        let values = list.values().slice(referenced.start, referenced.len());
        let elements = self.from_arrow_array_inner(values, element_field)?;
        let offsets = offsets.into_array();
        let validity = level_validity(list.nulls(), nullable)?;

        // SAFETY: Arrow supplies at least one non-negative, sorted integer offset. `trim_offsets`
        // rebases the offsets to the value slice, whose length the import preserves. The validity
        // comes from the same lists.
        Ok(unsafe { ListArray::new_unchecked(elements, offsets, validity) }.into_array())
    }

    fn import_list_view<O: OffsetSizeTrait + NativePType>(
        &self,
        list: &GenericListViewArray<O>,
        element_field: &Field,
        nullable: bool,
    ) -> VortexResult<ArrayRef> {
        let elements =
            self.from_arrow_array_inner(ArrowArrayRef::clone(list.values()), element_field)?;
        let offsets = list.offsets().clone().into_array();
        let sizes = list.sizes().clone().into_array();
        let validity = level_validity(list.nulls(), nullable)?;

        // SAFETY: Arrow supplies equally sized integer buffers whose ranges lie within the values.
        // The import preserves the value count, and the validity comes from the same views.
        Ok(
            unsafe { ListViewArray::new_unchecked(elements, offsets, sizes, validity) }
                .into_array(),
        )
    }

    /// Import the dictionary values with the dictionary field's extension metadata.
    fn import_dictionary_values(
        &self,
        array: &dyn ArrowArray,
        field: &Field,
        values_type: &DataType,
    ) -> VortexResult<ArrayRef> {
        let dict = array.as_any_dictionary_opt().ok_or_else(|| {
            vortex_err!(
                "Arrow dictionary import requires a DictionaryArray, got {}",
                array.data_type()
            )
        })?;

        let values_field = field.clone().with_data_type(values_type.clone());

        Ok(import_dictionary(dict, field.is_nullable(), |values| {
            self.from_arrow_array_inner(values, &values_field)
        })?
        .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())
}

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

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

/// Fails unless `metadata`, the extension metadata of `field`, is the metadata of `ext_dtype`.
pub(crate) fn ensure_ext_metadata(
    field: &Field,
    metadata: &[u8],
    ext_dtype: &ExtDTypeRef,
) -> VortexResult<()> {
    vortex_ensure!(
        metadata == ext_dtype.serialize_metadata()?,
        "Arrow field {:?} must carry the metadata of {ext_dtype}, got {metadata:?}",
        field.name()
    );

    Ok(())
}

#[expect(clippy::disallowed_methods, reason = "interning a dynamic id")]
fn field_uses_plugin(field: &Field, is_registered: &impl Fn(&Id) -> bool) -> bool {
    field
        .extension_type_name()
        .is_some_and(|name| is_registered(&Id::new(name)))
        || child_uses_plugin(field.data_type(), is_registered)
}

fn child_uses_plugin(data_type: &DataType, is_registered: &impl Fn(&Id) -> bool) -> bool {
    match data_type {
        DataType::Struct(fields) => fields
            .iter()
            .any(|field| field_uses_plugin(field, is_registered)),
        DataType::Union(fields, _) => fields
            .iter()
            .any(|(_, field)| field_uses_plugin(field, is_registered)),
        DataType::List(field)
        | DataType::LargeList(field)
        | DataType::ListView(field)
        | DataType::LargeListView(field)
        | DataType::FixedSizeList(field, _)
        | DataType::Map(field, _)
        | DataType::RunEndEncoded(_, field) => field_uses_plugin(field, is_registered),
        // A dictionary carries its value field's metadata on the outer field, checked above.
        DataType::Dictionary(_, values) => child_uses_plugin(values, is_registered),
        _ => false,
    }
}

/// Extension trait for accessing the [`ArrowSession`] on a Vortex session.
pub trait ArrowSessionExt: SessionExt {
    /// Get the Arrow session, creating it on first use.
    ///
    /// The new session has no plugins, and it can look up the extension types of
    /// [`DTypeSessionExt::dtypes`] by Vortex ID.
    fn arrow(&self) -> SessionGuard<'_, ArrowSession>;
}

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

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

    use arrow_array::DictionaryArray;
    use arrow_array::FixedSizeListArray as ArrowFixedSizeListArray;
    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::new_null_array;
    use arrow_array::types::Int32Type;
    use arrow_buffer::NullBuffer;
    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 arrow_schema::Metadata;
    use rstest::rstest;
    use vortex_array::IntoArray;
    use vortex_array::VortexSessionExecute as _;
    use vortex_array::arrays::Dict;
    use vortex_array::arrays::FixedSizeList;
    use vortex_array::arrays::ListArray;
    use vortex_array::arrays::PrimitiveArray;
    use vortex_array::arrays::StructArray as VortexStructArray;
    use vortex_array::arrays::VarBinViewArray;
    use vortex_array::arrays::fixed_size_list::FixedSizeListArraySlotsExt;
    use vortex_array::assert_arrays_eq;
    use vortex_array::dtype::DType;
    use vortex_array::dtype::Nullability;
    use vortex_array::dtype::PType;
    use vortex_array::dtype::extension::ExtDType;
    use vortex_array::dtype::extension::ExtVTable;
    use vortex_array::scalar::ScalarValue;
    use vortex_array::validity::Validity;
    use vortex_buffer::buffer;
    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 = SESSION.arrow();
        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 = SESSION.arrow();
        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 = SESSION.arrow();
        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(),
        )]);
        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 vortex_session = VortexSession::empty();
        let session = vortex_session.arrow();
        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::<Metadata>();
        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(),
        )]))
    }

    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_entries_with_value_field(value_field: FieldRef) -> StructArray {
        let key_field = Arc::new(Field::new("key", DataType::Int64, false));

        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,
        )
    }

    fn map_with_truncated_child() -> ArrowArrayRef {
        let entries = map_entries_with_value_field(truncated_field("value", DataType::Int64));
        Arc::new(MapArray::new(
            Arc::new(Field::new("entries", entries.data_type().clone(), false)),
            OffsetBuffer::new(vec![0, 5].into()),
            entries,
            None,
            false,
        ))
    }

    #[test]
    fn test_map_entries_ignore_import_plugins() -> VortexResult<()> {
        let vortex_session = VortexSession::empty();
        let session = vortex_session.arrow();
        session.register_importer(Arc::new(TruncatingImporter { decline: false }));

        let value_field = Arc::new(Field::new("value", DataType::Int64, false));
        let entries = map_entries_with_value_field(value_field);
        let map = MapArray::new(
            truncated_field("entries", entries.data_type().clone()),
            OffsetBuffer::new(vec![0, 5].into()),
            entries,
            None,
            false,
        );
        let field = Field::new("map", map.data_type().clone(), false);
        let expected_dtype = session.from_arrow_field(&field)?;

        let imported = session.from_arrow_array(Arc::new(map), &field)?;
        assert_eq!(imported.dtype(), &expected_dtype);

        Ok(())
    }

    #[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 vortex_session = VortexSession::empty();
        let session = vortex_session.arrow();
        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}"
        );
    }

    #[test]
    fn test_import_struct_with_non_nullable_descendants_under_null_row() -> VortexResult<()> {
        let row_nulls = NullBuffer::from(vec![true, false]);
        let inner = StructArray::try_new(
            Fields::from(vec![Field::new("x", DataType::Int32, false)]),
            vec![Arc::new(Int32Array::from(vec![Some(1), None]))],
            Some(row_nulls.clone()),
        )?;
        let outer = StructArray::try_new(
            Fields::from(vec![Field::new("inner", inner.data_type().clone(), false)]),
            vec![Arc::new(inner)],
            Some(row_nulls),
        )?;
        let imported = SESSION.arrow().from_arrow_array(Arc::new(outer), true)?;

        let inner = VortexStructArray::from_fields(&[("x", buffer![1i32, 0].into_array())])?;
        let expected = VortexStructArray::try_new(
            FieldNames::from(["inner"]),
            vec![inner.into_array()],
            2,
            Validity::from_iter([true, false]),
        )?;
        assert_arrays_eq!(imported, expected, &mut SESSION.create_execution_ctx());
        Ok(())
    }

    /// A list element field of nullable `i32` values.
    fn nullable_item() -> FieldRef {
        Arc::new(Field::new_list_field(DataType::Int32, true))
    }

    /// A map from `i32` keys to nullable `i32` values.
    fn int_map_type() -> DataType {
        let entries = Field::new_struct(
            "entries",
            vec![
                Field::new("key", DataType::Int32, false),
                Field::new("value", DataType::Int32, true),
            ],
            false,
        );
        DataType::Map(Arc::new(entries), false)
    }

    /// Create a dictionary with one null key and one available value.
    fn dictionary_with_null_key() -> ArrowArrayRef {
        Arc::new(DictionaryArray::<Int32Type>::new(
            Int32Array::new_null(1),
            Arc::new(StringArray::from(vec!["a"])),
        ))
    }

    /// Outer joins can produce null rows with nulls in declared non-nullable fields.
    #[rstest]
    #[case::list(new_null_array(&DataType::List(nullable_item()), 1))]
    #[case::large_list(new_null_array(&DataType::LargeList(nullable_item()), 1))]
    #[case::fixed_size_list(new_null_array(&DataType::FixedSizeList(nullable_item(), 2), 1))]
    #[case::list_view(new_null_array(&DataType::ListView(nullable_item()), 1))]
    #[case::large_list_view(new_null_array(&DataType::LargeListView(nullable_item()), 1))]
    #[case::map(new_null_array(&int_map_type(), 1))]
    #[case::dictionary(dictionary_with_null_key())]
    fn test_struct_with_null_children_preserves_declared_dtype(
        #[case] child: ArrowArrayRef,
    ) -> VortexResult<()> {
        let row = StructArray::try_new(
            Fields::from(vec![Field::new("c", child.data_type().clone(), false)]),
            vec![child],
            Some(NullBuffer::new_null(1)),
        )?;
        let field = Field::new("s", row.data_type().clone(), true);
        let session = SESSION.arrow();
        let imported = session.from_arrow_array(Arc::new(row), &field)?;
        assert_eq!(imported.dtype(), &session.from_arrow_field(&field)?);
        Ok(())
    }

    #[test]
    fn test_dictionary_without_values_in_null_list_gets_zero_entry() -> VortexResult<()> {
        let dictionary = DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8));
        let element = Arc::new(Field::new_list_field(dictionary, false));
        let lists = new_null_array(&DataType::FixedSizeList(element, 2), 1);
        let imported = SESSION.arrow().from_arrow_array(lists, true)?;

        let expected = VarBinViewArray::from_iter_str(["", ""]);
        let imported = imported.as_::<FixedSizeList>();
        assert_arrays_eq!(
            imported.elements(),
            expected,
            &mut SESSION.create_execution_ctx()
        );
        Ok(())
    }

    /// Build the structs `[{x: null}, null]` and a field that declares `x` non-nullable.
    fn struct_with_null_in_valid_row() -> (ArrowArrayRef, Field) {
        let rows = StructArray::new(
            Fields::from(vec![Field::new("x", DataType::Int32, true)]),
            vec![Arc::new(Int32Array::from(vec![None, Some(5)]))],
            Some(NullBuffer::from(vec![true, false])),
        );
        let field = Field::new_struct("s", vec![Field::new("x", DataType::Int32, false)], true);
        (Arc::new(rows), field)
    }

    /// Build the lists `[[1, null], null]` and a field that declares the elements non-nullable.
    fn fixed_size_list_with_null_in_valid_row() -> (ArrowArrayRef, Field) {
        let lists = ArrowFixedSizeListArray::new(
            nullable_item(),
            2,
            Arc::new(Int32Array::from(vec![Some(1), None, Some(3), Some(4)])),
            Some(NullBuffer::from(vec![true, false])),
        );
        let element = Field::new_list_field(DataType::Int32, false);
        let field = Field::new_fixed_size_list("l", element, 2, true);
        (Arc::new(lists), field)
    }

    #[rstest]
    #[case::struct_field(
        struct_with_null_in_valid_row(),
        VortexStructArray::new(
            FieldNames::from(["x"]),
            vec![buffer![0i32, 5].into_array()],
            2,
            Validity::from_iter([true, false]),
        ).into_array(),
    )]
    #[case::fixed_size_list_element(
        fixed_size_list_with_null_in_valid_row(),
        FixedSizeListArray::new(
            buffer![1i32, 0, 3, 4].into_array(),
            2,
            Validity::from_iter([true, false]),
            2,
        ).into_array(),
    )]
    fn test_declared_non_nullable_leaf_fills_null_in_valid_row(
        #[case] input: (ArrowArrayRef, Field),
        #[case] expected: ArrayRef,
    ) -> VortexResult<()> {
        let (array, field) = input;
        let imported = SESSION.arrow().from_arrow_array(array, &field)?;
        assert_arrays_eq!(imported, expected, &mut SESSION.create_execution_ctx());
        Ok(())
    }

    /// An extension type over any storage dtype.
    ///
    /// Its metadata is the storage dtype that it declares, which it reads back from the stored
    /// storage, so its serialized metadata is empty.
    #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
    struct AnyStorage;

    impl ExtVTable for AnyStorage {
        type Metadata = DType;
        type StoredMetadata = ();
        type NativeValue<'a> = &'a ScalarValue;

        fn id(&self) -> ExtId {
            static ID: CachedId = CachedId::new("test.any_storage");
            *ID
        }

        fn serialize_metadata(&self, _metadata: &DType) -> VortexResult<Vec<u8>> {
            Ok(Vec::new())
        }

        fn deserialize_metadata(&self, _metadata: &[u8]) -> VortexResult<()> {
            Ok(())
        }

        fn metadata_from_storage(
            &self,
            _stored_metadata: (),
            storage_dtype: &DType,
        ) -> VortexResult<DType> {
            Ok(storage_dtype.clone())
        }

        fn storage_dtype(metadata: &DType) -> DType {
            metadata.clone()
        }

        fn unpack_native<'a>(
            _ext_dtype: &'a ExtDType<Self>,
            storage_value: &'a ScalarValue,
        ) -> VortexResult<&'a ScalarValue> {
            Ok(storage_value)
        }
    }

    /// An [`AnyStorage`] dtype over `storage`.
    fn any_storage(storage: DType) -> VortexResult<ExtDTypeRef> {
        Ok(ExtDType::try_from_storage_with_vtable(AnyStorage, (), storage)?.erased())
    }

    /// The Arrow lists `[[{x: 1}], [{x: null}]]` with nullable fields at every level, where
    /// `list_nulls` is the validity of the two lists.
    fn lists_of_points(list_nulls: Option<NullBuffer>) -> ArrowArrayRef {
        let points = StructArray::new(
            Fields::from(vec![Field::new("x", DataType::Int32, true)]),
            vec![Arc::new(Int32Array::from(vec![Some(1), None]))],
            None,
        );
        Arc::new(GenericListArray::<i32>::new(
            Arc::new(Field::new("item", points.data_type().clone(), true)),
            OffsetBuffer::new(vec![0, 1, 2].into()),
            Arc::new(points),
            list_nulls,
        ))
    }

    /// Nullable lists of `{x: i32}` points, non-nullable below the lists.
    fn lists_of_points_dtype() -> DType {
        let x = DType::Primitive(PType::I32, Nullability::NonNullable);
        let point = DType::Struct(
            StructFields::from_iter([("x", x)]),
            Nullability::NonNullable,
        );
        DType::List(Arc::new(point), Nullability::Nullable)
    }

    #[rstest]
    #[case::valid_rows(lists_of_points(None), &[1, 0], &[0, 1, 2], Validity::AllValid)]
    #[case::under_null_row(
        lists_of_points(Some(NullBuffer::from(vec![true, false]))),
        &[1, 0],
        &[0, 1, 2],
        Validity::from_iter([true, false]),
    )]
    #[case::outside_sliced_rows(
        lists_of_points(None).slice(0, 1),
        &[1],
        &[0, 1],
        Validity::AllValid,
    )]
    fn test_from_arrow_storage_fills_null_coordinates(
        #[case] lists: ArrowArrayRef,
        #[case] expected_coordinates: &[i32],
        #[case] expected_offsets: &[i32],
        #[case] validity: Validity,
    ) -> VortexResult<()> {
        let ext = any_storage(lists_of_points_dtype())?;
        let imported = SESSION.arrow().from_arrow_storage(lists, &ext)?;

        let mut ctx = SESSION.create_execution_ctx();
        let coordinates = PrimitiveArray::from_iter(expected_coordinates.iter().copied());
        let points = VortexStructArray::from_fields(&[("x", coordinates.into_array())])?;
        let lists = ListArray::try_new(
            points.into_array(),
            PrimitiveArray::from_iter(expected_offsets.iter().copied()).into_array(),
            validity,
            &mut ctx,
        )?;
        let expected = ExtensionArray::try_new(ext, lists.into_array())?;
        assert_arrays_eq!(imported, expected, &mut ctx);
        Ok(())
    }

    /// Arrow storage `{x: i32, y: i32}` against declared storage with other field names, field
    /// order, or types.
    #[rstest]
    #[case::names(["x", "z"], [PType::I32, PType::I32])]
    #[case::order(["y", "x"], [PType::I32, PType::I32])]
    #[case::types(["x", "y"], [PType::I64, PType::I32])]
    fn test_from_arrow_storage_rejects_other_fields(
        #[case] names: [&str; 2],
        #[case] ptypes: [PType; 2],
    ) -> VortexResult<()> {
        let point: ArrowArrayRef = Arc::new(StructArray::from(vec![
            (
                Arc::new(Field::new("x", DataType::Int32, false)),
                Arc::new(Int32Array::from(vec![1])) as ArrowArrayRef,
            ),
            (
                Arc::new(Field::new("y", DataType::Int32, false)),
                Arc::new(Int32Array::from(vec![2])) as ArrowArrayRef,
            ),
        ]));
        let fields = ptypes.map(|ptype| DType::Primitive(ptype, Nullability::NonNullable));
        let storage = DType::Struct(
            StructFields::new(FieldNames::from(names), fields.to_vec()),
            Nullability::NonNullable,
        );

        let err = SESSION
            .arrow()
            .from_arrow_storage(point, &any_storage(storage)?)
            .expect_err("storage with other fields must fail the import");
        assert!(
            err.to_string()
                .contains("Arrow storage of test.any_storage must convert to"),
            "unexpected error: {err}"
        );
        Ok(())
    }

    const EXPORTER_NAME: &str = "test.exporter";
    static EXPORTER_ID: CachedId = CachedId::new(EXPORTER_NAME);

    /// Declines every array, because the tests only need an exporter registered under its name.
    #[derive(Debug)]
    struct DecliningExporter;

    impl ArrowExportVTable for DecliningExporter {
        fn arrow_ext_id(&self) -> Id {
            *EXPORTER_ID
        }

        fn vortex_id(&self) -> Id {
            *EXPORTER_ID
        }

        fn to_arrow_field(
            &self,
            _name: &str,
            _dtype: &DType,
            _session: &ArrowSession,
        ) -> VortexResult<Option<Field>> {
            Ok(None)
        }

        fn execute_arrow(
            &self,
            array: ArrayRef,
            _target: &Field,
            _options: &ArrowExportOptions,
            _ctx: &mut ExecutionCtx,
        ) -> VortexResult<ArrowExport> {
            Ok(ArrowExport::Unsupported(array))
        }
    }

    /// An `Int32` field that names `extension_name`, or a plain one without it.
    fn leaf(extension_name: Option<&str>) -> FieldRef {
        let mut leaf = Field::new("leaf", DataType::Int32, true);
        if let Some(name) = extension_name {
            leaf = leaf.with_metadata(Metadata::from_iter([(
                EXTENSION_TYPE_NAME_KEY.to_string(),
                name.to_string(),
            )]));
        }

        Arc::new(leaf)
    }

    /// Only a leaf that names a registered exporter makes an export call a plugin, at any depth.
    #[rstest]
    #[case::top_level(     |leaf: FieldRef| leaf.as_ref().clone())]
    #[case::struct_child(  |leaf: FieldRef| Field::new_struct("a", vec![leaf], true))]
    #[case::list_item(     |leaf: FieldRef| Field::new_list("a", leaf, true))]
    #[case::run_end_values(|leaf: FieldRef| {
        let run_ends = Arc::new(Field::new("run_ends", DataType::Int32, false));
        Field::new("a", DataType::RunEndEncoded(run_ends, leaf), true)
    })]
    #[case::dictionary_values(|leaf: FieldRef| {
        Field::new_dictionary("a", DataType::Int32, DataType::Struct(vec![leaf].into()), true)
    })]
    fn test_exports_without_plugins_finds_exporters_at_any_depth(
        #[case] wrap: fn(FieldRef) -> Field,
        #[values(None, Some("test.unregistered"), Some(EXPORTER_NAME))] leaf_name: Option<&str>,
    ) {
        let vortex_session = VortexSession::empty();
        let session = vortex_session.arrow();
        session.register_exporter(Arc::new(DecliningExporter));

        let field = wrap(leaf(leaf_name));
        let leaf_names_exporter = leaf_name == Some(EXPORTER_NAME);

        assert_eq!(
            session.exports_without_plugins(&field),
            !leaf_names_exporter
        );
    }
}