graphforge-filesystem 0.6.0-rc.1

Audited native filesystem primitives for GraphForge durability
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
//! Audited native filesystem primitives used by GraphForge's durability
//! protocol.
//!
//! Cache-release I/O and platform operations have private owners; common
//! capability types and public entrypoints remain at the crate root.

#![deny(unsafe_code)]

use std::ffi::{OsStr, OsString};
use std::fs::File;
use std::io;
use std::path::{Path, PathBuf};

mod cache_io;
mod platform;
#[cfg(windows)]
#[allow(unsafe_code)]
mod windows;
#[cfg(windows)]
mod windows_cas;

pub use cache_io::DEFAULT_CACHE_RELEASE_WINDOW_BYTES;
pub use cache_io::DurableFileCacheWriter;
pub use cache_io::FileCacheReleaseEvidence;
pub use cache_io::FileCacheReleaseOutcome;
pub use cache_io::FileCacheReleaseTracker;
pub use cache_io::FileCacheReleasingReader;
pub use cache_io::cache_release_window_for_streams;
pub use cache_io::release_file_cache;
pub use cache_io::validate_cache_release_operation_windows;
use platform::create_private_directory_platform;
use platform::file_identity_platform;
use platform::file_link_count_platform;
use platform::file_space_usage_platform;
use platform::install_new_file_platform;
pub use platform::is_link_or_reparse;
use platform::link_count;
use platform::path_identity_platform;
use platform::path_link_count_platform;
use platform::rename_no_replace_platform;
use platform::stable_child_names;
use platform::stable_child_names_bounded;
use platform::stable_create_child_directory;
use platform::stable_link_child;
use platform::stable_open_child_directory;
use platform::stable_open_child_file;
use platform::stable_open_directory;
#[cfg(windows)]
use platform::stable_open_directory_for_sync;
use platform::stable_open_or_create_child_file;
use platform::stable_open_publishing_child_file;
use platform::stable_open_replaceable_child_file;
use platform::stable_remove_child_directory_if_identity;
use platform::stable_unlink_child_if_identity;
use platform::visit_regular_files_platform;
use platform::{replace_file_from_platform, replace_file_platform};
#[cfg(windows)]
pub use windows_cas::{WindowsCasWriter, WindowsLegacyCasAdopter, WindowsSealedCasFile};

/// Stable filesystem identity suitable for Windows and Unix filesystems.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FileIdentity {
    /// Native volume/device identity.
    pub volume_serial: u64,
    /// Full native file identity (128-bit on Windows; zero-extended inode on Unix).
    pub file_id: [u8; 16],
}

/// Logical and physically allocated byte counts for one retained file handle.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FileSpaceUsage {
    /// Logical end-of-file length visible to readers.
    pub logical_bytes: u64,
    /// Physical filesystem allocation charged to the file.
    pub allocated_bytes: u64,
}

/// Stage of a failed retained-directory validation. Policy owners may preserve
/// their own diagnostics without duplicating native identity checks.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DirectoryValidationStage {
    /// Named path metadata could not be read.
    NamedMetadata,
    /// Retained handle metadata could not be read.
    RetainedMetadata,
    /// Named path identity could not be read.
    NamedIdentity,
    /// Retained handle identity could not be read.
    RetainedIdentity,
    /// A path/handle is not an ordinary directory or its identity changed.
    IdentityChanged,
}

/// Native validation failure with a typed stage and original I/O diagnostic.
#[derive(Debug)]
pub struct DirectoryValidationError {
    stage: DirectoryValidationStage,
    source: io::Error,
}

impl DirectoryValidationError {
    fn new(stage: DirectoryValidationStage, source: io::Error) -> Self {
        Self { stage, source }
    }

    /// Return the failing native operation for a caller's policy mapping.
    #[must_use]
    pub fn stage(&self) -> DirectoryValidationStage {
        self.stage
    }

    /// Preserve the existing native I/O error and kind for generic consumers.
    #[must_use]
    pub fn into_io_error(self) -> io::Error {
        self.source
    }
}

impl std::fmt::Display for DirectoryValidationError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        std::fmt::Display::fmt(&self.source, formatter)
    }
}

impl std::error::Error for DirectoryValidationError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(&self.source)
    }
}

/// Directory handle opened with this crate's native no-follow and sharing policy.
/// Private construction prevents an arbitrary `File` from claiming that policy.
#[derive(Debug)]
pub struct OpenedDirectoryHandle {
    file: File,
}

impl OpenedDirectoryHandle {
    /// Borrow the native handle for metadata, volume queries, or cooperative locks.
    #[must_use]
    pub fn as_file(&self) -> &File {
        &self.file
    }

    /// Transfer the raw handle to a caller that owns its validation policy.
    #[must_use]
    pub fn into_file(self) -> File {
        self.file
    }
}

/// Retained directory capability whose children are opened without following
/// links or reparse points.
#[derive(Debug)]
pub struct StableDirectory {
    path: PathBuf,
    file: File,
    identity: FileIdentity,
}

/// Single-owner capability for one exclusively created, unpublished child.
///
/// The guard follows the owned inode across an atomic rename and removes any
/// still-uncommitted name on explicit cleanup or drop. Callers must retain the
/// guard until every higher-level publication invariant, including parent
/// directory synchronization and manifest/receipt inclusion, is complete.
#[derive(Debug)]
pub struct UnpublishedArtifactGuard {
    directory: StableDirectory,
    candidate_names: Vec<OsString>,
    identity: Option<FileIdentity>,
    file: Option<File>,
    published: bool,
    parent_synced: bool,
    armed: bool,
}

impl UnpublishedArtifactGuard {
    /// Return the immutable identity captured during descriptor setup.
    ///
    /// # Errors
    /// Returns an error before descriptor identity has been initialized.
    pub fn identity(&self) -> io::Result<FileIdentity> {
        self.identity
            .ok_or_else(|| io::Error::other("unpublished artifact identity is not initialized"))
    }

