deltalens 2.2.0

Standalone CLI to inspect Delta Lake tables without Spark, JVM, or Python
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
use crate::error::DeltaLensError;
use rayon::prelude::*;
use std::ffi::OsString;
use std::io::Read;
use std::path::{Path, PathBuf};

#[cfg(any(target_os = "linux", target_os = "macos"))]
use std::os::unix::ffi::{OsStrExt, OsStringExt};
#[cfg(any(target_os = "linux", target_os = "macos"))]
use std::os::unix::fs::OpenOptionsExt;
#[cfg(any(target_os = "linux", target_os = "macos"))]
use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd};
#[cfg(windows)]
use std::os::windows::ffi::OsStringExt;
#[cfg(windows)]
use std::os::windows::fs::OpenOptionsExt;
#[cfg(windows)]
use std::os::windows::io::AsRawHandle;

#[cfg(feature = "cloud")]
use futures::stream::{self, StreamExt, TryStreamExt};
#[cfg(feature = "cloud")]
use object_store::path::Path as ObjectStorePath;
#[cfg(feature = "cloud")]
use object_store::{ObjectStore, ObjectStoreExt};
#[cfg(feature = "cloud")]
use std::sync::{Arc, OnceLock};
#[cfg(feature = "cloud")]
use tokio::runtime::Runtime;

#[cfg(feature = "cloud")]
const DEFAULT_CLOUD_CONCURRENCY: usize = 32;

#[cfg(feature = "cloud")]
fn tokio_runtime() -> Result<&'static Runtime, DeltaLensError> {
    static RT: OnceLock<Result<Runtime, String>> = OnceLock::new();
    let res = RT.get_or_init(|| {
        Runtime::new().map_err(|e| format!("Failed to create Tokio runtime for object store: {e}"))
    });
    match res {
        Ok(rt) => Ok(rt),
        Err(msg) => Err(DeltaLensError::Storage(msg.clone())),
    }
}

pub trait StorageBackend: Send + Sync {
    /// List immediate child entries in a directory/subpath (non-recursive).
    fn list(&self, dir_path: &str) -> Result<Vec<String>, DeltaLensError>;

    /// List immediate child entries in a directory/subpath whose filename is
    /// lexicographically greater than `start_after_name` (non-recursive).
    /// Cloud object stores implement this via `list_with_offset` to skip
    /// historical log entries preceding `_last_checkpoint`.
    /// Returns `Ok(None)` when offset listing is not supported by the backend.
    fn list_from_offset(
        &self,
        _dir_path: &str,
        _start_after_name: &str,
    ) -> Result<Option<Vec<String>>, DeltaLensError> {
        Ok(None)
    }

    /// Read entire file contents as bytes.
    fn read(&self, file_path: &str) -> Result<Vec<u8>, DeltaLensError>;

    /// Read multiple files concurrently using backend-appropriate parallelism
    /// (bounded Tokio async stream for cloud stores, Rayon for local disk).
    fn read_many(&self, file_paths: &[String]) -> Result<Vec<(String, Vec<u8>)>, DeltaLensError> {
        file_paths
            .iter()
            .map(|p| Ok((p.clone(), self.read(p)?)))
            .collect()
    }

    /// Check whether a file or directory path exists.
    fn exists(&self, path: &str) -> Result<bool, DeltaLensError>;

    /// Check whether a path exists and is a directory (or non-empty object prefix).
    fn is_dir(&self, path: &str) -> Result<bool, DeltaLensError> {
        self.exists(path)
    }

    /// Return a human-readable root string for display.
    fn root_display(&self) -> &str;
}

// ---------------------------------------------------------------------------
// Local filesystem
// ---------------------------------------------------------------------------

pub struct LocalStorage {
    root: PathBuf,
    root_display: String,
}

impl LocalStorage {
    pub fn new(root: String) -> Self {
        let root_path = PathBuf::from(&root);
        Self {
            root: root_path,
            root_display: root,
        }
    }

    #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
    fn resolve_path(&self, path: &str) -> Result<PathBuf, DeltaLensError> {
        let relative = Path::new(path);
        if relative.is_absolute()
            || relative.components().any(|component| {
                matches!(
                    component,
                    std::path::Component::ParentDir | std::path::Component::Prefix(_)
                )
            })
        {
            return Err(DeltaLensError::Storage(format!(
                "Path escapes table root: {path}"
            )));
        }

        let canonical_root = match std::fs::canonicalize(&self.root) {
            Ok(root) => root,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
                return Ok(self.root.join(relative));
            }
            Err(error) => return Err(error.into()),
        };
        let candidate = canonical_root.join(relative);

        // Check every existing prefix. This rejects symlinks that resolve outside
        // the table while still allowing paths whose final file does not exist.
        let mut probe = candidate.as_path();
        loop {
            if let Ok(metadata) = std::fs::symlink_metadata(probe) {
                if metadata.file_type().is_symlink() {
                    let resolved = std::fs::canonicalize(probe)?;
                    if !resolved.starts_with(&canonical_root) {
                        return Err(DeltaLensError::Storage(format!(
                            "Path escapes table root through a symlink: {path}"
                        )));
                    }
                }
            }

            if probe == canonical_root {
                break;
            }
            probe = probe.parent().ok_or_else(|| {
                DeltaLensError::Storage(format!("Path escapes table root: {path}"))
            })?;
        }

        Ok(candidate)
    }
}

impl StorageBackend for LocalStorage {
    fn list(&self, dir_path: &str) -> Result<Vec<String>, DeltaLensError> {
        let prefix = dir_path.trim_matches('/');

        #[cfg(any(target_os = "linux", target_os = "macos"))]
        let names = read_directory_names(open_table_directory(&self.root, dir_path)?)?;

        #[cfg(windows)]
        let names =
            read_directory_names_windows(open_table_directory_windows(&self.root, dir_path)?)?;

        #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
        let names = std::fs::read_dir(self.resolve_path(dir_path)?)?
            .map(|entry| entry.map(|entry| entry.file_name()))
            .collect::<Result<Vec<_>, _>>()?;

        let mut entries = Vec::with_capacity(names.len());
        for name in names {
            let file_name = name.to_string_lossy().to_string();
            // Always return paths relative to `self.root` so subsequent `read()`
            // never double-joins relative roots (e.g., `rel/dir` + `rel/dir/_delta_log/...`).
            let rel = if prefix.is_empty() {
                file_name
            } else {
                format!("{}/{}", prefix, file_name)
            };
            entries.push(rel);
        }
        Ok(entries)
    }

    fn read(&self, file_path: &str) -> Result<Vec<u8>, DeltaLensError> {
        #[cfg(any(target_os = "linux", target_os = "macos"))]
        let mut file = open_table_file(&self.root, file_path)?;

        #[cfg(windows)]
        let mut file = open_table_file_windows(&self.root, file_path)?;

        #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
        let mut file = std::fs::File::open(self.resolve_path(file_path)?)?;

        let mut contents = Vec::new();
        file.read_to_end(&mut contents)?;
        Ok(contents)
    }

    fn read_many(&self, file_paths: &[String]) -> Result<Vec<(String, Vec<u8>)>, DeltaLensError> {
        file_paths
            .par_iter()
            .map(|p| {
                let bytes = self.read(p)?;
                Ok((p.clone(), bytes))
            })
            .collect()
    }

