frozen-core 0.0.37

Custom implementations and core utilities for pid7-org projects
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
use super::{err, interface::FileInterface};
use crate::{error::FrozenResult, hints};
use std::{sync::atomic, time::Duration};
use windows_sys::Win32::{
    Foundation::{
        CloseHandle, ERROR_ACCESS_DENIED, ERROR_ALREADY_EXISTS, ERROR_BAD_PATHNAME,
        ERROR_DISK_FULL, ERROR_FILE_EXISTS, ERROR_FILE_NOT_FOUND, ERROR_HANDLE_DISK_FULL,
        ERROR_HANDLE_EOF, ERROR_INVALID_HANDLE, ERROR_INVALID_NAME, ERROR_INVALID_PARAMETER,
        ERROR_IO_DEVICE, ERROR_LOCK_VIOLATION, ERROR_NOT_SUPPORTED, ERROR_PATH_NOT_FOUND,
        ERROR_SHARING_BUFFER_EXCEEDED, ERROR_SHARING_VIOLATION, GENERIC_READ, GENERIC_WRITE,
        HANDLE, INVALID_HANDLE_VALUE,
    },
    Storage::FileSystem::{
        CREATE_NEW, CreateFileW, DELETE, DeleteFileW, FILE_ALLOCATION_INFO, FILE_ATTRIBUTE_NORMAL,
        FILE_DISPOSITION_FLAG_DELETE, FILE_DISPOSITION_FLAG_POSIX_SEMANTICS, FILE_DISPOSITION_INFO,
        FILE_DISPOSITION_INFO_EX, FILE_END_OF_FILE_INFO, FILE_FLAG_BACKUP_SEMANTICS,
        FILE_FLAG_RANDOM_ACCESS, FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE,
        FileAllocationInfo, FileDispositionInfo, FileDispositionInfoEx, FileEndOfFileInfo,
        FlushFileBuffers, GetFileAttributesW, GetFileSizeEx, INVALID_FILE_ATTRIBUTES,
        LOCKFILE_EXCLUSIVE_LOCK, LOCKFILE_FAIL_IMMEDIATELY, LockFileEx, OPEN_ALWAYS, OPEN_EXISTING,
        ReadFile, SetFileInformationByHandle, WriteFile,
    },
    System::IO::{OVERLAPPED, OVERLAPPED_0, OVERLAPPED_0_0},
};

/// File handle type for Windows systems
///
/// ## NOTES
///
/// We store the Win32 file handle as `isize` rather than `*mut c_void` mainly for two reasons,
///
/// - `isize` maps directly to `AtomicIsize`, giving lock free atomic handle swaps (same reasoning
///   as `AtomicI32` for POSIX `c_int` descriptors)
/// - Raw pointers are `!Send + !Sync`, which would leak into the public `FileId` type alias,
///   creating a pervasive `unsafe impl` burden for callers
///
/// At every Win32 callsite we convert the `handle as usize as HANDLE`; on x86-64 and AArch64 (our
/// only supported targets), `isize` and `HANDLE` have identical bit representations
pub(super) type FileId = isize;

/// Sentinel representing a closed or never opened handle
///
/// ## NOTES
///
/// Win32 defines `INVALID_HANDLE_VALUE` as `(HANDLE)(LONG_PTR)-1`, which is `-1isize` on all 64-bit
/// Windows targets
///
/// We deliberately avoid `0` (NULL) because some Win32 calls, such as `CreateFileW` on the NULL
/// device, legitimately return `0x0` as a valid handle
pub(in crate::file) const CLOSED_HANDLE: FileId = -1isize;

/// Maximum retries for transient `ERROR_SHARING_VIOLATION` / `ERROR_LOCK_VIOLATION` races
///
/// ## NOTES
///
/// Win32 does not have a signal interruption model equivalent to POSIX `EINTR`, but file share and
/// lock violation errors can appear transiently when another process is in the middle of opening or
/// releasing a file handle
///
/// A non CPU-blocking sleep between retries keeps us responsive while tolerating concurrent closing
/// races
const MAX_RETRIES: usize = 0x80;

/// Custom implementation of `std::fs::File` for Windows 64-bit systems
#[derive(Debug)]
pub(super) struct WINFile {
    handle: atomic::AtomicIsize,
}

impl FileInterface for WINFile {
    type Id = FileId;
    const CLOSED_ID: Self::Id = CLOSED_HANDLE;

    /// Read the raw Win32 handle value
    #[inline(always)]
    fn fd(&self) -> FileId {
        self.handle.load(atomic::Ordering::Acquire)
    }

    /// Check if the file at `path` exists using `GetFileAttributesW`
    ///
    /// ## Why `GetFileAttributesW` and not `PathFileExistsW`
    ///
    /// `GetFileAttributesW` is a single, documented kernel32 call with well defined error codes
    ///
    /// It does not require linking `shlwapi.dll` (where `PathFileExistsW` lives) and it has better
    /// availability
    ///
    /// It is also the canonical check used by virtually every production grade storage engine on
    /// Windows such as RocksDB, LMDB, SQLite, etc
    ///
    /// `INVALID_FILE_ATTRIBUTES` (0xFFFF_FFFF) is the sentinel for failure; we then inspect
    /// `GetLastError` to distinguish permission denial from genuine absence
    fn exists(path: &std::path::Path) -> FrozenResult<bool> {
        let wide = path_to_wide(path)?;
        let attrs = unsafe { GetFileAttributesW(wide.as_ptr()) };

        if attrs != INVALID_FILE_ATTRIBUTES {
            return Ok(true);
        }

        let code = last_error();
        let err_msg = err_msg(code);

        match code {
            // File or one of the path components does not exist
            ERROR_FILE_NOT_FOUND | ERROR_PATH_NOT_FOUND => Ok(false),

            // Lack of traverse or read permission on a path component
            ERROR_ACCESS_DENIED => err::raw_error(err::PRM, err_msg),

            // Syntactically invalid path
            // (e.g. embedded NUL, reserved name, bad drive letter)
            ERROR_INVALID_NAME | ERROR_BAD_PATHNAME => err::raw_error(err::INV, err_msg),

            _ => err::raw_error(err::UNK, err_msg),
        }
    }

    /// Create a new [`WINFile`] atomically with `CREATE_NEW`
    ///
    /// ## TOCTOU Safety
    ///
    /// `CreateFileW(CREATE_NEW)` maps directly to `NtCreateFile` with `FILE_CREATE` disposition,
    /// which is atomic at the NTFS/ReFS layer
    ///
    /// If the file already exists the kernel returns `ERROR_FILE_EXISTS` or `ERROR_ALREADY_EXISTS`
    /// before we ever hold a handle, eliminating the check-then-act window present in `open()` +
    /// `O_EXCL`
    ///
    /// ## `FILE_FLAG_RANDOM_ACCESS`
    ///
    /// We pass this flag at `CreateFileW` time because Win32 has no `posix_fadvise` equivalent for
    /// open handles
    ///
    /// The flag instructs the Cache Manager to bypass sequential read ahead heuristics, which is
    /// exactly what [`posix::f_advise_raw(FADV_RANDOM)`] does on Linux systems
    ///
    /// ## Exclusive Lock
    ///
    /// We open with `FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE` so that process-level
    /// metadata readers
    /// (e.g. monitoring tools) can still open the file, while still being able to perform
    /// handle-based deletion (and to not have the handle closed before trying to delete)
    ///
    /// Exclusive access for our engine is enforced by `LockFileEx` in [`flock`](WINFile::flock),
    /// mirroring the POSIX advisory lock model exactly
    fn create(path: &std::path::Path) -> FrozenResult<Self> {
        let handle = create_file_raw(path, CREATE_NEW)?;
        let file = Self { handle: atomic::AtomicIsize::new(handle) };

        if let Err(mut e) = sync_parent_dir(path) {
            if let Err(close_err) = file.close() {
                e.add_suppressed(close_err);
            }
            return Err(e);
        }

        Ok(file)
    }

