fsys 1.1.0

Filesystem IO for Rust storage engines: journal substrate, io_uring, NVMe passthrough, atomic writes, cross-platform 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
//! Error type for the `fsys` crate.
//!
//! All fallible operations in `fsys` return [`Result<T>`], which is a type
//! alias for [`std::result::Result<T, Error>`]. The [`Error`] enum is the
//! single error type produced by the library; consumers match on its
//! variants rather than juggling boxed trait objects.
//!
//! Error codes use the prefix `FS-` per the wider Hive error registry.
//! Codes are stable once assigned: the integer associated with each variant
//! is part of the public contract and will not change between versions.

use std::fmt;
use std::path::PathBuf;

/// Convenient `Result` alias that fixes the error type to [`Error`].
///
/// # Examples
///
/// ```
/// use fsys::Result;
///
/// fn always_ok() -> Result<u32> {
///     Ok(42)
/// }
///
/// assert_eq!(always_ok().ok(), Some(42));
/// ```
pub type Result<T> = std::result::Result<T, Error>;

/// The single error type produced by the `fsys` crate.
///
/// Every variant carries enough context to identify what was attempted,
/// where it failed, and what the caller can do next. Display output never
/// includes raw buffer contents; file paths are considered safe to surface
/// because callers already supplied them.
///
/// The enum is `#[non_exhaustive]` so the library can add new variants in
/// patch releases without breaking external `match` arms (callers must
/// include a `_` fallback). Error codes (`FS-XXXXX`) are assigned per
/// variant and are part of the public contract — they do not change once
/// assigned. Match on [`Error::code`] for log-grep-stable string contracts
/// rather than on the Display format, which may be refined for clarity.
#[derive(Debug)]
#[non_exhaustive]
#[must_use = "errors should be inspected, propagated, or logged"]
pub enum Error {
    /// A platform IO syscall returned an error.
    ///
    /// Wraps the underlying [`std::io::Error`]. Callers needing the
    /// original `io::ErrorKind` can pattern-match the inner value.
    ///
    /// **Code:** `FS-00001`. Caller action: inspect the inner kind; this
    /// is typically a transient condition such as `Interrupted` or a
    /// configuration problem such as `PermissionDenied`.
    Io(std::io::Error),

    /// A supplied path could not be used.
    ///
    /// **Code:** `FS-00002`. Caller action: correct the path. Common
    /// causes include empty segments, embedded NUL bytes, or characters
    /// disallowed on the active platform.
    InvalidPath {
        /// The offending path, as supplied by the caller.
        path: PathBuf,
        /// Human-readable explanation of why the path was rejected.
        reason: String,
    },

    /// A hardware probe failed.
    ///
    /// **Code:** `FS-00003`. Caller action: treat as advisory. The crate
    /// continues to operate with conservative defaults (queue depth 1,
    /// drive kind unknown). The 0.9.2+ accessor
    /// [`Handle::is_plp_protected`](crate::Handle::is_plp_protected) /
    /// [`plp_status`](crate::Handle::plp_status) reports
    /// `PlpStatus::Unknown` rather than panicking when probes fail; only
    /// call sites that REQUIRE real hardware information (e.g. databases
    /// deciding whether to skip per-commit fsync on confirmed PLP) should
    /// treat this as fatal.
    HardwareProbeFailed {
        /// Detail string describing which probe failed and why.
        detail: String,
    },

    /// The requested feature is not available on the active platform.
    ///
    /// **Code:** `FS-00004`. Caller action: select an alternative
    /// strategy, fall back to a portable path, or recompile with the
    /// appropriate feature flag.
    UnsupportedPlatform {
        /// Detail string describing what was requested and why this
        /// platform cannot serve it.
        detail: String,
    },

    /// The requested durability method is reserved and cannot be selected.
    ///
    /// **Code:** `FS-00005`. Caller action: select an available method
    /// ([`crate::Method::Sync`], [`crate::Method::Data`],
    /// [`crate::Method::Mmap`], [`crate::Method::Direct`], or
    /// [`crate::Method::Auto`]). [`crate::Method::Journal`] is the only
    /// reserved variant; for append-only / WAL workloads, use the
    /// [`JournalHandle`](crate::JournalHandle) substrate (independent of
    /// the `Method` enum) rather than waiting on `Method::Journal` to
    /// ship.
    UnsupportedMethod {
        /// The name of the method that was requested.
        method: &'static str,
    },

    /// A Direct IO operation could not satisfy its alignment requirements.
    ///
    /// **Code:** `FS-00006`. Caller action: this is an internal alignment
    /// failure. File a bug if you encounter this — fsys is responsible for
    /// managing alignment transparently on behalf of the caller.
    AlignmentRequired {
        /// Human-readable description of the violated requirement.
        detail: &'static str,
    },

    /// The atomic write-replace sequence failed part-way through.
    ///
    /// **Code:** `FS-00007`. Caller action: inspect `step` to determine
    /// how far the operation progressed. If `step` is `"write"` or
    /// earlier, the original file is unmodified. If `step` is `"rename"`,
    /// the original file may or may not have been replaced. A stale temp
    /// file may remain adjacent to the destination; it is safe to delete.
    AtomicReplaceFailed {
        /// The step that failed (e.g. `"open"`, `"write"`, `"flush"`,
        /// `"rename"`, `"sync_parent"`).
        step: &'static str,
        /// The underlying IO error from the failed step.
        source: std::io::Error,
    },

    /// A directory creation or removal operation failed part-way through.
    ///
    /// **Code:** `FS-00008`. Caller action: the filesystem is in a
    /// partially modified state. Inspect `failed_step` to identify which
    /// sub-operation triggered the error, and `completed_steps` to know
    /// what succeeded before the failure. No rollback is performed; the
    /// caller decides whether to retry, clean up, or accept the partial
    /// state.
    PartialDirectoryOp {
        /// The operation that failed (e.g. `"create /a/b/c"`).
        failed_step: String,
        /// Operations that succeeded before the failure.
        completed_steps: Vec<String>,
    },