    /// Re-read the retained descriptor identity and run a setup check before
    /// the descriptor is transferred to a writer.
    ///
    /// # Errors
    /// Returns an error when identity observation, `setup_check`, or the
    /// identity comparison fails.
    pub fn verify_identity_with(
        &mut self,
        setup_check: impl FnOnce() -> io::Result<()>,
    ) -> io::Result<FileIdentity> {
        let file = self
            .file
            .as_ref()
            .ok_or_else(|| io::Error::other("unpublished artifact descriptor was transferred"))?;
        let observed = file_identity(file)?;
        self.identity = Some(observed);
        setup_check()?;
        Ok(observed)
    }

    /// Borrow the private original candidate name for durability-owner validation.
    pub fn temporary_name(&self) -> io::Result<&OsStr> {
        self.candidate_names
            .first()
            .map(OsString::as_os_str)
            .ok_or_else(|| io::Error::other("unpublished artifact has no temporary name"))
    }

    /// Open one sibling through the retained no-follow parent capability.
    ///
    /// # Errors
    /// Returns an error when the child is absent, special, linked, or the
    /// retained directory authority changed.
    pub fn open_sibling(&self, name: &OsStr) -> io::Result<File> {
        self.directory.open_child_file(name)
    }

    /// Transfer the retained data descriptor into its durable writer.
    ///
    /// # Errors
    /// Returns an error if identity observation fails or the descriptor was
    /// already transferred.
    pub fn take_file(&mut self) -> io::Result<File> {
        if self.identity.is_none() {
            let file = self
                .file
                .as_ref()
                .ok_or_else(|| io::Error::other("unpublished artifact file already transferred"))?;
            self.identity = Some(file_identity(file)?);
        }
        self.file
            .take()
            .ok_or_else(|| io::Error::other("unpublished artifact file already transferred"))
    }

    /// Transfer exclusive unpublished cleanup to a new owner of this same file.
    /// A published guard cannot relinquish its semantic commit obligations.
    pub fn transfer_unpublished_owner(
        self,
        file: &File,
    ) -> io::Result<(StableDirectory, OsString, FileIdentity)> {
        let directory = self.directory.try_clone()?;
        self.transfer_unpublished_owner_in(directory, file)
    }

    /// Transfer an already-owned retained parent without duplicating its handle.
    pub fn transfer_unpublished_owner_in(
        mut self,
        directory: StableDirectory,
        file: &File,
    ) -> io::Result<(StableDirectory, OsString, FileIdentity)> {
        if self.published || self.file.is_some() || self.candidate_names.len() != 1 {
            return Err(io::Error::other(
                "unpublished owner transfer invariants are incomplete",
            ));
        }
        let expected = self.identity()?;
        self.directory.revalidate_named()?;
        directory.revalidate_named()?;
        let name = self.candidate_names[0].clone();
        let named = directory.open_child_file(&name)?;
        if directory.identity() != self.directory.identity()
            || file_identity(file)? != expected
            || file_identity(&named)? != expected
            || file_link_count(file)? != 1
        {
            return Err(io::Error::other(
                "unpublished owner transfer identity changed",
            ));
        }
        self.armed = false;
        Ok((directory, name, expected))
    }

    /// Atomically install `target` while retaining cleanup ownership.
    ///
    /// # Errors
    /// Returns an error when identity-safe installation fails.
    pub fn install_child(&mut self, target: &OsStr) -> io::Result<()> {
        validate_child_name(target)?;
        let temporary = self
            .candidate_names
            .first()
            .ok_or_else(|| io::Error::other("unpublished artifact has no temporary name"))?
            .clone();
        if !self.candidate_names.iter().any(|name| name == target) {
            self.candidate_names.push(target.to_owned());
        }
        self.directory
            .install_child(&temporary, self.identity()?, target)?;
        self.published = true;
        self.parent_synced = false;
        Ok(())
    }

    /// Synchronize the retained parent directory while remaining armed.
    ///
    /// # Errors
    /// Returns an error when the directory durability barrier fails.
    pub fn sync_parent(&mut self) -> io::Result<()> {
        self.sync_parent_with(StableDirectory::sync)
    }

    /// Acknowledge through the caller's durability owner, then mark this guard.
    pub fn sync_parent_with(
        &mut self,
        acknowledge: impl FnOnce(&StableDirectory) -> io::Result<()>,
    ) -> io::Result<()> {
        acknowledge(&self.directory)?;
        self.parent_synced = true;
        Ok(())
    }

    /// Disarm cleanup after every publication invariant is complete.
    ///
    /// # Errors
    /// Returns an error if the descriptor is still held by the guard or the
    /// atomic publication and parent barrier have not both completed.
    pub fn commit(mut self) -> io::Result<()> {
        if self.file.is_some() || !self.published || !self.parent_synced {
            return Err(io::Error::other(
                "unpublished artifact commit invariants are incomplete",
            ));
        }
        self.armed = false;
        Ok(())
    }