    /// Open an existing [`WINFile`] without creating it (`OPEN_EXISTING`)
    ///
    /// Fails with [`err::INV`] if the file does not exist, while using the same share mode and
    /// random access flag as [`create`](WINFile::create) for consistency
    fn open(path: &std::path::Path) -> FrozenResult<Self> {
        let handle = create_file_raw(path, OPEN_EXISTING)?;
        Ok(Self { handle: atomic::AtomicIsize::new(handle) })
    }

    /// Open an existing [`WINFile`] or create it if missing (`OPEN_ALWAYS`)
    ///
    /// The file is never truncated `OPEN_ALWAYS` is the Win32 equivalent of `O_CREAT` without
    /// `O_EXCL`
    ///
    /// ## Crash-Safe Durability
    ///
    /// NTFS journals the new directory entry by default, so crash durability here is stronger than
    /// on ext4/XFS without the `data=journal` mount option
    ///
    /// We still sync the parent directory via `sync_parent_dir` for correctness on ReFS and
    /// non-journaling volumes
    /// (e.g. exFAT)
    fn new(path: &std::path::Path) -> FrozenResult<Self> {
        let handle = create_file_raw(path, OPEN_ALWAYS)?;
        let file = Self { handle: atomic::AtomicIsize::new(handle) };

        if let Err(mut e) = sync_parent_dir(path) {
            if let Err(close_err) = file.close() {
                e.add_suppressed(close_err);
            }
            return Err(e);
        }

        Ok(file)
    }

    /// Acquire an exclusive, non-blocking advisory lock on [`WINFile`]
    ///
    /// ## Why `LockFileEx` and not `LockFile`
    ///
    /// `LockFileEx` with `LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY` is the Win32 exact
    /// semantic equivalent of `flock(fd, LOCK_EX | LOCK_NB)`,
    ///
    /// - Exclusive,
    ///   i.e. no other handle (in this or any other process) may hold an overlapping lock
    /// - Non-blocking,
    ///   i.e. if the lock cannot be acquired immediately, it fails with `ERROR_LOCK_VIOLATION`
    ///   rather than blocking
    ///
    /// ## Lock Range
    ///
    /// We lock the full virtual 64-bit file range `[0, u64::MAX)` by passing
    /// `nNumberOfBytesToLockLow = 0xFFFFFFFF` and `nNumberOfBytesToLockHigh = 0xFFFFFFFF`
    ///
    /// This is identical to how SQLite, LMDB and the Chromium leveldb port take whole-file locks on
    /// Windows
    ///
    /// It avoids any partial lock confusion if `grow()` later extends the file beyond a smaller
    /// initial lock range
    ///
    /// ## Advisory Semantics
    ///
    /// Win32 byte-range locks are advisory for cooperating processes using `LockFileEx`, but they
    /// are kernel enforced against direct `ReadFile`/`WriteFile` calls on overlapping locked ranges
    /// from non-cooperating handles
    ///
    /// This is slightly stricter than POSIX `flock`, but the observable behaviour from our storage
    /// engine's perspective is identical
    ///
    /// ## OVERLAPPED Requirement
    ///
    /// `LockFileEx` always requires a non-NULL `OVERLAPPED` pointer
    ///
    /// We pass a zeroed struct with `hEvent = NULL`; the kernel does not signal anything because we
    /// use the synchronous `LOCKFILE_FAIL_IMMEDIATELY` flag
    fn flock(&self) -> FrozenResult<()> {
        lock_raw(self.fd() as usize as HANDLE)
    }

    /// Close [`WINFile`] and release the Win32 kernel object
    ///
    /// Swaps the stored handle with `CLOSED_HANDLE` atomically so that a concurrent `Drop` racing
    /// with an explicit `close()` call cannot double-close the same handle (which would be a erious
    /// bug,
    /// i.e. the kernel recycles handle slots, so a delayed `CloseHandle` on a recycled slot
    /// silently closes someone else's descriptor)
    ///
    /// ## Lock Release
    ///
    /// Win32 byte range locks acquired via `LockFileEx` are automatically released when the last
    /// handle to the file is closed
    ///
    /// We do not need a matching `UnlockFileEx` call here
    ///
    /// ## Deferred I/O Errors
    ///
    /// Unlike POSIX `close(2)`, Win32 `CloseHandle` does not return buffered write errors
    ///
    /// Deferred I/O failures surface on the preceding `WriteFile` call or on `FlushFileBuffers`
    ///
    /// Our durability model enforces `FlushFileBuffers` after every write batch, so by the time
    /// `close` is called, all data is already confirmed durable and `CloseHandle` is a
    /// kernel-object teardown with no I/O side ffects
    fn close(self) -> FrozenResult<()> {
        let h = self.handle.swap(CLOSED_HANDLE, atomic::Ordering::AcqRel);
        if h == CLOSED_HANDLE {
            return Ok(());
        }

        close_raw(h as usize as HANDLE)
    }

    /// Delete the file at `path` from the filesystem namespace
    ///
    /// ## Win32 Delete Semantics vs POSIX `unlink`
    ///
    /// To eliminate TOCTOU races, we delete the file directly through our open `HANDLE` while
    /// keeping our exclusive advisory byte-range lock active, rather than closing our handle first
    /// and racing `DeleteFileW`
    ///
    /// We attempt POSIX delete semantics via `SetFileInformationByHandle` with
    /// `FileDispositionInfoEx` and `FILE_DISPOSITION_FLAG_DELETE |
    /// FILE_DISPOSITION_FLAG_POSIX_SEMANTICS` (supported on Windows 10 1607+ / Windows Server 2016+
    /// on NTFS/ReFS)
    ///
    /// This immediately unlinks the file from the directory namespace upon return, matching POSIX
    /// `unlink(2)` semantics
    ///
    /// On older Windows systems or filesystems that do not support `FileDispositionInfoEx`, we fall
    /// back to `FileDispositionInfo` (`FILE_DISPOSITION_INFO { DeleteFile: 1 }`)
    ///
    /// If both handle-based dispositions fail, as a final fallback we close the handle and call
    /// `DeleteFileW(path)`
    ///
    /// ## Parent Directory Sync
    ///
    /// Unlike ext4/XFS, NTFS filesystems journal directory operations by default, so a parent
    /// `FlushFileBuffers` after delete is advisory
    ///
    /// We still call `sync_parent_dir` for consistency with the POSIX path and for ReFS and/or
    /// non-default-journal config
    fn unlink(self, path: &std::path::Path) -> FrozenResult<()> {
        let h = self.handle.swap(CLOSED_HANDLE, atomic::Ordering::AcqRel);
        if h == CLOSED_HANDLE {
            // Already closed handle cannot be unlinked via handle
            return err::raw_error(err::INV, "file handle is already closed");
        }
        let handle = h as usize as HANDLE;

        // Attempt for handle-based deletion while lock is held
        let disposition_res = set_disposition_raw(handle);
        let close_res = close_raw(handle);

        match disposition_res {
            Ok(()) => {
                close_res?;
                sync_parent_dir(path)
            }
            Err(e) => {
                // If the error was due to lack of support or invalid parameter, we must fallback to `DeleteFileW`
                if e.reason == err::INV.reason || e.reason == err::UNK.reason {
                    let wide = path_to_wide(path)?;
                    let ok = unsafe { DeleteFileW(wide.as_ptr()) };

                    if ok != 0 {
                        let _ = close_res;
                        return sync_parent_dir(path);
                    }

                    let code = last_error();
                    let err_msg = err_msg(code);

                    match code {
                        ERROR_FILE_NOT_FOUND | ERROR_PATH_NOT_FOUND => {
                            err::raw_error(err::INV, err_msg)
                        }
                        ERROR_SHARING_VIOLATION | ERROR_LOCK_VIOLATION => {
                            err::raw_error(err::LCK, err_msg)
                        }
                        ERROR_ACCESS_DENIED => err::raw_error(err::PRM, err_msg),
                        ERROR_INVALID_NAME | ERROR_BAD_PATHNAME => {
                            err::raw_error(err::INV, err_msg)
                        }
                        _ => err::raw_error(err::UNK, err_msg),
                    }
                } else {
                    let mut err = e;
                    if let Err(c_err) = close_res {
                        err.add_suppressed(c_err);
                    }

                    Err(err)
                }
            }
        }
    }