    /// A batch operation was submitted to a [`crate::Handle`] that is
    /// being dropped.
    ///
    /// **Code:** `FS-00009`. Caller action: the handle is shutting down;
    /// rebuild a new handle if more IO is needed. This error is only
    /// produced when a batch submit races with `Handle::drop` — it is
    /// effectively unreachable when handle ownership is single-threaded
    /// or properly fenced.
    ShutdownInProgress,

    /// The group-lane queue is full and a non-blocking submission was
    /// rejected.
    ///
    /// **Code:** `FS-00010`. **Reserved variant — never emitted as of
    /// the current release.** The default backpressure mode is blocking
    /// submission (callers wait when the queue is full); this variant
    /// is reserved for a future opt-in error-mode (e.g.
    /// `Builder::backpressure(BackpressureMode::Error)`) that has not
    /// landed yet. Match it via the enum's `_` fallback arm (the enum
    /// is `#[non_exhaustive]`) — it cannot occur today.
    QueueFull,

    /// `io_uring_setup(2)` failed when constructing a per-handle ring.
    ///
    /// **Code:** `FS-00011`. Caller action: the Linux Direct path's
    /// io_uring branch is unavailable for this handle; fsys silently
    /// falls back to the `O_DIRECT` + `pwrite` + `fdatasync` path
    /// (locked decision #1 in `.dev/DECISIONS-0.5.0.md`). The fallback
    /// is observable via [`crate::Handle::active_method`]. This variant
    /// surfaces only when a caller explicitly requests ring diagnostics
    /// — normal handle creation does not return it. Common causes:
    /// kernel < 5.1, `io_uring_setup` disabled by a security profile
    /// (SECCOMP, AppArmor), container runtime restrictions.
    IoUringSetupFailed {
        /// Underlying `io::Error` returned by the failing `io_uring_setup`
        /// (or equivalent) syscall.
        source: std::io::Error,
    },

    /// A memory-mapped IO operation failed.
    ///
    /// **Code:** `FS-00012`. Caller action: when emitted from
    /// [`crate::Method::Mmap`] write/read paths, fsys has already
    /// attempted the documented fallback to [`crate::Method::Sync`].
    /// This variant surfaces only when fallback also fails — typically
    /// because the underlying file is on a filesystem that rejects both
    /// `mmap` and standard `write` (rare; usually a pseudo-filesystem
    /// like `procfs`).
    MmapFailed {
        /// Human-readable explanation of what failed (mapping creation,
        /// `msync`, page-size alignment, etc.).
        reason: String,
    },

    /// The per-handle aligned buffer pool is exhausted and a
    /// non-blocking lease was rejected.
    ///
    /// **Code:** `FS-00013`. **Reserved variant — never emitted in
    /// `0.5.0`.** Default lease semantics block until a buffer is
    /// returned to the pool (mirrors the bounded-queue blocking-submit
    /// contract from `0.4.0` decision #4). This variant is reserved
    /// for a future opt-in error-mode (e.g.
    /// `Builder::buffer_pool_mode(BufferPoolMode::Error)`). Match it
    /// to satisfy exhaustiveness even though it cannot occur today.
    BufferPoolExhausted,

    /// A PLP (Power Loss Protection) probe failed or is unavailable on
    /// this platform.
    ///
    /// **Code:** `FS-00014`. **Informational variant — `0.5.0`'s
    /// public API does not return it.** Per locked decision #3, PLP
    /// probe failures degrade [`crate::hardware::DriveInfo::plp`] to
    /// `Unknown` and log via the metrics placeholder; they do not fail
    /// handle creation. The variant exists in the enum so a future
    /// `probe_plp() -> Result<bool>` API can surface the underlying
    /// reason on request (out of scope for `0.5.0` per follow-up F-8
    /// in `.dev/DECISIONS-0.5.0.md`).
    PlpDetectionUnavailable {
        /// Human-readable explanation: missing capability, unsupported
        /// platform, IOCTL failure, etc.
        detail: String,
    },

    /// NVMe passthrough flush is not supported on the current platform.
    ///
    /// **Code:** `FS-00015`. Caller action: select an alternative
    /// method or accept the platform's standard durability primitive.
    /// macOS does not expose NVMe passthrough; this variant is the
    /// honest fail-fast for callers explicitly requesting
    /// `Method::Direct` with passthrough on macOS. On Linux and
    /// Windows, missing kernel support (Linux < 5.19) or unsupported
    /// hardware also surfaces here.
    NvmePassthroughUnsupported {
        /// Human-readable explanation: which platform, which kernel,
        /// which hardware constraint.
        detail: String,
    },

    /// NVMe passthrough is supported on this platform but the calling
    /// process lacks the privilege to issue raw NVMe commands.
    ///
    /// **Code:** `FS-00016`. Caller action: this is recoverable. The
    /// `Method::Direct` backend silently falls back to the standard
    /// durability primitive (`fdatasync` on Linux,
    /// `FILE_FLAG_WRITE_THROUGH` on Windows) when capability detection
    /// returns this error during the first Direct op. Callers
    /// observing this variant directly are typically diagnostic tools
    /// (`probe_nvme_passthrough() -> Result<bool>`, deferred to
    /// `0.7.0+` per follow-up F-9) that want to know **why** the
    /// fallback happened.
    NvmePassthroughDenied {
        /// Human-readable explanation: which capability check failed,
        /// which permission was missing, which OS error code surfaced.
        detail: String,
    },