    fn exists(&self, path: &str) -> Result<bool, DeltaLensError> {
        #[cfg(any(target_os = "linux", target_os = "macos"))]
        {
            // Use the same no-follow open as `read` so a symlink swapped in
            // after path validation cannot make us report an outside entry.
            match open_table_file(&self.root, path) {
                Ok(_) => Ok(true),
                Err(DeltaLensError::Io(ref e)) if e.kind() == std::io::ErrorKind::NotFound => {
                    Ok(false)
                }
                Err(e) => Err(e),
            }
        }
        #[cfg(windows)]
        {
            // Mirror Unix O_NOFOLLOW parity using handle-pinned opens verified
            // with GetFinalPathNameByHandleW. Opening a directory without
            // FILE_FLAG_BACKUP_SEMANTICS returns PermissionDenied on Windows, so
            // retry via open_table_directory_windows in that case.
            match open_table_file_windows(&self.root, path) {
                Ok(_) => Ok(true),
                Err(DeltaLensError::Io(ref e)) if e.kind() == std::io::ErrorKind::NotFound => {
                    Ok(false)
                }
                Err(DeltaLensError::Io(ref e))
                    if e.kind() == std::io::ErrorKind::PermissionDenied =>
                {
                    match open_table_directory_windows(&self.root, path) {
                        Ok(_) => Ok(true),
                        Err(DeltaLensError::Io(ref e))
                            if e.kind() == std::io::ErrorKind::NotFound =>
                        {
                            Ok(false)
                        }
                        Err(e) => Err(e),
                    }
                }
                Err(e) => Err(e),
            }
        }
        #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
        {
            Ok(self.resolve_path(path)?.exists())
        }
    }

    fn is_dir(&self, path: &str) -> Result<bool, DeltaLensError> {
        #[cfg(any(target_os = "linux", target_os = "macos"))]
        {
            match open_table_directory(&self.root, path) {
                Ok(_) => Ok(true),
                Err(DeltaLensError::Io(ref e))
                    if e.kind() == std::io::ErrorKind::NotFound
                        || e.raw_os_error() == Some(libc::ENOTDIR) =>
                {
                    Ok(false)
                }
                Err(e) => Err(e),
            }
        }
        #[cfg(windows)]
        {
            // FILE_FLAG_BACKUP_SEMANTICS can open regular files as well as
            // directories; query metadata on the already-pinned handle.
            match open_table_directory_windows(&self.root, path) {
                Ok(handle) => Ok(handle.metadata()?.is_dir()),
                Err(DeltaLensError::Io(ref e)) if e.kind() == std::io::ErrorKind::NotFound => {
                    Ok(false)
                }
                Err(e) => Err(e),
            }
        }
        #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
        {
            Ok(self.resolve_path(path)?.is_dir())
        }
    }

    fn root_display(&self) -> &str {
        &self.root_display
    }
}

#[cfg(windows)]
fn open_table_file_windows(root: &Path, path: &str) -> Result<std::fs::File, DeltaLensError> {
    let relative = Path::new(path);
    if relative.is_absolute()
        || relative.components().any(|component| {
            matches!(
                component,
                std::path::Component::ParentDir
                    | std::path::Component::RootDir
                    | std::path::Component::Prefix(_)
            )
        })
    {
        return Err(DeltaLensError::Storage(format!(
            "Path escapes table root: {path}"
        )));
    }

    let root_handle = std::fs::OpenOptions::new()
        .read(true)
        .custom_flags(windows_sys::Win32::Storage::FileSystem::FILE_FLAG_BACKUP_SEMANTICS)
        .open(root)?;
    let file = std::fs::File::open(root.join(relative))?;
    ensure_windows_handle_within_root(&root_handle, &file, path)?;
    Ok(file)
}

#[cfg(windows)]
fn ensure_windows_handle_within_root(
    root_handle: &std::fs::File,
    file_handle: &std::fs::File,
    original_path: &str,
) -> Result<(), DeltaLensError> {
    let root_path = windows_final_path(root_handle)?;
    let file_path = windows_final_path(file_handle)?;
    if !file_path.starts_with(&root_path) {
        return Err(DeltaLensError::Storage(format!(
            "Path escapes table root through a reparse point: {original_path}"
        )));
    }
    Ok(())
}

#[cfg(windows)]
fn windows_final_path(file: &std::fs::File) -> Result<PathBuf, DeltaLensError> {
    use windows_sys::Win32::Storage::FileSystem::{
        GetFinalPathNameByHandleW, FILE_NAME_NORMALIZED, VOLUME_NAME_DOS,
    };

    let flags = FILE_NAME_NORMALIZED | VOLUME_NAME_DOS;
    let mut buffer = vec![0u16; 512];
    loop {
        // The open handle pins the object while Windows resolves its final path.
        let length = unsafe {
            GetFinalPathNameByHandleW(
                file.as_raw_handle() as _,
                buffer.as_mut_ptr(),
                buffer.len() as u32,
                flags,
            )
        };
        if length == 0 {
            return Err(std::io::Error::last_os_error().into());
        }
        if (length as usize) < buffer.len() {
            buffer.truncate(length as usize);
            return Ok(PathBuf::from(std::ffi::OsString::from_wide(&buffer)));
        }
        buffer.resize(length as usize + 1, 0);
    }
}

#[cfg(windows)]
fn open_table_directory_windows(root: &Path, path: &str) -> Result<std::fs::File, DeltaLensError> {
    let relative = Path::new(path);
    if relative.is_absolute()
        || relative.components().any(|component| {
            matches!(
                component,
                std::path::Component::ParentDir
                    | std::path::Component::RootDir
                    | std::path::Component::Prefix(_)
            )
        })
    {
        return Err(DeltaLensError::Storage(format!(
            "Path escapes table root: {path}"
        )));
    }

    let root_handle = std::fs::OpenOptions::new()
        .read(true)
        .custom_flags(windows_sys::Win32::Storage::FileSystem::FILE_FLAG_BACKUP_SEMANTICS)
        .open(root)?;
    let directory = std::fs::OpenOptions::new()
        .read(true)
        .custom_flags(windows_sys::Win32::Storage::FileSystem::FILE_FLAG_BACKUP_SEMANTICS)
        .open(root.join(relative))?;
    ensure_windows_handle_within_root(&root_handle, &directory, path)?;
    Ok(directory)
}