    /// Query the current logical file length via `GetFileSizeEx`
    ///
    /// `GetFileSizeEx` returns an `i64` (Win32 `LARGE_INTEGER`) rather than a `u64` because the
    /// underlying `NtQueryInformationFile(FileStandardInformation)` field is signed
    ///
    /// A negative result would indicate a severely corrupted NTFS record; we treat it as `err::HCF`
    fn length(&self) -> FrozenResult<usize> {
        get_size_raw(self.fd() as usize as HANDLE)
    }

    /// Grow (zero-extend) [`WINFile`] by `len_to_add` bytes
    ///
    /// ## Operation Order (Allocation Before Logical Extension)
    ///
    /// We call `SetFileInformationByHandle(FileAllocationInfo)` before
    /// `SetFileInformationByHandle(FileEndOfFileInfo)` for the same reason Linux `fallocate` must
    /// precede `ftruncate`, cause the pre-reserving disk blocks detects `ERROR_HANDLE_DISK_FULL`
    /// and/or `ERROR_DISK_FULL` before the logical file size is updated, so a failed `grow` never
    /// leaves the file in a state where `st_size` claims space that does not physically exist on
    /// disk
    ///
    /// ## `FileAllocationInfo` Semantics
    ///
    /// `AllocationSize` is the physical cluster-granular reservation, not the logical length
    ///
    /// NTFS rounds the value up to the nearest cluster boundary (typically 4 KiB on
    /// default-formatted volumes)
    ///
    /// Passing `curr_len + len_to_add` as `AllocationSize` guarantees we reserve at least that many
    /// bytes
    ///
    /// ## `FileEndOfFileInfo` Semantics
    ///
    /// Sets the logical EOF pointer, zeroing any newly allocated but previously unwritten bytes
    /// between the old EOF and the new one
    ///
    /// This is the Win32 equivalent of `ftruncate(fd, new_len)`
    ///
    /// ## Best-effort Allocation
    ///
    /// If `FileAllocationInfo` fails with `ERROR_NOT_SUPPORTED` or `ERROR_INVALID_PARAMETER` (which
    /// some third-party filesystem drivers and network shares return), we continue to
    /// `FileEndOfFileInfo` anyway
    ///
    /// The worst-case outcome is sparse file allocation, which is acceptable, cause the write ops
    /// that follow will succeed as long as enough free space exists at write time
    #[inline(always)]
    fn grow(&self, curr_len: usize, len_to_add: usize) -> FrozenResult<()> {
        if len_to_add == 0 {
            return Ok(());
        }

        let new_len = match curr_len.checked_add(len_to_add) {
            Some(len) => match i64::try_from(len) {
                Ok(l) if l >= 0 => l,
                _ => {
                    return err::raw_error(err::GRW, "target file size exceeds i64 capacity");
                }
            },
            None => {
                return err::raw_error(err::GRW, "file growth calculation overflowed usize");
            }
        };

        let h = self.fd() as usize as HANDLE;

        // NOTE: best-effort pre-reservation; unsupported errors are non-fatal (see doc above)
        let alloc_res = set_alloc_raw(h, new_len);
        if let Err(ref e) = alloc_res {
            // Only disk-full is fatal at the allocation stage; anything else we continue
            if e.reason == err::NSP.reason {
                return alloc_res;
            }

            // INFO: ERROR_NOT_SUPPORTED / ERROR_INVALID_PARAMETER / unknown, and other errors fall through to EOF
            // extension
        }

        set_eof_raw(h, new_len)
    }

    /// Flush all dirty cache pages and file metadata to stable storage
    ///
    /// ## `FlushFileBuffers` vs `fdatasync` / `F_FULLFSYNC`
    ///
    /// Win32 `FlushFileBuffers` is stronger than POSIX `fdatasync` in one key respect, that is, it
    /// also issues a `FLUSH CACHE` command to SATA/NVMe drives that support it, equivalent to macOS
    /// `fcntl(F_FULLFSYNC)`
    ///
    /// On drives with volatile write caches (BBU-less HBAs, consumer SSDs in default mode), this
    /// guarantees that data has left the controller cache and reached persistent media
    ///
    /// There is no weaker `fdatasync` or equivalent on Windows; `FlushFileBuffers` always flushes
    /// both data and metadata (file size, timestamps)
    ///
    /// For our purposes this is strictly correct behaviour, and the extra metadata flush cost is
    /// negligible compared to the I/O itself
    ///
    /// ## Indefinite Retry (Not Applicable on Windows)
    ///
    /// Unlike POSIX, Win32 I/O is not interruptible by signals
    ///
    /// `FlushFileBuffers` either succeeds, fails with a hardware error (`ERROR_IO_DEVICE`), or
    /// returns an invalid-handle error
    ///
    /// No retry loop is needed
    fn sync(&self) -> FrozenResult<()> {
        flush_raw(self.fd() as usize as HANDLE)
    }

    /// Read into `buf` from absolute `offset` without mutating the file pointer
    ///
    /// ## `ReadFile` with `OVERLAPPED` for Positional I/O
    ///
    /// Win32 has no direct `pread` equivalent, but `ReadFile` with a non-NULL `OVERLAPPED` achieves
    /// the exact same semantics, as the `Offset` and `OffsetHigh` fields in the `OVERLAPPED`
    /// structure specify the absolute byte offset, and the kernel does not advance the file pointer
    ///
    /// This is the technique used by SQLite's Windows VFS, Chrome's storage layer, and every other
    /// serious Win32 storage engine
    ///
    /// ## `DWORD` Chunk Cap
    ///
    /// Win32 `ReadFile` takes a `DWORD` (u32) byte count per call
    ///
    /// For buffers larger than `u32::MAX` bytes we loop, issuing multiple `ReadFile` calls and
    /// advancing both the buffer pointer and the OVERLAPPED offset each iteration
    ///
    /// In practice our buffers are page aligned and far below this limit, but we handle it
    /// correctly for robustness
    ///
    /// ## Retry on `ERROR_SHARING_VIOLATION`
    ///
    /// A transient `ERROR_SHARING_VIOLATION` can appear if another process briefly holds an
    /// incompatible byte range lock that overlaps our read range
    ///
    /// We retry up to `MAX_RETRIES` times before failing
    #[inline(always)]
    fn pread(&self, buf: &mut [u8], offset: usize) -> FrozenResult<()> {
        if buf.is_empty() {
            return Ok(());
        }

        let h = self.fd() as usize as HANDLE;

        let mut read = 0usize;
        let mut retries = 0usize;

        while read < buf.len() {
            let cur_offset = match offset.checked_add(read) {
                Some(off) => off,
                None => return err::raw_error(err::INV, "read offset overflow"),
            };

            // OVERLAPPED offset is split into low 32 bits and high 32 bits
            let off_lo = cur_offset as u32;
            let off_hi = (cur_offset >> 0x20) as u32;

            // Cap to DWORD max per ReadFile call
            let to_read = (buf.len() - read).min(u32::MAX as usize) as u32;

            let mut overlapped = overlapped_at(off_lo, off_hi);
            let mut bytes_read: u32 = 0;

            let ok = unsafe {
                ReadFile(h, buf[read..].as_mut_ptr(), to_read, &mut bytes_read, &mut overlapped)
            };

            if ok != 0 {
                if hints::unlikely(bytes_read == 0) {
                    // No bytes read despite success, so we treat it as unexpected EOF (hcf)
                    return err::default_error(err::HCF);
                }

                read += bytes_read as usize;
                retries = 0;
                continue;
            }

            let code = last_error();
            let err_msg = err_msg(code);

            match code {
                // Unexpected EOF,
                // i.e. read beyond current file length, which is an hcf situation
                ERROR_HANDLE_EOF => return err::default_error(err::HCF),

                // Transient sharing/lock contention
                ERROR_SHARING_VIOLATION | ERROR_LOCK_VIOLATION => {
                    if retries < MAX_RETRIES {
                        retries += 1;
                        std::thread::sleep(Duration::from_millis(1));
                        continue;
                    }

                    return err::raw_error(err::UNK, err_msg);
                }

                // Permission denied on file or byte range
                ERROR_ACCESS_DENIED => return err::raw_error(err::RED, err_msg),

                // Stale, recycled, or already closed handle
                ERROR_INVALID_HANDLE => return err::raw_error(err::HCF, err_msg),

                // Hardware / device I/O failure
                ERROR_IO_DEVICE => return err::raw_error(err::HCF, err_msg),

                _ => return err::raw_error(err::UNK, err_msg),
            }
        }

        Ok(())
    }