    /// An async method was called outside an active tokio runtime.
    ///
    /// **Code:** `FS-00017`. Caller action: ensure the call site is
    /// inside a `#[tokio::main]` function, a `#[tokio::test]`, or
    /// otherwise within a tokio runtime context. fsys's async layer
    /// uses `tokio::task::spawn_blocking` internally and requires a
    /// runtime to drive the spawned task. This error is returned
    /// instead of panicking on `Handle::current()` failure, so callers
    /// observe a graceful, propagable error rather than a process
    /// crash.
    ///
    /// Only emitted when the `async` Cargo feature is enabled.
    AsyncRuntimeRequired,

    /// A glob pattern supplied to [`crate::Handle::find`] could not be
    /// parsed.
    ///
    /// **Code:** `FS-00018`. Caller action: correct the pattern. The
    /// accepted syntax is the `glob` crate's standard:
    /// `*` (any chars except `/`), `**` (any chars including `/`),
    /// `?` (one char), `[abc]` / `[!abc]` (character class),
    /// `{foo,bar}` (alternation). Patterns that escape the base
    /// directory (e.g. `../../etc/passwd`) are rejected with
    /// [`Error::InvalidPath`] instead — this variant covers only
    /// pattern-syntax errors.
    GlobPatternInvalid {
        /// Human-readable explanation of the syntax error.
        reason: String,
    },

    /// A handle's native io_uring async substrate has been poisoned —
    /// typically because the per-handle completion driver task panicked.
    ///
    /// **Code:** `FS-00019`. Caller action: subsequent async
    /// operations on this handle are rejected with this error. The
    /// handle's **sync** operations continue to work normally — only
    /// the native async substrate is poisoned. Construct a fresh
    /// handle for further async work, or set
    /// `FSYS_DISABLE_NATIVE_ASYNC=1` and rely on the
    /// [`spawn_blocking`](https://docs.rs/tokio/latest/tokio/task/fn.spawn_blocking.html)
    /// fallback. Diagnostic detail (e.g. the panic message) is in
    /// `reason`. Only emitted when the `async` Cargo feature is
    /// enabled and the platform is Linux.
    HandlePoisoned {
        /// Human-readable explanation of why the substrate is poisoned.
        reason: String,
    },

    /// An io_uring submission failed at the kernel boundary.
    ///
    /// **Code:** `FS-00020`. Caller action: this is a syscall-level
    /// failure (kernel rejected the submission queue entry — invalid
    /// fd, alignment violation, ring exhaustion that backpressure
    /// failed to absorb). Inspect `errno` to distinguish recoverable
    /// (`EAGAIN`, `EINTR`) from non-recoverable (`EINVAL`, `EBADF`)
    /// causes. Only emitted on Linux when the native async substrate
    /// is active.
    IoUringSubmitFailed {
        /// Raw `errno` from the failing submit. `0` when the failure
        /// was internal (e.g. SQE allocation rejected by our
        /// backpressure wrapper).
        errno: i32,
    },

    /// The per-handle completion driver task is no longer alive,
    /// but the substrate has not yet been marked
    /// [`HandlePoisoned`](Error::HandlePoisoned).
    ///
    /// **Code:** `FS-00021`. Caller action: this is a transient
    /// state observed when an async op submits *during* handle
    /// shutdown — the driver has exited but the handle hasn't
    /// fully drained yet. Treat it as `HandlePoisoned` for
    /// recovery purposes. Construct a fresh handle.
    CompletionDriverDead,

    /// A Cargo feature required to satisfy the request is not
    /// enabled at compile time.
    ///
    /// **Code:** `FS-00022`. Caller action: rebuild the crate with
    /// the named feature flag, or select an alternative method /
    /// backend that does not require it. Most commonly emitted when
    /// the caller selects [`crate::Method::Spdk`] without the
    /// `spdk` feature compiled in (the SPDK backend lives in the
    /// companion `fsys-spdk` crate, which is pulled in by the
    /// feature flag — code paths that name `Method::Spdk` compile
    /// with the feature off, but selecting that method at runtime
    /// is rejected here rather than silently falling through to a
    /// different backend).
    FeatureNotEnabled {
        /// The name of the required Cargo feature (e.g. `"spdk"`).
        feature: &'static str,
    },

    /// The SPDK kernel-bypass backend was requested but the system
    /// is not currently configured to host it.
    ///
    /// **Code:** `FS-00023`. Caller action: inspect `reason` to
    /// identify which precondition failed (Linux only, hugepages
    /// configured, `CAP_SYS_ADMIN` or `uid 0`, NVMe devices present
    /// and not kernel-bound, IOMMU groups present, sufficient
    /// cores). Fix the missing precondition (typically a sysadmin-
    /// level operation — allocate hugepages, rebind an NVMe device
    /// to `vfio-pci` / `uio_pci_generic`, enable IOMMU in the
    /// kernel command line), or fall back to a kernel-path method.
    /// The capability probe runs at startup and caches its result
    /// to disk; setting `FSYS_REPROBE=1` forces a re-probe on the
    /// next process start after configuration changes.
    SpdkUnavailable {
        /// Which precondition failed.
        reason: crate::capability::SpdkSkipReason,
    },
}