    /// Remove every possible uncommitted name and synchronize the parent.
    ///
    /// Names that are absent or no longer identify the exclusively created
    /// inode are left untouched.
    ///
    /// # Errors
    /// Returns sanitized cleanup failure context after attempting every unlink
    /// and the final parent-directory barrier.
    pub fn cleanup(&mut self) -> io::Result<()> {
        if !self.armed {
            return Ok(());
        }
        let mut cleanup = Ok(());
        let identity = match self.identity {
            Some(identity) => Some(identity),
            None => match self
                .file
                .as_ref()
                .ok_or_else(|| io::Error::other("unpublished artifact descriptor is unavailable"))
                .and_then(file_identity)
            {
                Ok(identity) => {
                    self.identity = Some(identity);
                    Some(identity)
                }
                Err(error) => {
                    cleanup = append_sanitized_cleanup(
                        cleanup,
                        &error,
                        "unpublished artifact identity recovery failed",
                    );
                    None
                }
            },
        };
        self.file.take();
        for name in &self.candidate_names {
            let Some(identity) = identity else {
                break;
            };
            let removed = self.directory.open_child_file(name).and_then(|file| {
                if file_identity(&file)? == identity {
                    drop(file);
                    self.directory.unlink_child_if_identity(name, identity)?;
                }
                Ok(())
            });
            match removed {
                Ok(()) => {}
                Err(error) if error.kind() == io::ErrorKind::NotFound => {}
                Err(error) => {
                    cleanup = append_sanitized_cleanup(
                        cleanup,
                        &error,
                        "unpublished artifact unlink failed",
                    );
                }
            }
        }
        cleanup = match self.directory.sync() {
            Ok(()) => cleanup,
            Err(error) => append_sanitized_cleanup(
                cleanup,
                &error,
                "unpublished artifact directory synchronization failed",
            ),
        };
        self.armed = false;
        cleanup
    }

    /// Perform full identity-safe cleanup and its parent barrier, then run one
    /// caller-supplied finalization check.
    ///
    /// # Errors
    /// Returns sanitized cleanup or finalization context after both have been
    /// attempted.
    pub fn cleanup_checked(
        &mut self,
        finalization_check: impl FnOnce() -> io::Result<()>,
    ) -> io::Result<()> {
        let cleanup = self.cleanup();
        match finalization_check() {
            Ok(()) => cleanup,
            Err(error) => append_sanitized_cleanup(
                cleanup,
                &error,
                "unpublished artifact cleanup finalization failed",
            ),
        }
    }
}

impl Drop for UnpublishedArtifactGuard {
    fn drop(&mut self) {
        let _ = self.cleanup();
    }
}

fn append_sanitized_cleanup(
    primary: io::Result<()>,
    cleanup: &io::Error,
    context: &'static str,
) -> io::Result<()> {
    let cleanup = io::Error::new(cleanup.kind(), context);
    match primary {
        Ok(()) => Err(cleanup),
        Err(primary) => Err(io::Error::new(
            primary.kind(),
            format!("{primary}; {cleanup}"),
        )),
    }
}

impl StableDirectory {
    /// Duplicate this retained directory capability without resolving its path again.
    ///
    /// # Errors
    /// Returns an error if the retained directory identity changed or the OS
    /// cannot duplicate its handle.
    pub fn try_clone(&self) -> io::Result<Self> {
        self.revalidate_named()?;
        let clone = Self {
            path: self.path.clone(),
            file: self.file.try_clone()?,
            identity: self.identity,
        };
        clone.revalidate_named()?;
        Ok(clone)
    }

    /// Acquire a cooperative shared lock on this retained Unix directory inode.
    ///
    /// Windows directory handles cannot be byte-range locked; callers use a
    /// retained regular coordination file there instead.
    #[cfg(unix)]
    pub fn lock_shared(&self) -> io::Result<()> {
        <File as fs4::FileExt>::lock_shared(&self.file)
    }

    /// Acquire a cooperative exclusive lock on this retained Unix directory inode.
    #[cfg(unix)]
    pub fn lock_exclusive(&self) -> io::Result<()> {
        <File as fs4::FileExt>::lock(&self.file)
    }

    /// Try to acquire a cooperative exclusive lock on this retained Unix directory inode.
    #[cfg(unix)]
    pub fn try_lock_exclusive(&self) -> io::Result<bool> {
        match <File as fs4::FileExt>::try_lock(&self.file) {
            Ok(()) => Ok(true),
            Err(fs4::TryLockError::WouldBlock) => Ok(false),
            Err(fs4::TryLockError::Error(error)) => Err(error),
        }
    }

    /// Release this retained Unix directory inode's cooperative lock.
    #[cfg(unix)]
    pub fn unlock(&self) -> io::Result<()> {
        <File as fs4::FileExt>::unlock(&self.file)
    }

    /// Open and retain a real directory at `path`.
    pub fn open(path: &Path) -> io::Result<Self> {
        let file = stable_open_directory(path)?;
        let identity = file_identity(&file)?;
        let directory = Self {
            path: path.to_path_buf(),
            file,
            identity,
        };
        directory.revalidate_named()?;
        Ok(directory)
    }

    /// Adopt an already retained handle and expected identity, validating both
    /// the named path and the handle before issuing a directory capability.
    pub fn from_retained_handle(
        path: PathBuf,
        handle: OpenedDirectoryHandle,
        identity: FileIdentity,
    ) -> Result<Self, DirectoryValidationError> {
        let directory = Self {
            path,
            file: handle.file,
            identity,
        };
        directory.revalidate_named_detailed()?;
        Ok(directory)
    }

    /// Borrow the retained handle for native volume queries and cooperative locks.
    /// Callers must revalidate around namespace-sensitive operations.
    #[must_use]
    pub fn as_file(&self) -> &File {
        &self.file
    }

    /// Return the named path associated with this capability.
    #[must_use]
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Transfer the policy-proven native handle for adoption by another capability.
    #[must_use]
    pub fn into_handle(self) -> OpenedDirectoryHandle {
        OpenedDirectoryHandle { file: self.file }
    }