    /// Write `buf` at absolute `offset` without mutating the file pointer
    ///
    /// Mirrors [`pread`](WINFile::pread) in structure while using `WriteFile` with a non-NULL
    /// `OVERLAPPED` carrying the target byte offset
    ///
    /// ## Zero Write Retry
    ///
    /// Unlike POSIX `pwrite`, `WriteFile` can succeed (return non-zero) but report zero bytes
    /// written in certain edge cases (pipe write to a full buffer, rare device conditions)
    ///
    /// We retry a bounded number of times before treating this as `err::HCF`
    ///
    /// ## Disk-Full Detection
    ///
    /// `ERROR_HANDLE_DISK_FULL` and `ERROR_DISK_FULL` are both mapped to `err::NSP`
    ///
    /// NTFS reports the former for in-progress writes and the latter for quota exhaustion or volume
    /// full at the start of the allocation
    #[inline(always)]
    fn pwrite(&self, buf: &[u8], offset: usize) -> FrozenResult<()> {
        if buf.is_empty() {
            return Ok(());
        }

        let h = self.fd() as usize as HANDLE;

        let mut written = 0usize;
        let mut retries = 0usize;

        while written < buf.len() {
            let cur_offset = match offset.checked_add(written) {
                Some(off) => off,
                None => return err::raw_error(err::INV, "write offset overflow"),
            };

            let off_lo = cur_offset as u32;
            let off_hi = (cur_offset >> 0x20) as u32;

            let to_write = (buf.len() - written).min(u32::MAX as usize) as u32;

            let mut overlapped = overlapped_at(off_lo, off_hi);
            let mut bytes_written: u32 = 0;

            let ok = unsafe {
                WriteFile(h, buf[written..].as_ptr(), to_write, &mut bytes_written, &mut overlapped)
            };

            if ok != 0 {
                if bytes_written == 0 {
                    // Rare zero write with no error code, retry bounded times before giving up
                    if retries < MAX_RETRIES {
                        retries += 1;
                        std::thread::sleep(Duration::from_millis(1));
                        continue;
                    }

                    return err::default_error(err::HCF);
                }

                written += bytes_written as usize;
                retries = 0;
                continue;
            }

            let code = last_error();
            let err_msg = err_msg(code);

            match code {
                // Transient sharing/lock contention
                ERROR_SHARING_VIOLATION | ERROR_LOCK_VIOLATION => {
                    if retries < MAX_RETRIES {
                        retries += 1;
                        std::thread::sleep(Duration::from_millis(1));
                        continue;
                    }

                    return err::raw_error(err::UNK, err_msg);
                }

                // Write permission denied or read-only volume
                ERROR_ACCESS_DENIED => return err::raw_error(err::WRT, err_msg),

                // Storage device full
                ERROR_HANDLE_DISK_FULL | ERROR_DISK_FULL => {
                    return err::raw_error(err::NSP, err_msg);
                }

                // Stale, recycled, or already closed handle
                ERROR_INVALID_HANDLE => return err::raw_error(err::HCF, err_msg),

                // Hardware / device I/O failure
                ERROR_IO_DEVICE => return err::raw_error(err::HCF, err_msg),

                _ => return err::raw_error(err::UNK, err_msg),
            }
        }

        Ok(())
    }
}

impl Drop for WINFile {
    fn drop(&mut self) {
        let h = self.handle.swap(CLOSED_HANDLE, atomic::Ordering::AcqRel);
        if h != CLOSED_HANDLE {
            // INFO: ignore CloseHandle errors in Drop, cause we cannot propagate them, and by this point all dirty
            // pages must already have been flushed by an explicit sync() call
            let _ = close_raw(h as usize as HANDLE);
        }
    }
}

/// Open or create a file at `path` using the given Win32 `disposition`
///
/// The `disposition` must be one of `CREATE_NEW`, `OPEN_EXISTING`, or `OPEN_ALWAYS`
///
/// ## Share Mode
///
/// We always request `FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE`
///
/// This allows other processes to open the file (for monitoring, backup, etc.) while we hold the
/// handle, and allows safe handle-based deletion without closing first
///
/// Exclusive I/O ownership is enforced at the advisory layer by `LockFileEx`, mirroring the POSIX
/// `flock` model
///
/// ## `FILE_FLAG_RANDOM_ACCESS`
///
/// Disables the Cache Manager's sequential read-ahead prefetcher
///
/// Equivalent to `posix_fadvise(POSIX_FADV_RANDOM)` on Linux
///
/// Our storage engine accesses file pages at arbitrary offsets, so read-ahead is counterproductive
/// and wastes I/O bandwidth and cache
///
/// ## Retry on `ERROR_SHARING_VIOLATION`
///
/// A transient `ERROR_SHARING_VIOLATION` during `CreateFileW` can occur when another process is in
/// the middle of closing its own handle to the same file (there is a brief window between the
/// handle table teardown and the lock release)
///
/// We retry up to `MAX_RETRIES` times
fn create_file_raw(path: &std::path::Path, disposition: u32) -> FrozenResult<FileId> {
    let wide = path_to_wide(path)?;

    let mut retries = 0; // only for ERROR_SHARING_VIOLATION transient races
    loop {
        let h = unsafe {
            CreateFileW(
                wide.as_ptr(),
                GENERIC_READ | GENERIC_WRITE | DELETE,
                FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
                core::ptr::null(),
                disposition,
                FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS,
                core::ptr::null_mut(),
            )
        };

        if h != INVALID_HANDLE_VALUE {
            // Cast the pointer sized handle to isize for atomic storage
            return Ok(h as isize);
        }

        let code = last_error();
        let err_msg = err_msg(code);

        match code {
            // Transient race,
            // i.e. another process is mid close on this path
            ERROR_SHARING_VIOLATION => {
                if retries < MAX_RETRIES {
                    retries += 1;
                    std::thread::sleep(Duration::from_millis(1));
                    continue;
                }

                // Lock contention after exhausting retries
                return err::raw_error(err::LCK, err_msg);
            }

            // File or path component does not exist (OPEN_EXISTING on missing file)
            ERROR_FILE_NOT_FOUND | ERROR_PATH_NOT_FOUND => {
                return err::raw_error(err::INV, err_msg);
            }

            // CREATE_NEW on a path where the file already exists
            ERROR_FILE_EXISTS | ERROR_ALREADY_EXISTS => {
                return err::raw_error(err::EXS, err_msg);
            }

            // Insufficient permission on file or parent directory
            ERROR_ACCESS_DENIED => return err::raw_error(err::PRM, err_msg),

            // Syntactically invalid path
            ERROR_INVALID_NAME | ERROR_BAD_PATHNAME => {
                return err::raw_error(err::INV, err_msg);
            }

            // Disk full at file creation time
            ERROR_HANDLE_DISK_FULL | ERROR_DISK_FULL => {
                return err::raw_error(err::NSP, err_msg);
            }

            _ => return err::raw_error(err::UNK, err_msg),
        }
    }
}