impl Error {
    /// Returns the stable `FS-XXXXX` code identifying this variant.
    ///
    /// Codes are stable across releases. They never change for an
    /// existing variant; new variants receive new codes.
    ///
    /// # Examples
    ///
    /// ```
    /// use fsys::Error;
    /// use std::io;
    ///
    /// let err = Error::Io(io::Error::from(io::ErrorKind::NotFound));
    /// assert_eq!(err.code(), "FS-00001");
    /// ```
    #[must_use]
    pub fn code(&self) -> &'static str {
        match self {
            Error::Io(_) => "FS-00001",
            Error::InvalidPath { .. } => "FS-00002",
            Error::HardwareProbeFailed { .. } => "FS-00003",
            Error::UnsupportedPlatform { .. } => "FS-00004",
            Error::UnsupportedMethod { .. } => "FS-00005",
            Error::AlignmentRequired { .. } => "FS-00006",
            Error::AtomicReplaceFailed { .. } => "FS-00007",
            Error::PartialDirectoryOp { .. } => "FS-00008",
            Error::ShutdownInProgress => "FS-00009",
            Error::QueueFull => "FS-00010",
            Error::IoUringSetupFailed { .. } => "FS-00011",
            Error::MmapFailed { .. } => "FS-00012",
            Error::BufferPoolExhausted => "FS-00013",
            Error::PlpDetectionUnavailable { .. } => "FS-00014",
            Error::NvmePassthroughUnsupported { .. } => "FS-00015",
            Error::NvmePassthroughDenied { .. } => "FS-00016",
            Error::AsyncRuntimeRequired => "FS-00017",
            Error::GlobPatternInvalid { .. } => "FS-00018",
            Error::HandlePoisoned { .. } => "FS-00019",
            Error::IoUringSubmitFailed { .. } => "FS-00020",
            Error::CompletionDriverDead => "FS-00021",
            Error::FeatureNotEnabled { .. } => "FS-00022",
            Error::SpdkUnavailable { .. } => "FS-00023",
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::Io(e) => write!(f, "[{}] io error: {}", self.code(), e),
            Error::InvalidPath { path, reason } => write!(
                f,
                "[{}] invalid path {:?}: {}",
                self.code(),
                path.display(),
                reason
            ),
            Error::HardwareProbeFailed { detail } => {
                write!(f, "[{}] hardware probe failed: {}", self.code(), detail)
            }
            Error::UnsupportedPlatform { detail } => {
                write!(f, "[{}] unsupported platform: {}", self.code(), detail)
            }
            Error::UnsupportedMethod { method } => {
                write!(
                    f,
                    "[{}] method '{}' is not implemented in this release",
                    self.code(),
                    method
                )
            }
            Error::AlignmentRequired { detail } => {
                write!(
                    f,
                    "[{}] alignment requirement failed: {}",
                    self.code(),
                    detail
                )
            }
            Error::AtomicReplaceFailed { step, source } => {
                write!(
                    f,
                    "[{}] atomic write-replace failed at step '{}': {}",
                    self.code(),
                    step,
                    source
                )
            }
            Error::PartialDirectoryOp {
                failed_step,
                completed_steps,
            } => {
                write!(
                    f,
                    "[{}] directory op failed at '{}' after {} completed step(s)",
                    self.code(),
                    failed_step,
                    completed_steps.len()
                )
            }
            Error::ShutdownInProgress => {
                write!(
                    f,
                    "[{}] handle is shutting down; batch submission rejected",
                    self.code()
                )
            }
            Error::QueueFull => {
                write!(
                    f,
                    "[{}] group-lane queue is full (reserved variant; never emitted in 0.4.0)",
                    self.code()
                )
            }
            Error::IoUringSetupFailed { source } => {
                write!(f, "[{}] io_uring_setup failed: {}", self.code(), source)
            }
            Error::MmapFailed { reason } => {
                write!(f, "[{}] mmap operation failed: {}", self.code(), reason)
            }
            Error::BufferPoolExhausted => {
                write!(
                    f,
                    "[{}] aligned buffer pool exhausted (reserved variant; never emitted in 0.5.0)",
                    self.code()
                )
            }
            Error::PlpDetectionUnavailable { detail } => {
                write!(f, "[{}] PLP detection unavailable: {}", self.code(), detail)
            }
            Error::NvmePassthroughUnsupported { detail } => {
                write!(
                    f,
                    "[{}] NVMe passthrough unsupported: {}",
                    self.code(),
                    detail
                )
            }
            Error::NvmePassthroughDenied { detail } => {
                write!(f, "[{}] NVMe passthrough denied: {}", self.code(), detail)
            }
            Error::AsyncRuntimeRequired => {
                write!(
                    f,
                    "[{}] async method called outside an active tokio runtime",
                    self.code()
                )
            }
            Error::GlobPatternInvalid { reason } => {
                write!(f, "[{}] invalid glob pattern: {}", self.code(), reason)
            }
            Error::HandlePoisoned { reason } => {
                write!(f, "[{}] async substrate poisoned: {}", self.code(), reason)
            }
            Error::IoUringSubmitFailed { errno } => {
                write!(
                    f,
                    "[{}] io_uring submit failed (errno {})",
                    self.code(),
                    errno
                )
            }
            Error::CompletionDriverDead => {
                write!(
                    f,
                    "[{}] io_uring completion driver task is no longer running",
                    self.code()
                )
            }
            Error::FeatureNotEnabled { feature } => {
                write!(
                    f,
                    "[{}] required Cargo feature '{}' is not enabled in this build",
                    self.code(),
                    feature
                )
            }
            Error::SpdkUnavailable { reason } => {
                write!(f, "[{}] SPDK backend unavailable: {}", self.code(), reason)
            }
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Error::Io(e) => Some(e),
            Error::AtomicReplaceFailed { source, .. } => Some(source),
            Error::IoUringSetupFailed { source } => Some(source),
            Error::InvalidPath { .. }
            | Error::HardwareProbeFailed { .. }
            | Error::UnsupportedPlatform { .. }
            | Error::UnsupportedMethod { .. }
            | Error::AlignmentRequired { .. }
            | Error::PartialDirectoryOp { .. }
            | Error::ShutdownInProgress
            | Error::QueueFull
            | Error::MmapFailed { .. }
            | Error::BufferPoolExhausted
            | Error::PlpDetectionUnavailable { .. }
            | Error::NvmePassthroughUnsupported { .. }
            | Error::NvmePassthroughDenied { .. }
            | Error::AsyncRuntimeRequired
            | Error::GlobPatternInvalid { .. }
            | Error::HandlePoisoned { .. }
            | Error::IoUringSubmitFailed { .. }
            | Error::CompletionDriverDead
            | Error::FeatureNotEnabled { .. }
            | Error::SpdkUnavailable { .. } => None,
        }
    }
}