    /// Require that the named path and retained handle still identify this
    /// ordinary directory, returning a typed failure stage for policy adapters.
    pub fn revalidate_named_detailed(&self) -> Result<(), DirectoryValidationError> {
        use DirectoryValidationStage as Stage;
        let named = std::fs::symlink_metadata(&self.path)
            .map_err(|error| DirectoryValidationError::new(Stage::NamedMetadata, error))?;
        let retained = self
            .file
            .metadata()
            .map_err(|error| DirectoryValidationError::new(Stage::RetainedMetadata, error))?;
        if !named.is_dir() || is_link_or_reparse(&named) || !retained.is_dir() {
            return Err(DirectoryValidationError::new(
                Stage::IdentityChanged,
                io::Error::other("stable directory path is linked or special"),
            ));
        }
        #[cfg(unix)]
        let named_identity = platform::metadata_identity(&named);
        #[cfg(not(unix))]
        let named_identity = path_identity(&self.path)
            .map_err(|error| DirectoryValidationError::new(Stage::NamedIdentity, error))?;
        if named_identity != self.identity {
            return Err(DirectoryValidationError::new(
                Stage::IdentityChanged,
                io::Error::other("stable directory identity changed"),
            ));
        }
        #[cfg(unix)]
        let retained_identity = platform::metadata_identity(&retained);
        #[cfg(not(unix))]
        let retained_identity = file_identity(&self.file)
            .map_err(|error| DirectoryValidationError::new(Stage::RetainedIdentity, error))?;
        if retained_identity != self.identity {
            return Err(DirectoryValidationError::new(
                Stage::IdentityChanged,
                io::Error::other("stable directory identity changed"),
            ));
        }
        Ok(())
    }

    /// Require that the named path still identifies this retained directory.
    pub fn revalidate_named(&self) -> io::Result<()> {
        self.revalidate_named_detailed()
            .map_err(DirectoryValidationError::into_io_error)
    }

    /// Open one real child directory relative to this capability.
    pub fn open_child_directory(&self, name: &OsStr) -> io::Result<Self> {
        validate_child_name(name)?;
        self.revalidate_named()?;
        let path = self.path.join(name);
        let file = stable_open_child_directory(&self.file, &path, name)?;
        let child = Self {
            identity: file_identity(&file)?,
            path,
            file,
        };
        child.revalidate_named()?;
        self.revalidate_named()?;
        Ok(child)
    }

    /// Create one child directory if absent, then retain it.
    pub fn create_child_directory(&self, name: &OsStr) -> io::Result<Self> {
        validate_child_name(name)?;
        self.revalidate_named()?;
        stable_create_child_directory(&self.file, &self.path.join(name), name)?;
        self.open_child_directory(name)
    }

    /// Open one regular child without following links or reparse points.
    pub fn open_child_file(&self, name: &OsStr) -> io::Result<File> {
        validate_child_name(name)?;
        self.revalidate_named()?;
        let path = self.path.join(name);
        let file = stable_open_child_file(&self.file, &path, name, false)?;
        validate_stable_child_file(&file, &path)?;
        self.revalidate_named()?;
        Ok(file)
    }

    /// Revalidate a retained regular child against its current named path.
    ///
    /// Performs the same fresh directory and child observations as opening
    /// the child, without replacing the retained handle or its seek position.
    pub fn revalidate_child_file(&self, name: &OsStr, file: &File) -> io::Result<()> {
        validate_child_name(name)?;
        self.revalidate_named()?;
        validate_stable_child_file(file, &self.path.join(name))?;
        self.revalidate_named()
    }

    /// Reopen an already-admitted private publication source with write access
    /// for its file barrier and Windows delete sharing for its native rename.
    /// Ordinary immutable readers retain their existing anti-delete sharing.
    pub fn open_publishing_child_file(
        &self,
        name: &OsStr,
        expected: FileIdentity,
    ) -> io::Result<File> {
        validate_child_name(name)?;
        self.revalidate_named()?;
        let path = self.path.join(name);
        let file = stable_open_publishing_child_file(&self.file, &path, name)?;
        validate_stable_child_file(&file, &path)?;
        if file_identity(&file)? != expected || file_link_count(&file)? != 1 {
            return Err(io::Error::other(
                "publication source identity or link count changed",
            ));
        }
        self.revalidate_named()?;
        Ok(file)
    }

    /// Visit regular descendants through retained, no-follow directory handles.
    ///
    /// Every child is opened relative to its retained parent and revalidated
    /// before it reaches `visit`. Links and non-regular objects are skipped.
    ///
    /// # Errors
    /// Returns an error if traversal exceeds `remaining`, a retained identity
    /// changes, directory enumeration fails, or `visit` fails. Targets without
    /// descriptor-relative directory enumeration return `Unsupported`.
    pub fn visit_regular_files(
        &self,
        remaining: &mut usize,
        visit: &mut impl FnMut(&File) -> io::Result<()>,
    ) -> io::Result<()> {
        self.revalidate_named()?;
        visit_regular_files_platform(self, remaining, visit)?;
        self.revalidate_named()
    }

    /// Create one new regular child without following links or reparse points.
    pub fn create_child_file(&self, name: &OsStr) -> io::Result<File> {
        validate_child_name(name)?;
        self.revalidate_named()?;
        let path = self.path.join(name);
        let file = stable_open_child_file(&self.file, &path, name, true)?;
        validate_stable_child_file(&file, &path)?;
        self.revalidate_named()?;
        Ok(file)
    }

    /// Create a Windows CAS child with exclusive data-write authority.
    ///
    /// Readers may coexist, but no second writer can be admitted. The handle
    /// retains the native authority needed for the irreversible seal.
    #[cfg(windows)]
    pub fn create_cas_child_file(&self, name: &OsStr) -> io::Result<WindowsCasWriter> {
        validate_child_name(name)?;
        self.revalidate_named()?;
        let path = self.path.join(name);
        let file = windows::create_cas_writer(&path)?;
        validate_stable_child_file(&file, &path)?;
        self.revalidate_named()?;
        Ok(WindowsCasWriter {
            identity: file_identity(&file)?,
            file,
        })
    }