#[cfg(windows)]
fn read_directory_names_windows(directory: std::fs::File) -> Result<Vec<OsString>, DeltaLensError> {
    use windows_sys::Win32::Foundation::ERROR_NO_MORE_FILES;
    use windows_sys::Win32::Storage::FileSystem::{
        FileIdBothDirectoryInfo, FileIdBothDirectoryRestartInfo, GetFileInformationByHandleEx,
        FILE_ID_BOTH_DIR_INFO,
    };

    let mut names = Vec::new();
    let mut buffer = vec![0u64; 8192];
    let buffer_bytes = std::mem::size_of_val(buffer.as_slice());
    let mut restart = true;

    loop {
        let info_class = if restart {
            FileIdBothDirectoryRestartInfo
        } else {
            FileIdBothDirectoryInfo
        };
        restart = false;

        let succeeded = unsafe {
            GetFileInformationByHandleEx(
                directory.as_raw_handle() as _,
                info_class,
                buffer.as_mut_ptr().cast(),
                buffer_bytes as u32,
            )
        };
        if succeeded == 0 {
            let error = std::io::Error::last_os_error();
            if error.raw_os_error() == Some(ERROR_NO_MORE_FILES as i32) {
                break;
            }
            return Err(error.into());
        }

        let buffer_ptr = buffer.as_ptr().cast::<u8>();
        let mut offset = 0usize;
        loop {
            if offset + std::mem::size_of::<FILE_ID_BOTH_DIR_INFO>() > buffer_bytes {
                return Err(DeltaLensError::Storage(
                    "Invalid directory entry returned by Windows".to_string(),
                ));
            }
            let info = unsafe { &*buffer_ptr.add(offset).cast::<FILE_ID_BOTH_DIR_INFO>() };
            if info.FileNameLength % 2 != 0 {
                return Err(DeltaLensError::Storage(
                    "Invalid directory name returned by Windows".to_string(),
                ));
            }
            let name_len = (info.FileNameLength / 2) as usize;
            let name_ptr = std::ptr::addr_of!(info.FileName).cast::<u16>();
            let name_offset = name_ptr as usize - buffer_ptr as usize;
            if name_len * 2 > buffer_bytes.saturating_sub(name_offset) {
                return Err(DeltaLensError::Storage(
                    "Invalid directory entry returned by Windows".to_string(),
                ));
            }
            let name = unsafe { std::slice::from_raw_parts(name_ptr, name_len) };
            if name != [b'.' as u16] && name != [b'.' as u16, b'.' as u16] {
                names.push(OsString::from_wide(name));
            }

            let next_offset = info.NextEntryOffset as usize;
            if next_offset == 0 {
                break;
            }
            if next_offset > buffer_bytes - offset {
                return Err(DeltaLensError::Storage(
                    "Invalid directory entry offset returned by Windows".to_string(),
                ));
            }
            offset += next_offset;
        }
    }

    Ok(names)
}

#[cfg(any(target_os = "linux", target_os = "macos"))]
fn is_symlink_at(dir_fd: libc::c_int, name: &std::ffi::CStr) -> bool {
    let mut stat: libc::stat = unsafe { std::mem::zeroed() };
    let rc = unsafe { libc::fstatat(dir_fd, name.as_ptr(), &mut stat, libc::AT_SYMLINK_NOFOLLOW) };
    rc == 0 && (stat.st_mode & libc::S_IFMT) == libc::S_IFLNK
}

#[cfg(any(target_os = "linux", target_os = "macos"))]
fn open_table_directory(root: &Path, path: &str) -> Result<std::fs::File, DeltaLensError> {
    let relative = Path::new(path);
    if relative.is_absolute()
        || relative.components().any(|component| {
            matches!(
                component,
                std::path::Component::ParentDir
                    | std::path::Component::RootDir
                    | std::path::Component::Prefix(_)
            )
        })
    {
        return Err(DeltaLensError::Storage(format!(
            "Path escapes table root: {path}"
        )));
    }

    // Open root once with O_DIRECTORY | O_CLOEXEC to pin it against root-swap TOCTOU,
    // then walk every relative component with openat(O_NOFOLLOW).
    let root_handle = std::fs::OpenOptions::new()
        .read(true)
        .custom_flags(libc::O_DIRECTORY | libc::O_CLOEXEC)
        .open(root)?;

    open_relative_directory_without_symlinks(root_handle, relative)
}

#[cfg(any(target_os = "linux", target_os = "macos"))]
fn open_relative_directory_without_symlinks(
    mut current: std::fs::File,
    relative: &Path,
) -> Result<std::fs::File, DeltaLensError> {
    for component in relative.components() {
        let name = match component {
            std::path::Component::CurDir => continue,
            std::path::Component::Normal(name) => name,
            _ => {
                return Err(DeltaLensError::Storage(format!(
                    "Path escapes table root: {}",
                    relative.display()
                )));
            }
        };
        let name = std::ffi::CString::new(name.as_bytes())
            .map_err(|_| DeltaLensError::Storage("Path contains a NUL byte".to_string()))?;
        let flags = libc::O_RDONLY | libc::O_CLOEXEC | libc::O_NOFOLLOW | libc::O_DIRECTORY;
        let fd = unsafe { libc::openat(current.as_raw_fd(), name.as_ptr(), flags) };
        if fd < 0 {
            let error = std::io::Error::last_os_error();
            if error.raw_os_error() == Some(libc::ELOOP)
                || (error.raw_os_error() == Some(libc::ENOTDIR)
                    && is_symlink_at(current.as_raw_fd(), &name))
            {
                return Err(DeltaLensError::Storage(format!(
                    "Path escapes table root through a symlink: {}",
                    relative.display()
                )));
            }
            return Err(error.into());
        }
        current = unsafe { std::fs::File::from_raw_fd(fd) };
    }

    Ok(current)
}

#[cfg(any(target_os = "linux", target_os = "macos"))]
fn read_directory_names(directory: std::fs::File) -> Result<Vec<OsString>, DeltaLensError> {
    let fd = directory.into_raw_fd();
    let stream = unsafe { libc::fdopendir(fd) };
    if stream.is_null() {
        let error = std::io::Error::last_os_error();
        unsafe {
            libc::close(fd);
        }
        return Err(error.into());
    }

    let mut names = Vec::new();
    let read_result = loop {
        clear_errno();
        let entry = unsafe { libc::readdir(stream) };
        if entry.is_null() {
            let error = std::io::Error::last_os_error();
            if error.raw_os_error().unwrap_or(0) != 0 {
                break Err(DeltaLensError::Io(error));
            }
            break Ok(());
        }

        let name = unsafe { std::ffi::CStr::from_ptr((*entry).d_name.as_ptr()) };
        if name.to_bytes() != b"." && name.to_bytes() != b".." {
            names.push(OsString::from_vec(name.to_bytes().to_vec()));
        }
    };
    let close_result = unsafe { libc::closedir(stream) };
    read_result?;
    if close_result != 0 {
        return Err(std::io::Error::last_os_error().into());
    }
    Ok(names)
}

#[cfg(target_os = "linux")]
fn clear_errno() {
    unsafe {
        *libc::__errno_location() = 0;
    }
}

#[cfg(target_os = "macos")]
fn clear_errno() {
    unsafe {
        *libc::__error() = 0;
    }
}

#[cfg(any(target_os = "linux", target_os = "macos"))]
fn open_table_file(root: &Path, path: &str) -> Result<std::fs::File, DeltaLensError> {
    let relative = Path::new(path);
    if relative.is_absolute()
        || relative.components().any(|component| {
            matches!(
                component,
                std::path::Component::ParentDir
                    | std::path::Component::RootDir
                    | std::path::Component::Prefix(_)
            )
        })
    {
        return Err(DeltaLensError::Storage(format!(
            "Path escapes table root: {path}"
        )));
    }

    // Open root once with O_DIRECTORY | O_CLOEXEC to pin it against root-swap TOCTOU,
    // then walk every relative component with openat(O_NOFOLLOW).
    let root_handle = std::fs::OpenOptions::new()
        .read(true)
        .custom_flags(libc::O_DIRECTORY | libc::O_CLOEXEC)
        .open(root)?;

    open_relative_without_symlinks(root_handle, relative)
}