impl From<std::io::Error> for Error {
    fn from(value: std::io::Error) -> Self {
        Error::Io(value)
    }
}

// ──────────────────────────────────────────────────────────────────────────────
// BatchError
// ──────────────────────────────────────────────────────────────────────────────

/// The error type returned by batch operations
/// (`Handle::write_batch`, `Handle::delete_batch`, `Handle::copy_batch`,
/// and `Batch::commit`).
///
/// `BatchError` reports per-batch failure semantics under decision #5
/// of the `0.4.0` design (independent ops, not transactions). When a
/// batch op fails — whether by returning an `Err` or by panicking — the
/// dispatcher stops processing the current batch, sends the response,
/// and moves on to the next batch in the queue. Subsequent ops in the
/// failing batch are **not attempted**. Ops that succeeded before the
/// failure **are** durable; fsys does **not** roll them back.
///
/// To recover from a `BatchError`, inspect:
/// - [`failed_at`](BatchError::failed_at): the index of the op that
///   failed.
/// - [`completed`](BatchError::completed): the number of ops that
///   completed successfully *before* the failure (always equal to
///   `failed_at()` in `0.4.0`; the accessor is preserved as a
///   structural guarantee for future phases that might allow
///   continuation).
/// - [`inner`](BatchError::inner) / [`into_inner`](BatchError::into_inner):
///   the underlying [`Error`] that describes the failure.
///
/// Callers needing all-or-nothing semantics must layer their own
/// transactional logic on top of fsys, or wait for `Method::Journal`
/// in `0.7.0`.
#[derive(Debug)]
#[non_exhaustive]
#[must_use = "errors should be inspected, propagated, or logged"]
pub struct BatchError {
    /// 0.9.6 — fields are `pub(crate)`, not `pub`. The audit (H-4)
    /// flagged the prior `pub` fields as a 1.0 lock-in concern:
    /// downstream callers reading `err.failed_at` directly froze
    /// the struct's internal representation. Use the accessor
    /// methods [`Self::failed_at`], [`Self::completed`], and
    /// [`Self::inner`] / [`Self::into_inner`] instead — they
    /// remain stable across any future internal refactor.
    pub(crate) failed_at: usize,
    pub(crate) completed: usize,
    /// The underlying error.
    ///
    /// Boxed because `Error` is `non_exhaustive` and may grow large; the
    /// box keeps `BatchError` itself small even when the inner error
    /// carries large payloads (e.g. paths, detail strings, captured
    /// `std::io::Error`s).
    pub(crate) source: Box<Error>,
}

impl BatchError {
    /// Returns the zero-based index of the op that failed within
    /// its batch. `0` means the first op failed; on a 100-op batch
    /// where op 73 failed, this returns `73`.
    #[must_use]
    #[inline]
    pub fn failed_at(&self) -> usize {
        self.failed_at
    }

    /// Returns the number of ops that completed successfully before
    /// the failure. Always `<= failed_at()`; equal when the prior
    /// ops were all committed at the time of the failure.
    #[must_use]
    #[inline]
    pub fn completed(&self) -> usize {
        self.completed
    }

    /// Returns the inner [`Error`] as a borrowed reference.
    pub fn inner(&self) -> &Error {
        &self.source
    }

    /// Consumes this `BatchError` and returns the boxed inner [`Error`].
    pub fn into_inner(self) -> Box<Error> {
        self.source
    }
}