    /// Convert an exact Windows CAS writer into an identity-matched sealed reader.
    #[cfg(windows)]
    pub fn seal_cas_child_file(
        &self,
        name: &OsStr,
        writer: WindowsCasWriter,
    ) -> io::Result<WindowsSealedCasFile> {
        validate_child_name(name)?;
        self.revalidate_named()?;
        let path = self.path.join(name);
        let expected = writer.identity;
        if file_identity(&writer.file)? != expected || path_identity(&path)? != expected {
            return Err(io::Error::other(
                "CAS writer identity changed before sealing",
            ));
        }
        windows::seal_cas_writer(&writer.file)?;
        if file_identity(&writer.file)? != expected || path_identity(&path)? != expected {
            return Err(io::Error::other(
                "CAS writer identity changed while sealing",
            ));
        }
        let bridge = windows::open_cas_bridge(&path)?;
        if file_identity(&bridge)? != expected {
            return Err(io::Error::other(
                "CAS bridge identity changed while sealing",
            ));
        }
        drop(writer.file);
        let reader = windows::open_sealed_cas_reader(&path)?;
        validate_stable_child_file(&reader, &path)?;
        if file_identity(&reader)? != expected || path_identity(&path)? != expected {
            return Err(io::Error::other(
                "CAS identity changed while reopening sealed reader",
            ));
        }
        drop(bridge);
        self.revalidate_named()?;
        Ok(WindowsSealedCasFile(reader))
    }

    /// Open a canonically sealed Windows CAS child while excluding writers.
    #[cfg(windows)]
    pub fn open_cas_child_file(&self, name: &OsStr) -> io::Result<WindowsSealedCasFile> {
        validate_child_name(name)?;
        self.revalidate_named()?;
        let path = self.path.join(name);
        let reader = windows::open_sealed_cas_reader(&path)?;
        validate_stable_child_file(&reader, &path)?;
        if !reader.metadata()?.permissions().readonly()
            || !windows::has_canonical_cas_dacl(&reader)?
        {
            return Err(io::Error::new(
                io::ErrorKind::PermissionDenied,
                "CAS child is not canonically sealed",
            ));
        }
        self.revalidate_named()?;
        Ok(WindowsSealedCasFile(reader))
    }

    /// Retain an exclusive metadata handle for authenticating a legacy sealed CAS child.
    #[cfg(windows)]
    pub fn open_legacy_cas_child_for_adoption(
        &self,
        name: &OsStr,
    ) -> io::Result<WindowsLegacyCasAdopter> {
        validate_child_name(name)?;
        self.revalidate_named()?;
        let path = self.path.join(name);
        let file = windows::open_legacy_cas_adopter(&path)?;
        validate_stable_child_file(&file, &path)?;
        let identity = file_identity(&file)?;
        if path_identity(&path)? != identity {
            return Err(io::Error::other("legacy CAS identity changed during open"));
        }
        self.revalidate_named()?;
        Ok(WindowsLegacyCasAdopter { file, identity })
    }

    /// Canonically seal a retained legacy CAS child after caller authentication.
    #[cfg(windows)]
    pub fn adopt_legacy_cas_child(
        &self,
        name: &OsStr,
        adopter: WindowsLegacyCasAdopter,
    ) -> io::Result<WindowsSealedCasFile> {
        validate_child_name(name)?;
        self.revalidate_named()?;
        let path = self.path.join(name);
        windows::set_canonical_cas_dacl(&adopter.file)?;
        let bridge = windows::open_cas_bridge(&path)?;
        if file_identity(&bridge)? != adopter.identity {
            return Err(io::Error::other("legacy CAS bridge identity changed"));
        }
        drop(adopter.file);
        let reader = windows::open_sealed_cas_reader(&path)?;
        if file_identity(&reader)? != adopter.identity || path_identity(&path)? != adopter.identity
        {
            return Err(io::Error::other(
                "legacy CAS identity changed during adoption",
            ));
        }
        drop(bridge);
        self.revalidate_named()?;
        Ok(WindowsSealedCasFile(reader))
    }

    /// Create a new regular child whose retained handle permits an atomic
    /// namespace replacement while it remains open.
    pub fn create_replaceable_child_file(&self, name: &OsStr) -> io::Result<File> {
        validate_child_name(name)?;
        self.revalidate_named()?;
        let path = self.path.join(name);
        let file = stable_open_replaceable_child_file(&self.file, &path, name)?;
        validate_stable_child_file(&file, &path)?;
        self.revalidate_named()?;
        Ok(file)
    }

    /// Exclusively create one replaceable child and immediately bind cleanup
    /// ownership to its retained descriptor identity.
    ///
    /// # Errors
    /// Returns an error when creation, identity capture, or directory-capability
    /// cloning fails. Setup failure removes the exact created inode when safe.
    pub fn create_unpublished_replaceable_child(
        &self,
        name: &OsStr,
    ) -> io::Result<UnpublishedArtifactGuard> {
        // Clone the parent authority before creating the child. From the
        // instant exclusive creation succeeds, no fallible setup remains
        // outside the armed guard.
        let directory = self.try_clone()?;
        let file = self.create_replaceable_child_file(name)?;
        Ok(UnpublishedArtifactGuard {
            directory,
            candidate_names: vec![name.to_owned()],
            identity: None,
            file: Some(file),
            published: false,
            parent_synced: false,
            armed: true,
        })
    }

    /// Open an existing regular child for read/write, or create it once.
    pub fn open_or_create_child_file(&self, name: &OsStr) -> io::Result<File> {
        validate_child_name(name)?;
        self.revalidate_named()?;
        let path = self.path.join(name);
        let file = stable_open_or_create_child_file(&self.file, &path, name)?;
        validate_stable_child_file(&file, &path)?;
        self.revalidate_named()?;
        Ok(file)
    }

    /// Enumerate child names while retaining this directory capability.
    pub fn child_names(&self) -> io::Result<Vec<std::ffi::OsString>> {
        self.revalidate_named()?;
        stable_child_names(&self.file, &self.path)
    }