#[cfg(any(target_os = "linux", target_os = "macos"))]
fn open_relative_without_symlinks(
    mut current: std::fs::File,
    relative: &Path,
) -> Result<std::fs::File, DeltaLensError> {
    let mut normals = Vec::new();
    for component in relative.components() {
        match component {
            std::path::Component::CurDir => continue,
            std::path::Component::Normal(name) => normals.push(name),
            _ => {
                return Err(DeltaLensError::Storage(format!(
                    "Path escapes table root: {}",
                    relative.display()
                )));
            }
        }
    }

    for (index, name) in normals.iter().enumerate() {
        let name = std::ffi::CString::new(name.as_bytes())
            .map_err(|_| DeltaLensError::Storage("Path contains a NUL byte".to_string()))?;
        let mut flags = libc::O_RDONLY | libc::O_CLOEXEC | libc::O_NOFOLLOW;
        if index + 1 < normals.len() {
            flags |= libc::O_DIRECTORY;
        }

        // Each component is opened relative to the prior directory descriptor.
        let fd = unsafe { libc::openat(current.as_raw_fd(), name.as_ptr(), flags) };
        if fd < 0 {
            let error = std::io::Error::last_os_error();
            if error.raw_os_error() == Some(libc::ELOOP)
                || (error.raw_os_error() == Some(libc::ENOTDIR)
                    && is_symlink_at(current.as_raw_fd(), &name))
            {
                return Err(DeltaLensError::Storage(format!(
                    "Path escapes table root through a symlink: {}",
                    relative.display()
                )));
            }
            return Err(error.into());
        }
        current = unsafe { std::fs::File::from_raw_fd(fd) };
    }

    Ok(current)
}

// ---------------------------------------------------------------------------
// Cloud Object Storage (S3, GCS, Azure) via `object_store`
// ---------------------------------------------------------------------------

#[cfg(feature = "cloud")]
pub struct ObjectStoreBackend {
    client: Arc<dyn ObjectStore>,
    scheme: String,
    bucket: String,
    /// Object key prefix (everything after bucket/container name), e.g. "data/transactions"
    prefix: String,
    /// Full URI for display, e.g. "s3://my-bucket/data/transactions"
    display_uri: String,
    concurrency: usize,
}

/// Public alias preserving S3Storage naming while sharing the hardened cloud backend.
#[cfg(feature = "cloud")]
pub type S3Storage = ObjectStoreBackend;

#[cfg(feature = "cloud")]
impl ObjectStoreBackend {
    /// Construct from an arbitrary `ObjectStore` implementation (also used in tests with `InMemory`).
    pub fn from_object_store(
        client: Arc<dyn ObjectStore>,
        scheme: &str,
        bucket: &str,
        prefix: &str,
        display_uri: String,
    ) -> Self {
        Self {
            client,
            scheme: scheme.to_string(),
            bucket: bucket.to_string(),
            prefix: prefix.trim_matches('/').to_string(),
            display_uri,
            concurrency: DEFAULT_CLOUD_CONCURRENCY,
        }
    }

    #[cfg(feature = "aws")]
    pub fn new_s3(
        scheme: &str,
        bucket: &str,
        prefix: &str,
        display_uri: String,
    ) -> Result<Self, DeltaLensError> {
        use object_store::aws::AmazonS3Builder;
        let client = AmazonS3Builder::from_env()
            .with_bucket_name(bucket)
            .build()
            .map_err(|e| {
                DeltaLensError::Auth(format!(
                    "Failed to create S3 client for bucket '{bucket}': {e}\n\
                     \n\
                     Ensure AWS credentials are available via one of:\n\
                       - Environment variables:  AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY [+ AWS_SESSION_TOKEN]\n\
                       - IAM instance/pod role:  Works automatically on EC2, ECS, EKS\n\
                       - WebIdentity / OIDC:     AWS_WEB_IDENTITY_TOKEN_FILE + AWS_ROLE_ARN\n\
                       (Note: object_store reads env/IMDS directly; export credentials from AWS CLI profiles if needed.)\n\
                     \n\
                     Other optional settings (as env vars):\n\
                       - AWS_REGION              e.g. us-east-1, eu-west-1\n\
                       - AWS_ENDPOINT            Custom S3-compatible endpoint (MinIO, R2, LocalStack)\n\
                       - AWS_ALLOW_HTTP          Set to 'true' for local HTTP endpoints (e.g. MinIO)"
                ))
            })?;
        Ok(Self::from_object_store(
            Arc::new(client),
            scheme,
            bucket,
            prefix,
            display_uri,
        ))
    }

    #[cfg(feature = "gcp")]
    pub fn new_gcs(
        bucket: &str,
        prefix: &str,
        display_uri: String,
    ) -> Result<Self, DeltaLensError> {
        use object_store::gcp::GoogleCloudStorageBuilder;
        let client = GoogleCloudStorageBuilder::from_env()
            .with_bucket_name(bucket)
            .build()
            .map_err(|e| {
                DeltaLensError::Auth(format!(
                    "Failed to create GCS client for bucket '{bucket}': {e}\n\
                     \n\
                     Ensure GCP credentials are available via:\n\
                       - GOOGLE_SERVICE_ACCOUNT or GOOGLE_APPLICATION_CREDENTIALS\n\
                       - GCE/GKE metadata service (automatic on GCP compute)"
                ))
            })?;
        Ok(Self::from_object_store(
            Arc::new(client),
            "gs",
            bucket,
            prefix,
            display_uri,
        ))
    }

    #[cfg(feature = "azure")]
    pub fn new_azure(
        scheme: &str,
        container: &str,
        account: Option<&str>,
        prefix: &str,
        display_uri: String,
    ) -> Result<Self, DeltaLensError> {
        use object_store::azure::MicrosoftAzureBuilder;
        let mut builder = MicrosoftAzureBuilder::from_env().with_container_name(container);
        if let Some(acct) = account {
            builder = builder.with_account(acct);
        }
        let client = builder.build().map_err(|e| {
            DeltaLensError::Auth(format!(
                "Failed to create Azure client for container '{container}': {e}\n\
                 \n\
                 Ensure Azure credentials are available via:\n\
                   - AZURE_STORAGE_ACCOUNT_NAME + AZURE_STORAGE_ACCOUNT_KEY (or AZURE_STORAGE_SAS_KEY)\n\
                   - Service principal: AZURE_CLIENT_ID + AZURE_CLIENT_SECRET + AZURE_TENANT_ID\n\
                   - Managed Identity / Azure CLI token"
            ))
        })?;
        Ok(Self::from_object_store(
            Arc::new(client),
            scheme,
            container,
            prefix,
            display_uri,
        ))
    }

    /// Build the full object key for a relative subpath beneath `self.prefix`.
    pub fn object_key(&self, subpath: &str) -> String {
        let clean = subpath.trim_start_matches('/');
        if self.prefix.is_empty() {
            clean.to_string()
        } else if clean.is_empty() {
            self.prefix.clone()
        } else {
            format!("{}/{}", self.prefix, clean)
        }
    }