/// Close a Win32 handle via `CloseHandle`
///
/// Unlike POSIX `close(2)`, `CloseHandle` does not report deferred write errors, those must be
/// caught by `FlushFileBuffers` (our `sync()`)
///
/// The only errors we expect here are `ERROR_INVALID_HANDLE` (double-close or handle corruption),
/// which we surface as `err::HCF`
fn close_raw(handle: HANDLE) -> FrozenResult<()> {
    let ok = unsafe { CloseHandle(handle) };
    if ok != 0 {
        return Ok(());
    }

    let code = last_error();
    let err_msg = err_msg(code);

    // A bad handle on close is an implementation error, we either double closed or corrupted the handle storage
    if code == ERROR_INVALID_HANDLE {
        return err::raw_error(err::HCF, err_msg);
    }

    err::raw_error(err::UNK, err_msg)
}

/// Flush dirty cache pages to stable storage via `FlushFileBuffers`
///
/// `FlushFileBuffers` is equivalent to a combined `fdatasync` + drive-level `FLUSH CACHE` command
///
/// On modern NVMe drives on Windows, this issues an `NVMe Flush` command, making it the strongest
/// available durability primitive on the platform
///
/// ## No Retry Needed
///
/// Win32 I/O is not signal interruptible
///
/// `FlushFileBuffers` either completes or returns a hardware error
///
/// No EINTR style retry is required
fn flush_raw(handle: HANDLE) -> FrozenResult<()> {
    let ok = unsafe { FlushFileBuffers(handle) };
    if ok != 0 {
        return Ok(());
    }

    let code = last_error();
    let err_msg = err_msg(code);

    match code {
        // Bad or closed handle (hcf)
        ERROR_INVALID_HANDLE => err::raw_error(err::HCF, err_msg),

        // Hardware I/O failure
        ERROR_IO_DEVICE => err::raw_error(err::SYN, err_msg),

        // Access denied
        // (e.g. flushing a read-only handle)
        ERROR_ACCESS_DENIED => err::raw_error(err::PRM, err_msg),

        _ => err::raw_error(err::SYN, err_msg),
    }
}

/// Acquire an exclusive, non-blocking byte range lock over the entire 64-bit file range
///
/// `LockFileEx` requires an `OVERLAPPED` pointer even in synchronous mode
///
/// The struct's `hEvent` field is `NULL`, which is valid cause Win32 only signals the event if the
/// lock request is async
/// (i.e. `LOCKFILE_FAIL_IMMEDIATELY` not set)
///
/// Since we always use `LOCKFILE_FAIL_IMMEDIATELY`, the event is never triggered
///
/// Lock range is `[0, u64::MAX)` the maximal Win32 byte-range, which is encoded as two `u32` pairs
/// `(nNumberOfBytesToLockLow, nNumberOfBytesToLockHigh) = (0xFFFFFFFF, 0xFFFFFFFF)`
fn lock_raw(handle: HANDLE) -> FrozenResult<()> {
    // OVERLAPPED with offset 0 (lock starts at byte 0)
    let mut overlapped = overlapped_at(0, 0);

    let ok = unsafe {
        LockFileEx(
            handle,
            LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY,
            0,
            0xFFFF_FFFF, // nNumberOfBytesToLockLow
            0xFFFF_FFFF, // nNumberOfBytesToLockHigh
            &mut overlapped,
        )
    };

    if ok != 0 {
        return Ok(());
    }

    let code = last_error();
    let err_msg = err_msg(code);

    match code {
        // Another process already holds an incompatible lock (non-blocking fail)
        ERROR_LOCK_VIOLATION | ERROR_SHARING_VIOLATION => err::raw_error(err::LCK, err_msg),

        // System or network lock table exhausted (Win32 equivalent of POSIX ENOLCK)
        ERROR_SHARING_BUFFER_EXCEEDED => err::raw_error(err::LEX, err_msg),

        // Bad or closed handle
        ERROR_INVALID_HANDLE => err::raw_error(err::HCF, err_msg),

        _ => err::raw_error(err::UNK, err_msg),
    }
}

/// Extend the logical file size (EOF pointer) to `new_len` bytes
///
/// NTFS zeroes any bytes between the previous EOF and the new EOF, satisfying our zero-fill
/// guarantee
///
/// This is the Win32 equivalent of `ftruncate(fd, new_len)`
fn set_eof_raw(handle: HANDLE, new_len: i64) -> FrozenResult<()> {
    let info = FILE_END_OF_FILE_INFO { EndOfFile: new_len };

    let ok = unsafe {
        SetFileInformationByHandle(
            handle,
            FileEndOfFileInfo,
            &info as *const _ as *const core::ffi::c_void,
            core::mem::size_of::<FILE_END_OF_FILE_INFO>() as u32,
        )
    };

    if ok != 0 {
        return Ok(());
    }

    let code = last_error();
    let err_msg = err_msg(code);

    match code {
        // Disk full at logical extension time
        ERROR_HANDLE_DISK_FULL | ERROR_DISK_FULL => err::raw_error(err::NSP, err_msg),

        // Bad handle
        ERROR_INVALID_HANDLE => err::raw_error(err::HCF, err_msg),

        // Access denied (read-only handle or volume)
        ERROR_ACCESS_DENIED => err::raw_error(err::PRM, err_msg),

        _ => err::raw_error(err::GRW, err_msg),
    }
}

/// Reserve physical disk clusters ahead of logical file extension
///
/// NTFS will round `AllocationSize` up to the next cluster boundary (default 4 KiB on most volumes)
///
/// This is the Win32 equivalent of `fallocate(fd, 0, offset, length)`
///
/// ## Best-effort
///
/// Some filesystem drivers (network shares, older CIFS/SMB drivers, some third-party antivirus
/// filter drivers) return `ERROR_NOT_SUPPORTED` or `ERROR_INVALID_PARAMETER` for
/// `FileAllocationInfo`
///
/// We treat those as non-fatal and let the caller fall through to `set_eof_raw`
///
/// The risk is that `set_eof_raw` succeeds but the blocks are sparse; future writes may then
/// encounter `ERROR_HANDLE_DISK_FULL` at write time rather than at `grow` time
///
/// This is the same trade-off POSIX makes on filesystems that do not support `fallocate`
fn set_alloc_raw(handle: HANDLE, new_len: i64) -> FrozenResult<()> {
    let info = FILE_ALLOCATION_INFO { AllocationSize: new_len };

    let ok = unsafe {
        SetFileInformationByHandle(
            handle,
            FileAllocationInfo,
            &info as *const _ as *const core::ffi::c_void,
            core::mem::size_of::<FILE_ALLOCATION_INFO>() as u32,
        )
    };

    if ok != 0 {
        return Ok(());
    }

    let code = last_error();
    let err_msg = err_msg(code);

    match code {
        // Driver or fs does not support physical pre-reservation as best-effort, non-fatal
        ERROR_NOT_SUPPORTED | ERROR_INVALID_PARAMETER => Ok(()),

        // Disk physically full, fatal, caller must propagate
        ERROR_HANDLE_DISK_FULL | ERROR_DISK_FULL => err::raw_error(err::NSP, err_msg),

        // Bad handle
        ERROR_INVALID_HANDLE => err::raw_error(err::HCF, err_msg),

        // Access denied
        ERROR_ACCESS_DENIED => err::raw_error(err::PRM, err_msg),

        _ => err::raw_error(err::GRW, err_msg),
    }
}