    /// Enumerate no more than `limit` child names from this retained directory.
    /// Returns `InvalidData` instead of materializing an attacker-sized sibling
    /// inventory when the bound is exceeded.
    pub fn child_names_bounded(&self, limit: usize) -> io::Result<Vec<std::ffi::OsString>> {
        self.revalidate_named()?;
        stable_child_names_bounded(&self.file, &self.path, limit)
    }

    /// Create a hard link between retained source and destination directories.
    pub fn link_child_into(
        &self,
        source_name: &OsStr,
        source: &File,
        expected_source: FileIdentity,
        destination: &Self,
        destination_name: &OsStr,
    ) -> io::Result<(File, FileIdentity)> {
        validate_child_name(source_name)?;
        validate_child_name(destination_name)?;
        self.revalidate_named()?;
        destination.revalidate_named()?;
        validate_stable_child_file(source, &self.path.join(source_name))?;
        if file_identity(source)? != expected_source {
            return Err(io::Error::other("hard-link source identity changed"));
        }
        stable_link_child(
            &self.file,
            &self.path,
            source_name,
            &destination.file,
            &destination.path,
            destination_name,
        )?;
        self.revalidate_named()?;
        destination.revalidate_named()?;
        let installed = destination.open_child_file(destination_name)?;
        let installed_identity = file_identity(&installed)?;
        if installed_identity != expected_source {
            return Err(io::Error::other("hard-link destination identity mismatch"));
        }
        Ok((installed, installed_identity))
    }

    /// Remove a child under the caller's held cooperative exclusive lifecycle
    /// guard, only while its current named identity matches `expected`.
    pub fn unlink_child_if_identity(&self, name: &OsStr, expected: FileIdentity) -> io::Result<()> {
        validate_child_name(name)?;
        self.revalidate_named()?;
        stable_unlink_child_if_identity(&self.file, &self.path, name, expected)?;
        self.revalidate_named()
    }

    /// Remove one empty child directory only while its retained and named
    /// identities still match. Callers must first authenticate and empty the
    /// directory through the returned child capability.
    pub fn remove_child_directory_if_identity(
        &self,
        name: &OsStr,
        expected: FileIdentity,
    ) -> io::Result<()> {
        validate_child_name(name)?;
        self.revalidate_named()?;
        stable_remove_child_directory_if_identity(&self.file, &self.path, name, expected)?;
        self.revalidate_named()
    }

    /// Atomically publish a retained temporary child as `target` within this
    /// retained directory. Cooperative publishers must serialize the target.
    pub fn replace_child(
        &self,
        temporary: &OsStr,
        expected_temporary: FileIdentity,
        target: &OsStr,
    ) -> io::Result<()> {
        self.replace_child_typed(temporary, expected_temporary, target)
            .map_err(|error| io::Error::other(error.to_string()))
    }

    /// Replace one child while retaining native visibility uncertainty.
    pub fn replace_child_typed(
        &self,
        temporary: &OsStr,
        expected_temporary: FileIdentity,
        target: &OsStr,
    ) -> Result<(), ReplaceFileError> {
        let prepare = || -> io::Result<bool> {
            validate_child_name(temporary)?;
            validate_child_name(target)?;
            self.revalidate_named()?;
            let temporary_file = self.open_child_file(temporary)?;
            if file_identity(&temporary_file)? != expected_temporary
                || file_link_count(&temporary_file)? != 1
            {
                return Err(io::Error::other(
                    "atomic temporary child identity or link count changed",
                ));
            }
            match self.open_child_file(target) {
                Ok(_) => Ok(true),
                Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
                Err(error) => Err(error),
            }
        };
        if prepare().map_err(ReplaceFileError::NotReplaced)? {
            replace_file_platform(
                &self.file,
                temporary,
                target,
                Some(expected_temporary),
                None,
            )?;
        } else {
            install_new_file_platform(&self.file, temporary, target, Some(expected_temporary))
                .map_err(ReplaceFileError::StateUnknown)?;
        }
        self.validate_replaced_child(target, expected_temporary)
            .map_err(ReplaceFileError::StateUnknown)
    }

    fn validate_replaced_child(&self, target: &OsStr, expected: FileIdentity) -> io::Result<()> {
        self.revalidate_named()?;
        let installed = self.open_child_file(target)?;
        if file_identity(&installed)? != expected || file_link_count(&installed)? != 1 {
            return Err(io::Error::other(
                "replacement target identity or link count changed",
            ));
        }
        Ok(())
    }

    /// Atomically replace an authenticated prior child, which may share its inode
    /// with immutable payloads or active snapshots. The source must be private.
    /// Callers must authenticate the prior contents and serialize publishers;
    /// this operation checks identity and never writes to the prior inode.
    pub fn replace_authenticated_child(
        &self,
        temporary: &OsStr,
        expected_temporary: FileIdentity,
        target: &OsStr,
        expected_target: FileIdentity,
    ) -> io::Result<()> {
        self.replace_authenticated_child_typed(
            temporary,
            expected_temporary,
            target,
            expected_target,
        )
        .map_err(|error| io::Error::other(error.to_string()))
    }

    /// Replace an authenticated prior child without losing native error state.
    pub fn replace_authenticated_child_typed(
        &self,
        temporary: &OsStr,
        expected_temporary: FileIdentity,
        target: &OsStr,
        expected_target: FileIdentity,
    ) -> Result<(), ReplaceFileError> {
        validate_child_name(temporary).map_err(ReplaceFileError::NotReplaced)?;
        validate_child_name(target).map_err(ReplaceFileError::NotReplaced)?;
        self.revalidate_named()
            .map_err(ReplaceFileError::NotReplaced)?;
        replace_file_platform(
            &self.file,
            temporary,
            target,
            Some(expected_temporary),
            Some(expected_target),
        )?;
        self.validate_replaced_child(target, expected_temporary)
            .map_err(ReplaceFileError::StateUnknown)
    }