    /// Resolve either a full URI (`scheme://bucket/key`) or a relative subpath (`_delta_log/...`)
    /// into an object store key. Relative paths ALWAYS prepend `self.prefix` and reject
    /// path traversal (`..`, `.`), NUL bytes, backslashes, leading slashes, and empty segments.
    /// Full URIs must match this backend's scheme and bucket and stay beneath `self.prefix`.
    pub fn resolve_key(&self, path: &str) -> Result<String, DeltaLensError> {
        if path.contains('\0') || path.contains('\\') {
            return Err(DeltaLensError::InvalidInput(format!(
                "Object path '{path}' contains forbidden control or backslash characters"
            )));
        }

        if let Some((scheme, rest)) = split_uri_scheme(path) {
            let (authority, key) = rest.split_once('/').unwrap_or((rest, ""));
            if !scheme.eq_ignore_ascii_case(&self.scheme)
                || !authority.eq_ignore_ascii_case(&self.bucket)
            {
                return Err(DeltaLensError::InvalidInput(format!(
                    "Object URI '{path}' does not match configured bucket '{}://{}'",
                    self.scheme, self.bucket
                )));
            }

            let clean_key = key.trim_start_matches('/').trim_end_matches('/');
            if !clean_key.is_empty()
                && clean_key
                    .split('/')
                    .any(|seg| seg.is_empty() || seg == "." || seg == "..")
            {
                return Err(DeltaLensError::InvalidInput(format!(
                    "Object URI '{path}' contains invalid or parent traversal path segments"
                )));
            }
            if !self.prefix.is_empty() {
                let within_prefix = clean_key == self.prefix
                    || clean_key
                        .strip_prefix(&self.prefix)
                        .is_some_and(|tail| tail.starts_with('/'));
                if !within_prefix {
                    return Err(DeltaLensError::InvalidInput(format!(
                        "Object URI '{path}' escapes configured table prefix '{}'",
                        self.prefix
                    )));
                }
            }
            return Ok(clean_key.to_string());
        }

        if path.is_empty() {
            return Ok(self.prefix.clone());
        }

        let trimmed = path.trim_end_matches('/');
        if trimmed.is_empty()
            || trimmed.starts_with('/')
            || trimmed
                .split('/')
                .any(|seg| seg.is_empty() || seg == "." || seg == "..")
        {
            return Err(DeltaLensError::InvalidInput(format!(
                "Relative object path '{path}' contains invalid or parent traversal path segments"
            )));
        }

        Ok(self.object_key(trimmed))
    }

    fn map_store_error(action: &str, target: &str, err: object_store::Error) -> DeltaLensError {
        let msg = format!("Failed to {action} object '{target}': {err}");
        match err {
            object_store::Error::Unauthenticated { .. }
            | object_store::Error::PermissionDenied { .. } => DeltaLensError::Auth(msg),
            _ => {
                let lower = msg.to_lowercase();
                if lower.contains("401")
                    || lower.contains("403")
                    || lower.contains("access denied")
                    || lower.contains("invalidaccesskeyid")
                    || lower.contains("signaturedoesnotmatch")
                    || lower.contains("expiredtoken")
                    || lower.contains("credentials")
                {
                    DeltaLensError::Auth(msg)
                } else {
                    DeltaLensError::Storage(msg)
                }
            }
        }
    }
}

#[cfg(feature = "cloud")]
impl StorageBackend for ObjectStoreBackend {
    fn list(&self, dir_path: &str) -> Result<Vec<String>, DeltaLensError> {
        let key = self.resolve_key(dir_path)?;
        let prefix_opt = if key.is_empty() {
            None
        } else {
            Some(ObjectStorePath::from(format!(
                "{}/",
                key.trim_end_matches('/')
            )))
        };

        let rt = tokio_runtime()?;
        let list_result = rt
            .block_on(async { self.client.list_with_delimiter(prefix_opt.as_ref()).await })
            .map_err(|e| Self::map_store_error("list", dir_path, e))?;

        Ok(list_result
            .objects
            .into_iter()
            .map(|meta| format!("{}://{}/{}", self.scheme, self.bucket, meta.location))
            .collect())
    }

    fn list_from_offset(
        &self,
        dir_path: &str,
        start_after_name: &str,
    ) -> Result<Option<Vec<String>>, DeltaLensError> {
        let key = self.resolve_key(dir_path)?;
        let dir_prefix = key.trim_end_matches('/');
        let prefix_opt = if dir_prefix.is_empty() {
            None
        } else {
            Some(ObjectStorePath::from(format!("{dir_prefix}/")))
        };
        let clean_offset = start_after_name.trim_start_matches('/');
        let offset_key = if dir_prefix.is_empty() {
            clean_offset.to_string()
        } else {
            format!("{dir_prefix}/{clean_offset}")
        };
        let offset = ObjectStorePath::from(offset_key);

        let rt = tokio_runtime()?;
        let metas: Vec<object_store::ObjectMeta> = rt
            .block_on(async {
                self.client
                    .list_with_offset(prefix_opt.as_ref(), &offset)
                    .try_collect()
                    .await
            })
            .map_err(|e| Self::map_store_error("list", dir_path, e))?;

        let immediate_prefix = if dir_prefix.is_empty() {
            String::new()
        } else {
            format!("{dir_prefix}/")
        };

        let entries = metas
            .into_iter()
            .filter_map(|meta| {
                let loc = meta.location.as_ref();
                let rel = if immediate_prefix.is_empty() {
                    loc
                } else {
                    loc.strip_prefix(&immediate_prefix)?
                };
                if rel.is_empty() || rel.contains('/') {
                    return None;
                }
                Some(format!("{}://{}/{}", self.scheme, self.bucket, loc))
            })
            .collect();

        Ok(Some(entries))
    }

    fn read(&self, file_path: &str) -> Result<Vec<u8>, DeltaLensError> {
        let key = self.resolve_key(file_path)?;
        let location = ObjectStorePath::from(key);
        let rt = tokio_runtime()?;
        let bytes = rt
            .block_on(async { self.client.get(&location).await?.bytes().await })
            .map_err(|e| Self::map_store_error("read", file_path, e))?;
        Ok(bytes.to_vec())
    }

    fn read_many(&self, file_paths: &[String]) -> Result<Vec<(String, Vec<u8>)>, DeltaLensError> {
        if file_paths.is_empty() {
            return Ok(Vec::new());
        }
        let rt = tokio_runtime()?;
        let client = Arc::clone(&self.client);
        let concurrency = self.concurrency.max(1);
        let resolved: Vec<(String, ObjectStorePath)> = file_paths
            .iter()
            .map(|p| Ok((p.clone(), ObjectStorePath::from(self.resolve_key(p)?))))
            .collect::<Result<Vec<_>, DeltaLensError>>()?;

        rt.block_on(async move {
            stream::iter(resolved)
                .map(|(orig_path, location)| {
                    let client = Arc::clone(&client);
                    async move {
                        let bytes = client
                            .get(&location)
                            .await
                            .map_err(|e| Self::map_store_error("read", &orig_path, e))?
                            .bytes()
                            .await
                            .map_err(|e| Self::map_store_error("read", &orig_path, e))?;
                        Ok::<(String, Vec<u8>), DeltaLensError>((orig_path, bytes.to_vec()))
                    }
                })
                .buffer_unordered(concurrency)
                .try_collect()
                .await
        })
    }