/// Mark a file for deletion through its open handle
///
/// We first attempt POSIX delete semantics via `FileDispositionInfoEx` with
/// `FILE_DISPOSITION_FLAG_DELETE | FILE_DISPOSITION_FLAG_POSIX_SEMANTICS`
///
/// This is supported on Windows 10 (version 1607+) / Windows Server 2016+ on NTFS and ReFS volumes,
/// immediately removing the file from the directory namespace upon return while keeping the file
/// data intact until all handles close (matching POSIX `unlink(2)`)
///
/// If `FileDispositionInfoEx` is not supported (older Windows versions,
/// e.g. Windows 7/8/Server 2012, or filesystems that return `ERROR_NOT_SUPPORTED` /
/// `ERROR_INVALID_PARAMETER`), we fall back to classic `FileDispositionInfo`
fn set_disposition_raw(handle: HANDLE) -> FrozenResult<()> {
    // FileDispositionInfoEx similar to POSIX semantics (Win 10 1607+)
    let info_ex = FILE_DISPOSITION_INFO_EX {
        Flags: FILE_DISPOSITION_FLAG_DELETE | FILE_DISPOSITION_FLAG_POSIX_SEMANTICS,
    };

    let ok = unsafe {
        SetFileInformationByHandle(
            handle,
            FileDispositionInfoEx,
            &info_ex as *const _ as *const core::ffi::c_void,
            core::mem::size_of::<FILE_DISPOSITION_INFO_EX>() as u32,
        )
    };

    if ok != 0 {
        return Ok(());
    }

    // INFO: If not supported by the OS or filesystem driver, we must fall back to FileDispositionInfo

    let code = last_error();
    if code == ERROR_NOT_SUPPORTED || code == ERROR_INVALID_PARAMETER {
        let info = FILE_DISPOSITION_INFO { DeleteFile: 1 };
        let ok_classic = unsafe {
            SetFileInformationByHandle(
                handle,
                FileDispositionInfo,
                &info as *const _ as *const core::ffi::c_void,
                core::mem::size_of::<FILE_DISPOSITION_INFO>() as u32,
            )
        };

        if ok_classic != 0 {
            return Ok(());
        }

        let code_classic = last_error();
        let err_msg = err_msg(code_classic);

        return match code_classic {
            ERROR_ACCESS_DENIED => err::raw_error(err::PRM, err_msg),
            ERROR_INVALID_HANDLE => err::raw_error(err::HCF, err_msg),
            ERROR_SHARING_VIOLATION | ERROR_LOCK_VIOLATION => err::raw_error(err::LCK, err_msg),
            ERROR_NOT_SUPPORTED | ERROR_INVALID_PARAMETER => err::raw_error(err::INV, err_msg),
            _ => err::raw_error(err::UNK, err_msg),
        };
    }

    let err_msg = err_msg(code);
    match code {
        ERROR_ACCESS_DENIED => err::raw_error(err::PRM, err_msg),
        ERROR_INVALID_HANDLE => err::raw_error(err::HCF, err_msg),
        ERROR_SHARING_VIOLATION | ERROR_LOCK_VIOLATION => err::raw_error(err::LCK, err_msg),
        _ => err::raw_error(err::UNK, err_msg),
    }
}

/// Query the current logical file length via `GetFileSizeEx`
///
/// Returns a `LARGE_INTEGER` (i64); negative values indicate severe NTFS corruption
fn get_size_raw(handle: HANDLE) -> FrozenResult<usize> {
    let mut size: i64 = 0;
    let ok = unsafe { GetFileSizeEx(handle, &mut size) };

    if ok == 0 {
        let code = last_error();
        let err_msg = err_msg(code);

        if code == ERROR_INVALID_HANDLE {
            return err::raw_error(err::HCF, err_msg);
        }

        return err::raw_error(err::UNK, err_msg);
    }

    if hints::unlikely(size < 0) {
        return err::raw_error(err::HCF, "filesystem reported negative file size");
    }

    match usize::try_from(size) {
        Ok(sz) => Ok(sz),
        Err(_) => err::raw_error(err::HCF, "file size exceeds usize address space"),
    }
}

/// Flush the parent directory of `path` to durable storage
///
/// ## Why Sync the Parent Directory on Windows?
///
/// NTFS with default settings journals directory updates, so a `DeleteFileW` or `CreateFileW`
/// followed by a crash will typically be replayed correctly on the next mount
///
/// However,
///
/// - `ReFS` does not have a traditional journal; it uses copy-on-write tree updates, and un-flushed
///   metadata changes may be lost on a sudden power failure
/// - Network-redirected volumes (SMB, iSCSI) often have their own caching layers that do not
///   participate in NTFS's local journal
/// - Developer machines running exFAT or FAT32 (common on SD cards or cross-platform shares) have
///   no jouranaling at all
///
/// We open the parent directory with `FILE_FLAG_BACKUP_SEMANTICS` (which is required to open
/// directories) and call `FlushFileBuffers`
///
/// On NTFS this is a no-op most of the time (journal replay handles it), but on the filesystems
/// above it provides an actual durability guarantee
///
/// ## Best-effort
///
/// If the parent directory cannot be opened (permission denied, path resolution failure), we
/// silently continue the worst outcome is that a crash loses the directory entry, which is
/// recoverable by the caller's higher-level recovery logic
fn sync_parent_dir(path: &std::path::Path) -> FrozenResult<()> {
    let parent = extract_parent_dir(path);
    let wide = match path_to_wide(&parent) {
        Ok(w) => w,
        Err(_) => return Ok(()), // best effort (skip if path encoding fails)
    };

    let h = unsafe {
        CreateFileW(
            wide.as_ptr(),
            GENERIC_READ | GENERIC_WRITE,
            FILE_SHARE_READ | FILE_SHARE_WRITE,
            core::ptr::null(),
            OPEN_EXISTING,
            // FILE_FLAG_BACKUP_SEMANTICS is required to open a directory handle on Win32
            FILE_FLAG_BACKUP_SEMANTICS,
            core::ptr::null_mut(),
        )
    };

    if h == INVALID_HANDLE_VALUE {
        // Best effort (inability to open the parent directory is non fatal)
        return Ok(());
    }

    // INFO:
    //
    // We intentionally ignore flush errors on the directory handle
    //
    // On NTFS, directory flushes are almost always a no-op because the journal already protects directory metadata
    //
    // On ReFS/exFAT the flush is best-effort due to driver limitations
    //
    // In neither case does a failed directory flush constitute a data loss event for the file itself; only for the
    // directory entry, which is recoverable
    let _ = flush_raw(h);

    // INFO:
    //
    // Ignore close errors on the directory handle
    //
    // The handle was opened read-only (no writes pending), so CloseHandle cannot report deferred I/O errors
    let _ = close_raw(h);

    Ok(())
}

/// Convert a `std::path::Path` to a NUL-terminated UTF-16 wide string
///
/// Win32 Unicode APIs (`CreateFileW`, `DeleteFileW`, etc.) require UTF-16LE strings with a NULL
/// terminator
///
/// Rust paths on Windows are `OsString` backed and can be converted losslessly via `encode_wide()`
///
/// We append a trailing `0u16` for the NUL terminator
///
/// ## Errors
///
/// Returns `err::INV` if `path` contains embedded NUL characters (which would truncate the string
/// passed to Win32 and silently open a different file)
fn path_to_wide(path: &std::path::Path) -> FrozenResult<Vec<u16>> {
    use std::os::windows::ffi::OsStrExt;

    let mut wide: Vec<u16> = path.as_os_str().encode_wide().collect();

    // Guard against embedded NUL in the path, which would silently truncate the Win32 call
    if wide.contains(&0u16) {
        return err::raw_error(err::INV, "path contains embedded NUL character");
    }

    wide.push(0); // NULL terminator
    Ok(wide)
}