    /// Atomically move an authenticated temporary from another retained
    /// directory over this directory's exact authenticated target.
    ///
    /// The temporary must already be durably sealed: this renames it without
    /// write access, so it neither flushes nor needs to open its payload for
    /// writing. On Windows the caller must not retain its own handle to the
    /// temporary, and a retained reader of the target that denies delete
    /// sharing makes the replacement fail with nothing replaced.
    #[doc(hidden)]
    pub fn replace_authenticated_child_from(
        &self,
        source_directory: &Self,
        temporary: &OsStr,
        expected_temporary: FileIdentity,
        target: &OsStr,
        expected_target: FileIdentity,
    ) -> Result<(), ReplaceFileError> {
        validate_child_name(temporary).map_err(ReplaceFileError::NotReplaced)?;
        validate_child_name(target).map_err(ReplaceFileError::NotReplaced)?;
        source_directory
            .revalidate_named()
            .map_err(ReplaceFileError::NotReplaced)?;
        self.revalidate_named()
            .map_err(ReplaceFileError::NotReplaced)?;
        replace_file_from_platform(
            &source_directory.file,
            &self.file,
            temporary,
            target,
            Some(expected_temporary),
            Some(expected_target),
        )?;
        source_directory
            .revalidate_named()
            .map_err(ReplaceFileError::StateUnknown)?;
        self.validate_replaced_child(target, expected_temporary)
            .map_err(ReplaceFileError::StateUnknown)
    }

    /// Atomically install a retained temporary child without replacing an
    /// existing target. This is the creation authority for durable control
    /// records whose first publication must never overwrite competing state.
    ///
    /// # Errors
    /// Returns an I/O error when either name is invalid, the retained source
    /// identity changed, the target already exists, or durable installation
    /// and identity revalidation fail.
    pub fn install_child(
        &self,
        temporary: &OsStr,
        expected_temporary: FileIdentity,
        target: &OsStr,
    ) -> io::Result<()> {
        validate_child_name(temporary)?;
        validate_child_name(target)?;
        self.revalidate_named()?;
        let temporary_file = self.open_child_file(temporary)?;
        if file_identity(&temporary_file)? != expected_temporary
            || file_link_count(&temporary_file)? != 1
        {
            return Err(io::Error::other(
                "atomic temporary child identity or link count changed",
            ));
        }
        drop(temporary_file);
        install_new_file_platform(&self.file, temporary, target, Some(expected_temporary))?;
        self.revalidate_named()?;
        self.open_child_file(target).map(|_| ())
    }

    /// Preserve whether create-only publication definitely did not install or
    /// reached a native visibility boundary whose result needs reconciliation.
    pub fn install_child_typed(
        &self,
        temporary: &OsStr,
        expected_temporary: FileIdentity,
        target: &OsStr,
    ) -> Result<(), ReplaceFileError> {
        let prepare = || -> io::Result<()> {
            validate_child_name(temporary)?;
            validate_child_name(target)?;
            self.revalidate_named()?;
            let file = self.open_child_file(temporary)?;
            if file_identity(&file)? != expected_temporary || file_link_count(&file)? != 1 {
                return Err(io::Error::other(
                    "atomic temporary child identity or link count changed",
                ));
            }
            Ok(())
        };
        prepare().map_err(ReplaceFileError::NotReplaced)?;
        install_new_file_platform(&self.file, temporary, target, Some(expected_temporary))
            .map_err(|error| {
                if error.kind() == io::ErrorKind::AlreadyExists {
                    ReplaceFileError::NotReplaced(error)
                } else {
                    ReplaceFileError::StateUnknown(error)
                }
            })?;
        self.validate_replaced_child(target, expected_temporary)
            .map_err(ReplaceFileError::StateUnknown)
    }

    /// Flush this retained directory capability.
    pub fn sync(&self) -> io::Result<()> {
        self.revalidate_named()?;
        #[cfg(windows)]
        {
            let directory = stable_open_directory_for_sync(&self.path)?;
            if file_identity(&directory)? != self.identity {
                return Err(io::Error::other(
                    "stable directory identity changed before sync",
                ));
            }
            directory.observed_sync_all()?;
            self.revalidate_named()
        }
        #[cfg(not(windows))]
        {
            self.file.observed_sync_all()?;
            self.revalidate_named()
        }
    }

    /// Return the retained native identity.
    #[must_use]
    pub fn identity(&self) -> FileIdentity {
        self.identity
    }
}

/// Open a directory handle using the platform's no-follow and sharing policy.
/// The caller must validate directory kind and retained/named identity before
/// treating it as authority; prefer `StableDirectory::open` for a capability.
pub fn open_directory_handle(path: &Path) -> io::Result<OpenedDirectoryHandle> {
    stable_open_directory(path).map(|file| OpenedDirectoryHandle { file })
}

fn validate_child_name(name: &OsStr) -> io::Result<()> {
    let path = Path::new(name);
    if name.is_empty()
        || path.is_absolute()
        || path.components().count() != 1
        || matches!(name.to_str(), Some("." | ".."))
    {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "invalid child name",
        ));
    }
    Ok(())
}

fn validate_stable_child_file(file: &File, path: &Path) -> io::Result<()> {
    let metadata = file.metadata()?;
    let named = std::fs::symlink_metadata(path)?;
    if !metadata.is_file()
        || !named.is_file()
        || is_link_or_reparse(&named)
        || file_identity(file)? != path_identity(path)?
    {
        return Err(io::Error::other(
            "stable child is linked, special, or substituted",
        ));
    }
    Ok(())
}

/// Native Windows volume facts needed by the durability admission policy.
#[cfg(windows)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WindowsVolumeInformation {
    /// Filesystem name reported by the mounted volume (`NTFS`, `ReFS`, ...).
    pub filesystem_name: String,
    /// Whether the volume reports the read-only filesystem flag.
    pub read_only: bool,
    /// Whether Windows classifies the volume root as a fixed local drive.
    pub fixed: bool,
}