    fn exists(&self, path: &str) -> Result<bool, DeltaLensError> {
        let key = self.resolve_key(path)?;
        if key.is_empty() {
            return Ok(true);
        }
        let file_loc = ObjectStorePath::from(key.clone());
        let dir_loc = ObjectStorePath::from(format!("{}/", key.trim_end_matches('/')));
        let rt = tokio_runtime()?;

        rt.block_on(async {
            match self.client.head(&file_loc).await {
                Ok(_) => Ok(true),
                Err(object_store::Error::NotFound { .. }) => {
                    let list = self
                        .client
                        .list_with_delimiter(Some(&dir_loc))
                        .await
                        .map_err(|e| Self::map_store_error("check", path, e))?;
                    Ok(!list.objects.is_empty() || !list.common_prefixes.is_empty())
                }
                Err(e) => Err(Self::map_store_error("check", path, e)),
            }
        })
    }

    fn is_dir(&self, path: &str) -> Result<bool, DeltaLensError> {
        let key = self.resolve_key(path)?;
        let prefix_opt = if key.is_empty() {
            None
        } else {
            Some(ObjectStorePath::from(format!(
                "{}/",
                key.trim_end_matches('/')
            )))
        };
        let rt = tokio_runtime()?;
        let list = rt
            .block_on(async { self.client.list_with_delimiter(prefix_opt.as_ref()).await })
            .map_err(|e| Self::map_store_error("check directory", path, e))?;
        Ok(!list.objects.is_empty() || !list.common_prefixes.is_empty())
    }

    fn root_display(&self) -> &str {
        &self.display_uri
    }
}

// ---------------------------------------------------------------------------
// URI parsing & Factory
// ---------------------------------------------------------------------------

/// Split `scheme://rest` if `uri` begins with a valid RFC 3986 scheme.
fn split_uri_scheme(uri: &str) -> Option<(&str, &str)> {
    let (scheme, rest) = uri.split_once("://")?;
    if scheme.is_empty() {
        return None;
    }
    let valid = scheme.bytes().enumerate().all(|(i, b)| {
        b.is_ascii_alphabetic()
            || (i > 0 && (b.is_ascii_digit() || b == b'+' || b == b'-' || b == b'.'))
    });
    if valid {
        Some((scheme, rest))
    } else {
        None
    }
}

/// Parse an Azure authority (`container@account.dfs.core.windows.net` or `container`)
/// and prefix.
#[cfg(feature = "azure")]
fn parse_azure_uri(rest: &str) -> Result<(String, Option<String>, String), DeltaLensError> {
    let (authority, prefix) = rest.split_once('/').unwrap_or((rest, ""));
    if authority.is_empty() {
        return Err(DeltaLensError::InvalidInput(
            "Azure URI is missing container name".to_string(),
        ));
    }
    if let Some((container, host)) = authority.split_once('@') {
        let account = host
            .split('.')
            .next()
            .filter(|s| !s.is_empty())
            .map(String::from);
        if container.is_empty() {
            return Err(DeltaLensError::InvalidInput(
                "Azure URI is missing container name before '@'".to_string(),
            ));
        }
        Ok((container.to_string(), account, prefix.to_string()))
    } else {
        Ok((authority.to_string(), None, prefix.to_string()))
    }
}

fn resolve_local_root(
    local_path: &str,
) -> Result<(Box<dyn StorageBackend>, String), DeltaLensError> {
    let path = Path::new(local_path);
    let abs = if path.is_absolute() {
        path.to_path_buf()
    } else {
        std::env::current_dir()
            .map_err(DeltaLensError::Io)?
            .join(path)
    };
    let root = abs.to_string_lossy().to_string();
    Ok((Box::new(LocalStorage::new(root.clone())), root))
}