/// Read the Win32 last error code for the current thread
///
/// All Win32 APIs set the thread local error code before returning
///
/// We read it immediately after a failed call to avoid it being overwritten by any intermediate
/// operation
#[inline]
fn last_error() -> u32 {
    unsafe { windows_sys::Win32::Foundation::GetLastError() }
}

/// Format a Win32 error code as a human-readable string
///
/// Delegates to `std::io::Error::from_raw_os_error` which calls `FormatMessageW` internally
///
/// The resulting string is suitable for inclusion in [`FrozenError`](crate::error::FrozenError)
/// messages
#[inline]
fn err_msg(code: u32) -> String {
    std::io::Error::from_raw_os_error(code as i32).to_string()
}

/// Build the parent directory path from `path`
///
/// If `path` has no parent component
/// (e.g. a bare filename), returns `"."` so that `sync_parent_dir` operates on the current working
/// directory
fn extract_parent_dir(path: &std::path::Path) -> std::path::PathBuf {
    match path.parent() {
        Some(p) if !p.as_os_str().is_empty() => p.to_path_buf(),
        _ => std::path::Path::new(".").to_path_buf(),
    }
}

/// Construct a zeroed `OVERLAPPED` with the I/O offset pre filled
///
/// Win32 decomposes the 64-bit file offset into two 32-bit fields (`Offset` and `OffsetHigh`)
/// stored inside the `Anonymous.Anonymous` union within `OVERLAPPED`
///
/// We zero the struct first (satisfying any reserved-field requirements) and then set the two
/// offset fields
///
/// `hEvent` is left `NULL` because we use synchronous I/O (`ReadFile`/`WriteFile` with a non-NULL
/// `OVERLAPPED` still completes synchronously when the file is opened without
/// `FILE_FLAG_OVERLAPPED`)
#[inline(always)]
fn overlapped_at(offset_lo: u32, offset_hi: u32) -> OVERLAPPED {
    OVERLAPPED {
        Internal: 0,
        InternalHigh: 0,
        Anonymous: OVERLAPPED_0 {
            Anonymous: OVERLAPPED_0_0 { Offset: offset_lo, OffsetHigh: offset_hi },
        },
        hEvent: core::ptr::null_mut(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::{path::PathBuf, sync::Arc};

    fn tmp_path() -> (tempfile::TempDir, PathBuf) {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("tmp_file");
        (dir, path)
    }

    mod file_new_close {
        use super::*;

        #[test]
        fn ok_new_close_cycle() {
            let (_dir, path) = tmp_path();
            let file = WINFile::new(&path).unwrap();
            assert!(path.exists());
            file.close().unwrap();
        }

        #[test]
        fn ok_new_close_cycle_on_existing() {
            let (_dir, path) = tmp_path();
            let file1 = WINFile::new(&path).unwrap();
            file1.close().unwrap();

            let file2 = WINFile::new(&path).unwrap();
            file2.close().unwrap();
        }

        #[test]
        fn err_new_on_missing_parent_dir() {
            let (_dir, path) = tmp_path();
            let missing = path.join("missing\\sub\\dir\\file");
            let err = WINFile::new(&missing).unwrap_err();
            assert_eq!(err.reason, err::INV.reason);
        }
    }

    mod file_create_open {
        use super::*;

        #[test]
        fn ok_create_close_cycle() {
            let (_dir, path) = tmp_path();
            let file = WINFile::create(&path).unwrap();
            assert!(path.exists());
            file.close().unwrap();
        }

        #[test]
        fn err_create_when_already_exists() {
            let (_dir, path) = tmp_path();
            let file = WINFile::create(&path).unwrap();
            let err = WINFile::create(&path).unwrap_err();
            assert_eq!(err.reason, err::EXS.reason);
            file.close().unwrap();
        }

        #[test]
        fn err_create_on_missing_parent_dir() {
            let (_dir, path) = tmp_path();
            let missing = path.join("missing\\sub\\file");
            let err = WINFile::create(&missing).unwrap_err();
            assert_eq!(err.reason, err::INV.reason);
        }

        #[test]
        fn ok_open_existing_file() {
            let (_dir, path) = tmp_path();
            let file = WINFile::create(&path).unwrap();
            file.close().unwrap();

            let opened = WINFile::open(&path).unwrap();
            opened.close().unwrap();
        }

        #[test]
        fn err_open_on_missing_file() {
            let (_dir, path) = tmp_path();
            let err = WINFile::open(&path).unwrap_err();
            assert_eq!(err.reason, err::INV.reason);
        }
    }

    mod file_unlink {
        use super::*;

        #[test]
        fn ok_unlink_existing() {
            let (_dir, path) = tmp_path();
            let file = WINFile::new(&path).unwrap();
            assert!(path.exists());

            file.unlink(&path).unwrap();
            assert!(!path.exists());
        }

        #[test]
        fn ok_unlink_while_locked_and_immediate_recreate() {
            let (_dir, path) = tmp_path();
            let file = WINFile::new(&path).unwrap();
            file.flock().unwrap();

            file.unlink(&path).unwrap();
            assert!(!path.exists());

            let new_file = WINFile::create(&path).unwrap();
            assert!(path.exists());
            new_file.close().unwrap();
        }

        #[test]
        fn err_open_after_unlink_grown_file() {
            let (_dir, path) = tmp_path();
            let file = WINFile::new(&path).unwrap();

            file.grow(0, 0x2000).unwrap();
            assert_eq!(file.length().unwrap(), 0x2000);

            file.unlink(&path).unwrap();
            assert!(!path.exists());

            let err = WINFile::open(&path).unwrap_err();
            assert_eq!(err.reason, err::INV.reason);
        }

        #[test]
        fn ok_unlink_concurrent_reader_handles() {
            let (_dir, path) = tmp_path();
            let file = WINFile::new(&path).unwrap();

            let reader = WINFile::open(&path).unwrap();

            // NOTE: deleting while reader is open succeeds due to FILE_SHARE_DELETE + POSIX disposition semantics
            file.unlink(&path).unwrap();

            reader.close().unwrap();
            assert!(!path.exists());
        }

        #[test]
        fn err_concurrent_open_during_and_after_unlink() {
            let (_dir, path) = tmp_path();
            let file = WINFile::new(&path).unwrap();
            file.grow(0, 0x1000).unwrap();

            let running = Arc::new(atomic::AtomicBool::new(true));

            // Thread 2: constantly attempts WINFile::open
            let opener = {
                let path = path.clone();
                let running = running.clone();
                std::thread::spawn(move || {
                    let mut attempts = 0;
                    while running.load(atomic::Ordering::Relaxed) || attempts < 0x32 {
                        attempts += 1;
                        let res = WINFile::open(&path);
                        // Once unlinked, open must fail with INV (file not found) or PRM (delete-pending) It must never
                        // succeed after unlink
                        if let Err(e) = res {
                            assert!(
                                e.reason == err::INV.reason || e.reason == err::PRM.reason,
                                "Unexpected error reason: {:?}",
                                e
                            );
                        }
                        std::thread::yield_now();
                    }
                })
            };

            // Thread 1: unlinks the file
            std::thread::sleep(std::time::Duration::from_millis(5));
            file.unlink(&path).unwrap();
            running.store(false, atomic::Ordering::Relaxed);

            opener.join().unwrap();

            // After unlink, opening must consistently fail with INV
            let err = WINFile::open(&path).unwrap_err();
            assert_eq!(err.reason, err::INV.reason);
        }

        #[test]
        fn ok_concurrent_new_fails_before_unlink_and_succeeds_after() {
            let (_dir, path) = tmp_path();
            let file = WINFile::create(&path).unwrap();
            file.grow(0, 0x1000).unwrap();

            let unlinked = Arc::new(atomic::AtomicBool::new(false));

            let creator = {
                let path = path.clone();
                let unlinked = unlinked.clone();
                std::thread::spawn(move || {
                    let mut created = None;
                    // Before unlink occurs, WINFile::create must fail with EXS (or PRM while delete is pending) Once
                    // unlink completes, WINFile::create must eventually succeed
                    while created.is_none() {
                        match WINFile::create(&path) {
                            Ok(f) => {
                                assert!(
                                    unlinked.load(atomic::Ordering::Acquire),
                                    "WINFile::create succeeded before file.unlink completed!"
                                );
                                created = Some(f);
                            }
                            Err(e) => {
                                assert!(
                                    e.reason == err::EXS.reason || e.reason == err::PRM.reason,
                                    "Unexpected error reason during race: {:?}",
                                    e
                                );
                                std::thread::yield_now();
                            }
                        }
                    }
                    created.unwrap()
                })
            };

            std::thread::sleep(std::time::Duration::from_millis(0x0A));
            unlinked.store(true, atomic::Ordering::Release);
            file.unlink(&path).unwrap();

            let new_file = creator.join().unwrap();
            assert!(WINFile::exists(&path).unwrap());
            new_file.close().unwrap();
        }

        #[test]
        fn err_unlink_missing() {
            let (_dir, path) = tmp_path();

            let file = WINFile::create(&path).unwrap();
            let missing_path = path.with_file_name("definitely_does_not_exist.db");

            // NOTE: constructing with CLOSED_HANDLE so unlink's internal close is a no-op
            let inner_file = WINFile { handle: atomic::AtomicIsize::new(CLOSED_HANDLE) };
            let err = inner_file.unlink(&missing_path).unwrap_err();
            assert_eq!(err.reason, err::INV.reason);

            file.close().unwrap();
        }
    }

    mod file_lock {
        use super::*;

        #[test]
        fn ok_flock_acquires_exclusive_lock() {
            let (_dir, path) = tmp_path();
            let file = WINFile::new(&path).unwrap();
            file.flock().unwrap();
            file.close().unwrap();
        }

        #[test]
        fn err_flock_when_already_locked() {
            let (_dir, path) = tmp_path();
            let file1 = WINFile::new(&path).unwrap();
            file1.flock().unwrap();

            let file2 = WINFile::new(&path).unwrap();
            let err = file2.flock().unwrap_err();
            assert_eq!(err.reason, err::LCK.reason);

            file1.close().unwrap();
            file2.close().unwrap();
        }

        #[test]
        fn ok_flock_released_after_close() {
            let (_dir, path) = tmp_path();
            let file1 = WINFile::new(&path).unwrap();
            file1.flock().unwrap();
            file1.close().unwrap();

            let file2 = WINFile::new(&path).unwrap();
            file2.flock().unwrap();
            file2.close().unwrap();
        }
    }

    mod file_grow {
        use super::*;

        #[test]
        fn ok_grow() {
            let (_dir, path) = tmp_path();
            let file = WINFile::new(&path).unwrap();

            let initial = file.length().unwrap();
            assert_eq!(initial, 0);

            file.grow(0, 0x1000).unwrap();
            let new_len = file.length().unwrap();
            assert_eq!(new_len, 0x1000);

            file.close().unwrap();
        }

        #[test]
        fn ok_grow_extends_with_zero() {
            let (_dir, path) = tmp_path();
            let file = WINFile::new(&path).unwrap();
            file.grow(0, 0x500).unwrap();

            let mut buf = vec![0u8; 0x500];
            file.pread(&mut buf, 0).unwrap();

            assert!(buf.iter().all(|b| *b == 0));
            file.close().unwrap();
        }

        #[test]
        fn ok_grow_zero_noop() {
            let (_dir, path) = tmp_path();
            let file = WINFile::new(&path).unwrap();
            file.grow(0, 0).unwrap();
            assert_eq!(file.length().unwrap(), 0);
            file.close().unwrap();
        }

        #[test]
        fn ok_grow_multiple_times() {
            let (_dir, path) = tmp_path();
            let file = WINFile::new(&path).unwrap();

            file.grow(0, 0x1000).unwrap();
            file.grow(0x1000, 0x2000).unwrap();

            assert_eq!(file.length().unwrap(), 0x3000);
            file.close().unwrap();
        }
    }

    mod file_sync {
        use super::*;

        #[test]
        fn ok_sync() {
            let (_dir, path) = tmp_path();
            let file = WINFile::new(&path).unwrap();
            file.grow(0, 0x1000).unwrap();
            file.sync().unwrap();
            file.close().unwrap();
        }
    }

    mod file_pread_pwrite {
        use super::*;

        #[test]
        fn ok_pwrite_and_pread() {
            let (_dir, path) = tmp_path();
            let file = WINFile::new(&path).unwrap();
            file.grow(0, 0x1000).unwrap();

            let data = [0xABu8; 0x100];
            file.pwrite(&data, 0x200).unwrap();

            let mut buf = [0u8; 0x100];
            file.pread(&mut buf, 0x200).unwrap();

            assert_eq!(buf, data);
            file.close().unwrap();
        }

        #[test]
        fn ok_pwrite_empty_noop() {
            let (_dir, path) = tmp_path();
            let file = WINFile::new(&path).unwrap();
            file.pwrite(&[], 0).unwrap();
            file.close().unwrap();
        }

        #[test]
        fn ok_pread_empty_noop() {
            let (_dir, path) = tmp_path();
            let file = WINFile::new(&path).unwrap();
            file.pread(&mut [], 0).unwrap();
            file.close().unwrap();
        }

        #[test]
        fn ok_pwrite_at_multiple_offsets() {
            let (_dir, path) = tmp_path();
            let file = WINFile::new(&path).unwrap();
            file.grow(0, 0x1000).unwrap();

            file.pwrite(&[0x11u8; 0x100], 0x000).unwrap();
            file.pwrite(&[0x22u8; 0x100], 0x100).unwrap();
            file.pwrite(&[0x33u8; 0x100], 0x200).unwrap();

            let mut a = [0u8; 0x100];
            let mut b = [0u8; 0x100];
            let mut c = [0u8; 0x100];

            file.pread(&mut a, 0x000).unwrap();
            file.pread(&mut b, 0x100).unwrap();
            file.pread(&mut c, 0x200).unwrap();

            assert_eq!(a, [0x11u8; 0x100]);
            assert_eq!(b, [0x22u8; 0x100]);
            assert_eq!(c, [0x33u8; 0x100]);

            file.close().unwrap();
        }
    }

    mod file_exists {
        use super::*;

        #[test]
        fn ok_exists_true_for_existing_file() {
            let (_dir, path) = tmp_path();
            let file = WINFile::create(&path).unwrap();
            file.close().unwrap();

            assert!(WINFile::exists(&path).unwrap());
        }

        #[test]
        fn ok_exists_false_for_missing_file() {
            let (_dir, path) = tmp_path();
            assert!(!WINFile::exists(&path).unwrap());
        }
    }

    mod file_fd {
        use super::*;

        #[test]
        fn ok_fd_not_closed_after_open() {
            let (_dir, path) = tmp_path();
            let file = WINFile::new(&path).unwrap();
            assert_ne!(file.fd(), CLOSED_HANDLE);
            assert!(!file.is_closed());
            file.close().unwrap();
        }

        #[test]
        fn ok_is_closed_after_close() {
            let (_dir, path) = tmp_path();
            let file = WINFile::new(&path).unwrap();

            file.close().unwrap();
        }
    }
}