/// Create a durability-probe directory that is private to the current user.
///
/// Unix uses mode `0700`. Windows installs a protected DACL that grants full
/// access only to the owner, LocalSystem, and local administrators.
pub fn create_private_directory(path: &Path) -> io::Result<()> {
    create_private_directory_platform(path)
}

/// Return the stable native volume/file identity of an open handle.
pub fn file_identity(file: &File) -> io::Result<FileIdentity> {
    file_identity_platform(file)
}

/// Return logical and physically allocated bytes for a retained regular-file handle.
///
/// The descriptor is the sole authority: this function never resolves or reopens a
/// pathname. Unsupported platforms and native values that cannot be represented
/// safely fail closed.
pub fn file_space_usage(file: &File) -> io::Result<FileSpaceUsage> {
    file_space_usage_platform(file)
}

/// Return the stable native volume/file identity of a non-followed path.
pub fn path_identity(path: &Path) -> io::Result<FileIdentity> {
    path_identity_platform(path)
}

/// Return the native hard-link count of an open file handle.
pub fn file_link_count(file: &File) -> io::Result<u64> {
    file_link_count_platform(file)
}

/// Return the native hard-link count of a non-followed path.
pub fn path_link_count(path: &Path) -> io::Result<u64> {
    path_link_count_platform(path)
}

/// Query Windows volume facts from the native mount root containing `path`.
///
/// This accepts canonical extended-length paths such as `\\?\C:\...` and
/// follows mount-point boundaries through `GetVolumePathNameW`.
#[cfg(windows)]
pub fn windows_volume_information(path: &Path) -> io::Result<WindowsVolumeInformation> {
    windows::volume_information(path)
}

/// Failure classification for an attempted atomic replacement.
#[derive(Debug)]
pub enum ReplaceFileError {
    /// The operating system rejected the operation and the open source handle
    /// plus both named identities were verified unchanged.
    NotReplaced(io::Error),
    /// The operating system reported failure after it may have moved or
    /// modified one of the named files. The caller must reconcile from
    /// authoritative persisted state.
    StateUnknown(io::Error),
}

impl std::fmt::Display for ReplaceFileError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NotReplaced(error) => write!(formatter, "file was not replaced: {error}"),
            Self::StateUnknown(error) => {
                write!(
                    formatter,
                    "replacement state requires reconciliation: {error}"
                )
            }
        }
    }
}

impl std::error::Error for ReplaceFileError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(match self {
            Self::NotReplaced(error) | Self::StateUnknown(error) => error,
        })
    }
}

/// Classify an OS-reported failed replacement from reconciled identities.
///
/// This is public for the deterministic fault oracle; publication callers use
/// [`replace_file`] directly.
#[doc(hidden)]
#[must_use]
pub fn classify_failed_replacement(
    error: io::Error,
    source_before: FileIdentity,
    target_before: FileIdentity,
    source_after: Option<FileIdentity>,
    target_after: Option<FileIdentity>,
) -> ReplaceFileError {
    if source_after == Some(source_before) && target_after == Some(target_before) {
        ReplaceFileError::NotReplaced(error)
    } else {
        ReplaceFileError::StateUnknown(error)
    }
}

/// Atomically replace an existing regular file with another regular file in
/// the same directory.
///
/// Source contents must already be written. On Windows the implementation
/// reopens and flushes the source through a write-through handle before issuing
/// the NTFS namespace rename through that same handle. On POSIX the caller
/// remains responsible for the containing-directory durability barrier.
pub fn replace_file(
    directory: &File,
    source_name: &OsStr,
    target_name: &OsStr,
) -> Result<(), ReplaceFileError> {
    verify_single_component(source_name).map_err(ReplaceFileError::NotReplaced)?;
    verify_single_component(target_name).map_err(ReplaceFileError::NotReplaced)?;
    replace_file_platform(directory, source_name, target_name, None, None)
}

/// Atomically install a new regular file without replacing an existing entry.
///
/// Windows uses the same flushed write-through source handle for the NTFS
/// namespace rename. POSIX callers remain responsible for directory `fsync`.
pub fn install_new_file(
    directory: &File,
    source_name: &OsStr,
    target_name: &OsStr,
) -> io::Result<()> {
    verify_single_component(source_name)?;
    verify_single_component(target_name)?;
    install_new_file_platform(directory, source_name, target_name, None)
}

/// Atomically move a file or directory without replacing any existing destination.
///
/// This never copies across volumes. The caller owns source admission and the
/// containing-directory durability barrier after a successful namespace change.
pub fn rename_no_replace(source: &Path, destination: &Path) -> io::Result<()> {
    rename_no_replace_platform(source, destination)
}

fn verify_single_component(name: &OsStr) -> io::Result<()> {
    let mut components = Path::new(name).components();
    if !matches!(components.next(), Some(std::path::Component::Normal(_)))
        || components.next().is_some()
    {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "filesystem operation requires one plain name",
        ));
    }
    Ok(())
}

fn verify_regular_metadata(metadata: &std::fs::Metadata) -> io::Result<()> {
    if is_link_or_reparse(metadata) || !metadata.is_file() || link_count(metadata) != 1 {
        return Err(io::Error::other(
            "replacement path is not a regular non-link file",
        ));
    }
    Ok(())
}

fn verify_space_usage_metadata(metadata: &std::fs::Metadata) -> io::Result<()> {
    if is_link_or_reparse(metadata) || !metadata.is_file() {
        return Err(io::Error::other(
            "space usage handle is not a regular non-reparse file",
        ));
    }
    Ok(())
}

#[cfg(test)]
mod tests;

/// Optional, process-wide diagnostic work counters.
pub mod observation;
pub use observation::ObservedSync;