/// Parse a URI and create the appropriate storage backend.
/// Returns `(storage_backend, table_root_path)`.
pub fn storage_for(uri: &str) -> Result<(Box<dyn StorageBackend>, String), DeltaLensError> {
    let uri = uri.trim();
    if uri.is_empty() {
        return Err(DeltaLensError::InvalidInput(
            "Table path cannot be empty".to_string(),
        ));
    }

    if let Some((scheme_raw, rest)) = split_uri_scheme(uri) {
        let scheme = scheme_raw.to_ascii_lowercase();
        match scheme.as_str() {
            "file" => resolve_local_root(rest),
            "s3" | "s3a" | "s3n" => {
                #[cfg(feature = "aws")]
                {
                    let (bucket, prefix) = rest.split_once('/').unwrap_or((rest, ""));
                    if bucket.is_empty() {
                        return Err(DeltaLensError::InvalidInput(format!(
                            "S3 URI '{uri}' is missing bucket name"
                        )));
                    }
                    let root = uri.trim_end_matches('/').to_string();
                    let storage = ObjectStoreBackend::new_s3(&scheme, bucket, prefix, root.clone())?;
                    Ok((Box::new(storage), root))
                }
                #[cfg(not(feature = "aws"))]
                {
                    let _ = rest;
                    Err(DeltaLensError::UnsupportedScheme(format!(
                        "{scheme}:// (rebuild deltalens with the 'aws' feature enabled)"
                    )))
                }
            }
            "gs" => {
                #[cfg(feature = "gcp")]
                {
                    let (bucket, prefix) = rest.split_once('/').unwrap_or((rest, ""));
                    if bucket.is_empty() {
                        return Err(DeltaLensError::InvalidInput(format!(
                            "GCS URI '{uri}' is missing bucket name"
                        )));
                    }
                    let root = uri.trim_end_matches('/').to_string();
                    let storage = ObjectStoreBackend::new_gcs(bucket, prefix, root.clone())?;
                    Ok((Box::new(storage), root))
                }
                #[cfg(not(feature = "gcp"))]
                {
                    let _ = rest;
                    Err(DeltaLensError::UnsupportedScheme(format!(
                        "gs:// (rebuild deltalens with the 'gcp' feature enabled)"
                    )))
                }
            }
            "az" | "abfs" | "abfss" => {
                #[cfg(feature = "azure")]
                {
                    let (container, account, prefix) = parse_azure_uri(rest)?;
                    let root = uri.trim_end_matches('/').to_string();
                    let storage = ObjectStoreBackend::new_azure(
                        &scheme,
                        &container,
                        account.as_deref(),
                        &prefix,
                        root.clone(),
                    )?;
                    Ok((Box::new(storage), root))
                }
                #[cfg(not(feature = "azure"))]
                {
                    let _ = rest;
                    Err(DeltaLensError::UnsupportedScheme(format!(
                        "{scheme}:// (rebuild deltalens with the 'azure' feature enabled)"
                    )))
                }
            }
            other => Err(DeltaLensError::UnsupportedScheme(format!(
                "{other}:// — supported schemes: file://, s3://, s3a://, s3n://, gs://, az://, abfs://, abfss://"
            ))),
        }
    } else {
        resolve_local_root(uri)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    #[test]
    fn test_local_storage_relative_root_no_double_join() {
        let tmp = TempDir::new().unwrap();
        let log_dir = tmp.path().join("_delta_log");
        std::fs::create_dir(&log_dir).unwrap();
        std::fs::write(log_dir.join("00000000000000000000.json"), b"{}\n").unwrap();

        let rel_storage = LocalStorage::new(tmp.path().to_string_lossy().to_string());
        assert!(rel_storage.is_dir("_delta_log").unwrap());
        let listed = rel_storage.list("_delta_log").unwrap();
        assert_eq!(listed, vec!["_delta_log/00000000000000000000.json"]);
        let bytes = rel_storage.read(&listed[0]).unwrap();
        assert_eq!(bytes, b"{}\n");
    }

    #[test]
    fn test_local_storage_rejects_file_as_dir() {
        let tmp = TempDir::new().unwrap();
        std::fs::write(tmp.path().join("_delta_log"), b"not a directory").unwrap();
        let storage = LocalStorage::new(tmp.path().to_string_lossy().to_string());
        assert!(storage.exists("_delta_log").unwrap());
        assert!(!storage.is_dir("_delta_log").unwrap());
    }

    #[test]
    fn test_local_storage_rejects_parent_path() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path().join("table");
        std::fs::create_dir(&root).unwrap();
        std::fs::write(tmp.path().join("outside.json"), b"secret").unwrap();

        let storage = LocalStorage::new(root.to_string_lossy().to_string());
        assert!(matches!(
            storage.read("../outside.json"),
            Err(DeltaLensError::Storage(_))
        ));
    }

    #[cfg(unix)]
    #[test]
    fn test_local_storage_rejects_symlink_escape() {
        use std::os::unix::fs::symlink;

        let tmp = TempDir::new().unwrap();
        let root = tmp.path().join("table");
        let sidecars = root.join("_delta_log/_sidecars");
        std::fs::create_dir_all(&sidecars).unwrap();
        let outside = tmp.path().join("outside.parquet");
        std::fs::write(&outside, b"outside table").unwrap();
        symlink(&outside, sidecars.join("outside.parquet")).unwrap();

        let storage = LocalStorage::new(root.to_string_lossy().to_string());
        assert!(matches!(
            storage.read("_delta_log/_sidecars/outside.parquet"),
            Err(DeltaLensError::Storage(_))
        ));
    }

    #[cfg(any(target_os = "linux", target_os = "macos"))]
    #[test]
    fn test_exists_and_is_dir_reject_symlink_escape() {
        use std::os::unix::fs::symlink;

        let tmp = TempDir::new().unwrap();
        let root = tmp.path().join("table");
        let outside = tmp.path().join("outside");
        std::fs::create_dir(&root).unwrap();
        std::fs::create_dir(&outside).unwrap();
        symlink(&outside, root.join("link")).unwrap();

        let storage = LocalStorage::new(root.to_string_lossy().to_string());
        assert!(matches!(
            storage.exists("link"),
            Err(DeltaLensError::Storage(_))
        ));
        assert!(matches!(
            storage.is_dir("link"),
            Err(DeltaLensError::Storage(_))
        ));
    }

    #[cfg(any(target_os = "linux", target_os = "macos"))]
    #[test]
    fn test_descriptor_relative_read_rejects_symlink_swap() {
        use std::os::unix::fs::symlink;
        use std::os::unix::fs::OpenOptionsExt;

        let tmp = TempDir::new().unwrap();
        let root = tmp.path().join("table");
        let safe_dir = root.join("data");
        let outside_dir = tmp.path().join("outside");
        std::fs::create_dir_all(&safe_dir).unwrap();
        std::fs::create_dir_all(&outside_dir).unwrap();
        std::fs::write(safe_dir.join("file.parquet"), b"inside").unwrap();
        std::fs::write(outside_dir.join("file.parquet"), b"outside").unwrap();

        let root_handle = std::fs::OpenOptions::new()
            .read(true)
            .custom_flags(libc::O_DIRECTORY | libc::O_CLOEXEC)
            .open(&root)
            .unwrap();
        let resolved_target = Path::new("data/file.parquet");

        std::fs::rename(&safe_dir, root.join("data-original")).unwrap();
        symlink(&outside_dir, &safe_dir).unwrap();

        assert!(open_relative_without_symlinks(root_handle, resolved_target).is_err());
    }

    #[cfg(any(target_os = "linux", target_os = "macos"))]
    #[test]
    fn test_descriptor_relative_list_uses_pinned_directory() {
        use std::os::unix::fs::symlink;

        let tmp = TempDir::new().unwrap();
        let root = tmp.path().join("table");
        let log_dir = root.join("_delta_log");
        let replacement_dir = tmp.path().join("replacement");
        std::fs::create_dir_all(&log_dir).unwrap();
        std::fs::create_dir(&replacement_dir).unwrap();
        std::fs::write(log_dir.join("inside.json"), b"inside").unwrap();
        std::fs::write(replacement_dir.join("outside.json"), b"outside").unwrap();

        let directory = open_table_directory(&root, "_delta_log").unwrap();
        std::fs::rename(&log_dir, root.join("_delta_log-old")).unwrap();
        symlink(&replacement_dir, &log_dir).unwrap();

        let names = read_directory_names(directory).unwrap();
        assert!(names.iter().any(|name| name == "inside.json"));
        assert!(!names.iter().any(|name| name == "outside.json"));
    }

    #[cfg(windows)]
    #[test]
    fn test_windows_handle_path_check_rejects_external_file() {
        use std::os::windows::fs::OpenOptionsExt;

        let tmp = TempDir::new().unwrap();
        let root = tmp.path().join("table");
        std::fs::create_dir(&root).unwrap();
        let inside = root.join("inside.json");
        let outside = tmp.path().join("outside.json");
        std::fs::write(&inside, b"inside").unwrap();
        std::fs::write(&outside, b"outside").unwrap();

        let storage = LocalStorage::new(root.to_string_lossy().to_string());
        assert_eq!(storage.read("inside.json").unwrap(), b"inside");

        let root_handle = std::fs::OpenOptions::new()
            .read(true)
            .custom_flags(windows_sys::Win32::Storage::FileSystem::FILE_FLAG_BACKUP_SEMANTICS)
            .open(&root)
            .unwrap();
        let outside_handle = std::fs::File::open(outside).unwrap();
        assert!(matches!(
            ensure_windows_handle_within_root(&root_handle, &outside_handle, "outside.json"),
            Err(DeltaLensError::Storage(message))
                if message.contains("Path escapes table root")
        ));
    }

    #[cfg(windows)]
    #[test]
    fn test_windows_directory_listing_uses_pinned_handle() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path().join("table");
        let log_dir = root.join("_delta_log");
        let replacement_dir = tmp.path().join("replacement");
        std::fs::create_dir_all(&log_dir).unwrap();
        std::fs::create_dir(&replacement_dir).unwrap();
        std::fs::write(log_dir.join("inside.json"), b"inside").unwrap();
        std::fs::write(replacement_dir.join("outside.json"), b"outside").unwrap();

        let directory = open_table_directory_windows(&root, "_delta_log").unwrap();
        std::fs::rename(&log_dir, root.join("_delta_log-old")).unwrap();
        std::fs::rename(&replacement_dir, &log_dir).unwrap();

        let names = read_directory_names_windows(directory).unwrap();
        assert!(names.iter().any(|name| name == "inside.json"));
        assert!(!names.iter().any(|name| name == "outside.json"));
    }

    #[test]
    fn test_storage_for_rejects_unknown_scheme() {
        let res = storage_for("hdfs://namenode:8020/data/table");
        assert!(matches!(res, Err(DeltaLensError::UnsupportedScheme(_))));

        let res2 = storage_for("http://example.com/table");
        assert!(matches!(res2, Err(DeltaLensError::UnsupportedScheme(_))));
    }

    #[cfg(feature = "cloud")]
    #[test]
    fn test_object_store_prefix_resolution_exists_read_list_read_many() {
        use bytes::Bytes;
        use object_store::memory::InMemory;

        let mem = Arc::new(InMemory::new());
        let rt = tokio_runtime().unwrap();
        rt.block_on(async {
            mem.put(
                &ObjectStorePath::from("warehouse/sales/_delta_log/00000000000000000000.json"),
                Bytes::from_static(b"{\"commitInfo\":{\"timestamp\":1,\"operation\":\"WRITE\"}}\n")
                    .into(),
            )
            .await
            .unwrap();
            mem.put(
                &ObjectStorePath::from("warehouse/sales/_delta_log/_sidecars/sidecar1.parquet"),
                Bytes::from_static(b"sidecar-bytes").into(),
            )
            .await
            .unwrap();
        });

        let backend = ObjectStoreBackend::from_object_store(
            mem,
            "s3",
            "my-bucket",
            "warehouse/sales",
            "s3://my-bucket/warehouse/sales".to_string(),
        );

        // Prefix MUST be prepended for relative paths in exists() and read()
        assert_eq!(
            backend.resolve_key("_delta_log").unwrap(),
            "warehouse/sales/_delta_log"
        );
        assert!(backend.exists("_delta_log").unwrap());
        assert!(backend.is_dir("_delta_log").unwrap());
        assert!(!backend.exists("_nonexistent").unwrap());

        // Non-recursive list_with_delimiter should NOT return _sidecars/sidecar1.parquet
        let listed = backend.list("_delta_log").unwrap();
        assert_eq!(
            listed,
            vec!["s3://my-bucket/warehouse/sales/_delta_log/00000000000000000000.json"]
        );

        // Relative read() prepends prefix
        let rel_bytes = backend
            .read("_delta_log/00000000000000000000.json")
            .unwrap();
        assert!(rel_bytes.starts_with(b"{\"commitInfo\""));

        // Full URI read() works identically when beneath prefix
        let full_bytes = backend.read(&listed[0]).unwrap();
        assert_eq!(rel_bytes, full_bytes);

        // Full URI escaping `self.prefix` (including sibling prefix) MUST be rejected!
        assert!(matches!(
            backend
                .resolve_key("s3://my-bucket/warehouse/other/_delta_log/00000000000000000000.json"),
            Err(DeltaLensError::InvalidInput(_))
        ));
        assert!(matches!(
            backend.resolve_key(
                "s3://my-bucket/warehouse/sales_other/_delta_log/00000000000000000000.json"
            ),
            Err(DeltaLensError::InvalidInput(_))
        ));
        assert!(matches!(
            backend.read("s3://my-bucket/secret/file.json"),
            Err(DeltaLensError::InvalidInput(_))
        ));

        // Relative nested read (_sidecars) works
        let sidecar = backend
            .read("_delta_log/_sidecars/sidecar1.parquet")
            .unwrap();
        assert_eq!(sidecar, b"sidecar-bytes");

        // read_many reads concurrently via Tokio without panics
        let batch = backend
            .read_many(&[
                "_delta_log/00000000000000000000.json".to_string(),
                "_delta_log/_sidecars/sidecar1.parquet".to_string(),
            ])
            .unwrap();
        assert_eq!(batch.len(), 2);
    }

    #[cfg(feature = "cloud")]
    #[test]
    fn test_object_store_resolve_key_rejects_relative_traversal() {
        use object_store::memory::InMemory;

        let backend = ObjectStoreBackend::from_object_store(
            Arc::new(InMemory::new()),
            "s3",
            "my-bucket",
            "warehouse/sales",
            "s3://my-bucket/warehouse/sales".to_string(),
        );

        // Valid relative paths stay under `self.prefix`.
        assert_eq!(backend.resolve_key("").unwrap(), "warehouse/sales");
        assert_eq!(
            backend.resolve_key("_delta_log").unwrap(),
            "warehouse/sales/_delta_log"
        );
        assert_eq!(
            backend.resolve_key("_delta_log/").unwrap(),
            "warehouse/sales/_delta_log"
        );
        assert_eq!(
            backend
                .resolve_key("_delta_log/00000000000000000000.json")
                .unwrap(),
            "warehouse/sales/_delta_log/00000000000000000000.json"
        );

        // Parent traversal, dot segments, empty segments, leading slashes, backslashes, NUL bytes,
        // and mismatched URI schemes/buckets MUST all be rejected.
        for bad in [
            "..",
            "../other/secret.json",
            "_delta_log/../../secret.json",
            "_delta_log/../_delta_log/00000000000000000000.json",
            "_delta_log/./00000000000000000000.json",
            "_delta_log//00000000000000000000.json",
            "/",
            "/_delta_log/00000000000000000000.json",
            "_delta_log\\..\\secret.json",
            "_delta_log/00000000000000000000.json\0",
            "s3://other-bucket/warehouse/sales/_delta_log/00000000000000000000.json",
            "gs://my-bucket/warehouse/sales/_delta_log/00000000000000000000.json",
            "s3://my-bucket/warehouse/sales/_delta_log/../secret.json",
            "s3://my-bucket/warehouse/sales/_delta_log//secret.json",
        ] {
            assert!(
                matches!(
                    backend.resolve_key(bad),
                    Err(DeltaLensError::InvalidInput(_))
                ),
                "Expected InvalidInput for path: {bad:?}"
            );
        }
    }

    #[cfg(windows)]
    #[test]
    fn test_windows_exists_and_is_dir_handle_pinned() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path().join("table");
        let log_dir = root.join("_delta_log");
        std::fs::create_dir_all(&log_dir).unwrap();
        std::fs::write(log_dir.join("00000000000000000000.json"), b"{}\n").unwrap();
        std::fs::write(tmp.path().join("outside.json"), b"secret").unwrap();

        let storage = LocalStorage::new(root.to_string_lossy().to_string());
        assert!(storage.exists("_delta_log").unwrap());
        assert!(storage.is_dir("_delta_log").unwrap());
        assert!(storage
            .exists("_delta_log/00000000000000000000.json")
            .unwrap());
        assert!(!storage
            .is_dir("_delta_log/00000000000000000000.json")
            .unwrap());
        assert!(!storage.exists("_delta_log/missing.json").unwrap());
        assert!(!storage.is_dir("_delta_log/missing").unwrap());
        assert!(matches!(
            storage.exists("../outside.json"),
            Err(DeltaLensError::Storage(_))
        ));
        assert!(matches!(
            storage.is_dir("../outside.json"),
            Err(DeltaLensError::Storage(_))
        ));
    }
}