impl fmt::Display for BatchError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "batch failed at op {} after {} successful op(s): {}",
            self.failed_at, self.completed, self.source
        )
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use std::io;

    #[test]
    fn test_error_code_io_returns_fs00001() {
        let err = Error::Io(io::Error::from(io::ErrorKind::NotFound));
        assert_eq!(err.code(), "FS-00001");
    }

    #[test]
    fn test_error_code_invalid_path_returns_fs00002() {
        let err = Error::InvalidPath {
            path: PathBuf::from("bad"),
            reason: "empty segment".into(),
        };
        assert_eq!(err.code(), "FS-00002");
    }

    #[test]
    fn test_error_code_hardware_probe_returns_fs00003() {
        let err = Error::HardwareProbeFailed {
            detail: "nvme ioctl unavailable".into(),
        };
        assert_eq!(err.code(), "FS-00003");
    }

    #[test]
    fn test_error_code_unsupported_platform_returns_fs00004() {
        let err = Error::UnsupportedPlatform {
            detail: "io_uring requires Linux 5.1+".into(),
        };
        assert_eq!(err.code(), "FS-00004");
    }

    #[test]
    fn test_error_display_unsupported_platform_includes_detail() {
        let err = Error::UnsupportedPlatform {
            detail: "io_uring not available".into(),
        };
        let s = err.to_string();
        assert!(s.starts_with("[FS-00004]"));
        assert!(s.contains("io_uring not available"));
    }

    #[test]
    fn test_error_display_io_includes_code_and_kind() {
        let err = Error::Io(io::Error::from(io::ErrorKind::NotFound));
        let s = err.to_string();
        assert!(s.starts_with("[FS-00001]"));
        assert!(s.contains("io error"));
    }

    #[test]
    fn test_error_display_invalid_path_does_not_panic_on_unicode() {
        let err = Error::InvalidPath {
            path: PathBuf::from("名前/test"),
            reason: "rejected".into(),
        };
        let s = err.to_string();
        assert!(s.contains("FS-00002"));
    }

    #[test]
    fn test_error_source_io_returns_inner() {
        let inner = io::Error::from(io::ErrorKind::PermissionDenied);
        let err = Error::Io(inner);
        assert!(std::error::Error::source(&err).is_some());
    }

    #[test]
    fn test_error_source_invalid_path_returns_none() {
        let err = Error::InvalidPath {
            path: PathBuf::from("x"),
            reason: "y".into(),
        };
        assert!(std::error::Error::source(&err).is_none());
    }

    #[test]
    fn test_error_from_io_error_converts() {
        let io_err = io::Error::from(io::ErrorKind::Other);
        let err: Error = io_err.into();
        assert_eq!(err.code(), "FS-00001");
    }

    #[test]
    fn test_result_alias_compiles_for_ok_and_err_paths() {
        fn returns_ok() -> Result<u8> {
            Ok(1)
        }
        fn returns_err() -> Result<u8> {
            Err(Error::HardwareProbeFailed {
                detail: "test".into(),
            })
        }
        assert_eq!(returns_ok().ok(), Some(1));
        assert!(returns_err().is_err());
    }

    #[test]
    fn test_error_code_unsupported_method_returns_fs00005() {
        let err = Error::UnsupportedMethod { method: "Mmap" };
        assert_eq!(err.code(), "FS-00005");
    }

    #[test]
    fn test_error_display_unsupported_method_includes_name() {
        let err = Error::UnsupportedMethod { method: "Journal" };
        let s = err.to_string();
        assert!(s.starts_with("[FS-00005]"));
        assert!(s.contains("Journal"));
    }

    #[test]
    fn test_error_code_alignment_required_returns_fs00006() {
        let err = Error::AlignmentRequired {
            detail: "size not a multiple of sector size",
        };
        assert_eq!(err.code(), "FS-00006");
    }

    #[test]
    fn test_error_display_alignment_required_includes_detail() {
        let err = Error::AlignmentRequired {
            detail: "buffer not aligned to 4096",
        };
        let s = err.to_string();
        assert!(s.starts_with("[FS-00006]"));
        assert!(s.contains("4096"));
    }

    #[test]
    fn test_error_code_atomic_replace_failed_returns_fs00007() {
        let err = Error::AtomicReplaceFailed {
            step: "rename",
            source: io::Error::from(io::ErrorKind::PermissionDenied),
        };
        assert_eq!(err.code(), "FS-00007");
    }

    #[test]
    fn test_error_display_atomic_replace_includes_step() {
        let err = Error::AtomicReplaceFailed {
            step: "flush",
            source: io::Error::from(io::ErrorKind::Other),
        };
        let s = err.to_string();
        assert!(s.starts_with("[FS-00007]"));
        assert!(s.contains("flush"));
    }

    #[test]
    fn test_error_source_atomic_replace_returns_inner() {
        let err = Error::AtomicReplaceFailed {
            step: "write",
            source: io::Error::from(io::ErrorKind::NotFound),
        };
        assert!(std::error::Error::source(&err).is_some());
    }

    #[test]
    fn test_error_code_partial_dir_op_returns_fs00008() {
        let err = Error::PartialDirectoryOp {
            failed_step: "create /a/b".into(),
            completed_steps: vec!["create /a".into()],
        };
        assert_eq!(err.code(), "FS-00008");
    }

    #[test]
    fn test_error_display_partial_dir_op_includes_step() {
        let err = Error::PartialDirectoryOp {
            failed_step: "create /a/b/c".into(),
            completed_steps: vec!["create /a".into(), "create /a/b".into()],
        };
        let s = err.to_string();
        assert!(s.starts_with("[FS-00008]"));
        assert!(s.contains("/a/b/c"));
    }

    #[test]
    fn test_error_source_partial_dir_op_returns_none() {
        let err = Error::PartialDirectoryOp {
            failed_step: "create /x".into(),
            completed_steps: vec![],
        };
        assert!(std::error::Error::source(&err).is_none());
    }

    // ── 0.4.0 additions ──────────────────────────────────────────────────

    #[test]
    fn test_error_code_shutdown_in_progress_returns_fs00009() {
        let err = Error::ShutdownInProgress;
        assert_eq!(err.code(), "FS-00009");
    }

    #[test]
    fn test_error_display_shutdown_in_progress_includes_code() {
        let err = Error::ShutdownInProgress;
        let s = err.to_string();
        assert!(s.starts_with("[FS-00009]"));
        assert!(s.contains("shutting down"));
    }

    #[test]
    fn test_error_source_shutdown_in_progress_returns_none() {
        let err = Error::ShutdownInProgress;
        assert!(std::error::Error::source(&err).is_none());
    }

    #[test]
    fn test_error_code_queue_full_returns_fs00010() {
        let err = Error::QueueFull;
        assert_eq!(err.code(), "FS-00010");
    }

    #[test]
    fn test_error_display_queue_full_marked_reserved() {
        let err = Error::QueueFull;
        let s = err.to_string();
        assert!(s.starts_with("[FS-00010]"));
        assert!(s.to_ascii_lowercase().contains("reserved"));
    }

    #[test]
    fn test_error_source_queue_full_returns_none() {
        let err = Error::QueueFull;
        assert!(std::error::Error::source(&err).is_none());
    }

    #[test]
    fn test_batch_error_fields_round_trip() {
        let inner = Error::Io(io::Error::from(io::ErrorKind::NotFound));
        let be = BatchError {
            failed_at: 3,
            completed: 3,
            source: Box::new(inner),
        };
        assert_eq!(be.failed_at, 3);
        assert_eq!(be.completed, 3);
        assert_eq!(be.inner().code(), "FS-00001");
    }

    #[test]
    fn test_batch_error_display_includes_indices_and_inner() {
        let inner = Error::HardwareProbeFailed {
            detail: "probe stub".into(),
        };
        let be = BatchError {
            failed_at: 7,
            completed: 7,
            source: Box::new(inner),
        };
        let s = be.to_string();
        assert!(s.contains("op 7"));
        assert!(s.contains("7 successful"));
        assert!(s.contains("FS-00003"));
    }

    #[test]
    fn test_batch_error_implements_std_error_with_inner_source() {
        let inner = Error::Io(io::Error::from(io::ErrorKind::PermissionDenied));
        let be = BatchError {
            failed_at: 0,
            completed: 0,
            source: Box::new(inner),
        };
        let dyn_err: &dyn std::error::Error = &be;
        assert!(dyn_err.source().is_some());
    }

    #[test]
    fn test_batch_error_into_inner_returns_boxed_error() {
        let inner = Error::ShutdownInProgress;
        let be = BatchError {
            failed_at: 0,
            completed: 0,
            source: Box::new(inner),
        };
        let unboxed: Box<Error> = be.into_inner();
        assert_eq!(unboxed.code(), "FS-00009");
    }

    // ── 0.5.0 additions ──────────────────────────────────────────────────

    #[test]
    fn test_error_code_io_uring_setup_failed_returns_fs00011() {
        let err = Error::IoUringSetupFailed {
            source: io::Error::from(io::ErrorKind::PermissionDenied),
        };
        assert_eq!(err.code(), "FS-00011");
    }

    #[test]
    fn test_error_display_io_uring_setup_failed_includes_source() {
        let err = Error::IoUringSetupFailed {
            source: io::Error::from(io::ErrorKind::PermissionDenied),
        };
        let s = err.to_string();
        assert!(s.starts_with("[FS-00011]"));
        assert!(s.contains("io_uring_setup"));
    }

    #[test]
    fn test_error_source_io_uring_setup_failed_returns_inner() {
        let err = Error::IoUringSetupFailed {
            source: io::Error::from(io::ErrorKind::PermissionDenied),
        };
        assert!(std::error::Error::source(&err).is_some());
    }

    #[test]
    fn test_error_code_mmap_failed_returns_fs00012() {
        let err = Error::MmapFailed {
            reason: "page-size alignment failed".into(),
        };
        assert_eq!(err.code(), "FS-00012");
    }

    #[test]
    fn test_error_display_mmap_failed_includes_reason() {
        let err = Error::MmapFailed {
            reason: "fallback to Sync also failed on procfs".into(),
        };
        let s = err.to_string();
        assert!(s.starts_with("[FS-00012]"));
        assert!(s.contains("procfs"));
    }

    #[test]
    fn test_error_source_mmap_failed_returns_none() {
        let err = Error::MmapFailed {
            reason: "test".into(),
        };
        assert!(std::error::Error::source(&err).is_none());
    }

    #[test]
    fn test_error_code_buffer_pool_exhausted_returns_fs00013() {
        let err = Error::BufferPoolExhausted;
        assert_eq!(err.code(), "FS-00013");
    }

    #[test]
    fn test_error_display_buffer_pool_exhausted_marked_reserved() {
        let err = Error::BufferPoolExhausted;
        let s = err.to_string();
        assert!(s.starts_with("[FS-00013]"));
        assert!(s.to_ascii_lowercase().contains("reserved"));
    }

    #[test]
    fn test_error_source_buffer_pool_exhausted_returns_none() {
        let err = Error::BufferPoolExhausted;
        assert!(std::error::Error::source(&err).is_none());
    }

    #[test]
    fn test_error_code_plp_detection_unavailable_returns_fs00014() {
        let err = Error::PlpDetectionUnavailable {
            detail: "CAP_SYS_ADMIN required".into(),
        };
        assert_eq!(err.code(), "FS-00014");
    }

    #[test]
    fn test_error_display_plp_detection_unavailable_includes_detail() {
        let err = Error::PlpDetectionUnavailable {
            detail: "IOKit property missing".into(),
        };
        let s = err.to_string();
        assert!(s.starts_with("[FS-00014]"));
        assert!(s.contains("IOKit property missing"));
    }

    #[test]
    fn test_error_source_plp_detection_unavailable_returns_none() {
        let err = Error::PlpDetectionUnavailable {
            detail: "test".into(),
        };
        assert!(std::error::Error::source(&err).is_none());
    }

    // ── 0.6.0 additions ──────────────────────────────────────────────────

    #[test]
    fn test_error_code_nvme_passthrough_unsupported_returns_fs00015() {
        let err = Error::NvmePassthroughUnsupported {
            detail: "macOS does not expose IOCTL_STORAGE_PROTOCOL_COMMAND".into(),
        };
        assert_eq!(err.code(), "FS-00015");
    }

    #[test]
    fn test_error_display_nvme_passthrough_unsupported_includes_detail() {
        let err = Error::NvmePassthroughUnsupported {
            detail: "kernel < 5.19".into(),
        };
        let s = err.to_string();
        assert!(s.starts_with("[FS-00015]"));
        assert!(s.contains("kernel < 5.19"));
    }

    #[test]
    fn test_error_source_nvme_passthrough_unsupported_returns_none() {
        let err = Error::NvmePassthroughUnsupported {
            detail: "test".into(),
        };
        assert!(std::error::Error::source(&err).is_none());
    }

    #[test]
    fn test_error_code_nvme_passthrough_denied_returns_fs00016() {
        let err = Error::NvmePassthroughDenied {
            detail: "EACCES on /dev/nvme0".into(),
        };
        assert_eq!(err.code(), "FS-00016");
    }

    #[test]
    fn test_error_display_nvme_passthrough_denied_includes_detail() {
        let err = Error::NvmePassthroughDenied {
            detail: "ERROR_ACCESS_DENIED on STORAGE_PROTOCOL_COMMAND".into(),
        };
        let s = err.to_string();
        assert!(s.starts_with("[FS-00016]"));
        assert!(s.contains("STORAGE_PROTOCOL_COMMAND"));
    }

    #[test]
    fn test_error_source_nvme_passthrough_denied_returns_none() {
        let err = Error::NvmePassthroughDenied {
            detail: "test".into(),
        };
        assert!(std::error::Error::source(&err).is_none());
    }

    #[test]
    fn test_error_code_async_runtime_required_returns_fs00017() {
        let err = Error::AsyncRuntimeRequired;
        assert_eq!(err.code(), "FS-00017");
    }

    #[test]
    fn test_error_display_async_runtime_required_mentions_tokio() {
        let err = Error::AsyncRuntimeRequired;
        let s = err.to_string();
        assert!(s.starts_with("[FS-00017]"));
        assert!(s.to_ascii_lowercase().contains("tokio"));
    }

    #[test]
    fn test_error_source_async_runtime_required_returns_none() {
        let err = Error::AsyncRuntimeRequired;
        assert!(std::error::Error::source(&err).is_none());
    }

    #[test]
    fn test_error_code_glob_pattern_invalid_returns_fs00018() {
        let err = Error::GlobPatternInvalid {
            reason: "unmatched bracket".into(),
        };
        assert_eq!(err.code(), "FS-00018");
    }

    #[test]
    fn test_error_display_glob_pattern_invalid_includes_reason() {
        let err = Error::GlobPatternInvalid {
            reason: "stray '['".into(),
        };
        let s = err.to_string();
        assert!(s.starts_with("[FS-00018]"));
        assert!(s.contains("stray"));
    }

    #[test]
    fn test_error_source_glob_pattern_invalid_returns_none() {
        let err = Error::GlobPatternInvalid {
            reason: "test".into(),
        };
        assert!(std::error::Error::source(&err).is_none());
    }

    // ── 0.7.0 additions ──────────────────────────────────────────────────

    #[test]
    fn test_error_code_handle_poisoned_returns_fs00019() {
        let err = Error::HandlePoisoned {
            reason: "completion driver panicked".into(),
        };
        assert_eq!(err.code(), "FS-00019");
    }

    #[test]
    fn test_error_display_handle_poisoned_includes_reason() {
        let err = Error::HandlePoisoned {
            reason: "driver task aborted".into(),
        };
        let s = err.to_string();
        assert!(s.starts_with("[FS-00019]"));
        assert!(s.contains("driver task aborted"));
    }

    #[test]
    fn test_error_source_handle_poisoned_returns_none() {
        let err = Error::HandlePoisoned {
            reason: "test".into(),
        };
        assert!(std::error::Error::source(&err).is_none());
    }

    #[test]
    fn test_error_code_iouring_submit_failed_returns_fs00020() {
        let err = Error::IoUringSubmitFailed { errno: 22 };
        assert_eq!(err.code(), "FS-00020");
    }

    #[test]
    fn test_error_display_iouring_submit_failed_includes_errno() {
        let err = Error::IoUringSubmitFailed { errno: 9 };
        let s = err.to_string();
        assert!(s.starts_with("[FS-00020]"));
        assert!(s.contains("9"));
    }

    #[test]
    fn test_error_source_iouring_submit_failed_returns_none() {
        let err = Error::IoUringSubmitFailed { errno: 0 };
        assert!(std::error::Error::source(&err).is_none());
    }

    #[test]
    fn test_error_code_completion_driver_dead_returns_fs00021() {
        let err = Error::CompletionDriverDead;
        assert_eq!(err.code(), "FS-00021");
    }

    #[test]
    fn test_error_display_completion_driver_dead_mentions_driver() {
        let err = Error::CompletionDriverDead;
        let s = err.to_string();
        assert!(s.starts_with("[FS-00021]"));
        assert!(s.to_ascii_lowercase().contains("driver"));
    }

    #[test]
    fn test_error_source_completion_driver_dead_returns_none() {
        let err = Error::CompletionDriverDead;
        assert!(std::error::Error::source(&err).is_none());
    }

    // ── 1.1.0 additions ──────────────────────────────────────────────────

    #[test]
    fn test_error_code_feature_not_enabled_returns_fs00022() {
        let err = Error::FeatureNotEnabled { feature: "spdk" };
        assert_eq!(err.code(), "FS-00022");
    }

    #[test]
    fn test_error_display_feature_not_enabled_includes_feature_name() {
        let err = Error::FeatureNotEnabled { feature: "spdk" };
        let s = err.to_string();
        assert!(s.starts_with("[FS-00022]"));
        assert!(s.contains("'spdk'"));
        assert!(s.to_ascii_lowercase().contains("feature"));
    }

    #[test]
    fn test_error_source_feature_not_enabled_returns_none() {
        let err = Error::FeatureNotEnabled { feature: "test" };
        assert!(std::error::Error::source(&err).is_none());
    }

    #[test]
    fn test_error_code_spdk_unavailable_returns_fs00023() {
        let err = Error::SpdkUnavailable {
            reason: crate::capability::SpdkSkipReason::NotLinux,
        };
        assert_eq!(err.code(), "FS-00023");
    }

    #[test]
    fn test_error_display_spdk_unavailable_includes_reason_text() {
        let err = Error::SpdkUnavailable {
            reason: crate::capability::SpdkSkipReason::NotLinux,
        };
        let s = err.to_string();
        assert!(s.starts_with("[FS-00023]"));
        assert!(s.to_ascii_lowercase().contains("spdk"));
        // SpdkSkipReason::Display must produce non-empty user-facing text.
        assert!(s.to_ascii_lowercase().contains("linux"));
    }

    #[test]
    fn test_error_source_spdk_unavailable_returns_none() {
        let err = Error::SpdkUnavailable {
            reason: crate::capability::SpdkSkipReason::NotLinux,
        };
        assert!(std::error::Error::source(&err).is_none());
    }
}