qubit-fs 0.3.3

Provider-neutral synchronous and asynchronous filesystem abstraction for Rust
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
// =============================================================================
//    Copyright (c) 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================
//! Owning asynchronous copy operation with cancellation-safe state tracking.

use super::internal::CopyCancellationGuard;
use super::internal::CopyDeadline;
use super::internal::CopyRecoverySnapshot;
use super::internal::StreamCopyPlan;
use super::internal::from_completed_stats;
use crate::AsyncFileSystem;
use crate::copy::AsyncCopyFailure;
use crate::copy::AsyncCopyOperationState;
use crate::copy::CopyConflictPolicy;
use crate::copy::CopyFailureState;
use crate::copy::CopyOptions;
use crate::copy::CopyOutcome;
use crate::copy::CopyStats;
use crate::copy::internal::from_write_failure_state;
use crate::error::FsError;
use crate::error::FsErrorKind;
use crate::error::FsOperation;
use crate::error::OpenFailureStage;
use crate::metadata::SymlinkPolicy;
use crate::path::Path;
use crate::read::ReadOptions;
use crate::spi::CopyAttempt;
use crate::spi::CopyRequest;
use crate::spi::ProviderOperation;
use crate::spi::ResolvedCopyOptions;
use crate::spi::SpiFuture;
use crate::write::AsyncWriterRecovery;
use crate::write::internal::is_unchanged_open_failure;
use crate::write::internal::open_failure_state;

/// An owning copy request whose recovery writer remains accessible after
/// failure.
///
/// # Examples
///
/// This example uses an isolated in-memory provider fixture.
/// The operation remains owned by the caller after an execution error, so the
/// caller can inspect its state and take any retained writer recovery.
///
/// ```rust
/// # mod support { include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/common/rustdoc_support.rs")); }
/// # use support::*;
/// # let (filesystem, _) = async_recording_spi::async_recording_file_system(Default::default());
/// # poll_support::ready(async {
/// use qubit_fs::Path;
/// use qubit_fs::copy::CopyOptions;
///
/// let mut operation = filesystem.begin_copy(
///     Path::parse("/source")?, Path::parse("/target")?, CopyOptions::default(),
/// )?;
/// let outcome = operation.execute().await?;
/// assert_eq!(5, outcome.stats().bytes);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// # }).unwrap();
/// ```
pub struct AsyncCopyOperation {
    /// Facade used to validate and execute the pending operation.
    pub(crate) file_system: AsyncFileSystem,
    /// Immutable validated source path.
    source: Path,
    /// Immutable validated destination path.
    target: Path,
    /// Facade-resolved copy policy.
    options: ResolvedCopyOptions,
    /// Observable lifecycle state.
    state: AsyncCopyOperationState,
    /// Destination writer retained when recovery remains possible.
    writer: Option<AsyncWriterRecovery>,
    /// Monotonic start used to enforce caller elapsed-time budgets.
    deadline: CopyDeadline,
    /// Publication state and progress retained for cancellation recovery.
    recovery: CopyRecoverySnapshot,
}

impl AsyncCopyOperation {
    /// Builds a preflight-validated operation without provider I/O.
    ///
    /// # Parameters
    /// - `file_system`: Facade that will validate and execute the operation.
    /// - `source`: Validated logical source path.
    /// - `target`: Validated logical destination path.
    /// - `options`: Copy options resolved by the facade.
    /// - `symlink_policy`: Policy applied when traversing symbolic links.
    ///
    /// # Returns
    /// A ready operation that retains the resolved copy request.
    #[must_use]
    pub(crate) fn new(
        file_system: AsyncFileSystem,
        source: Path,
        target: Path,
        options: CopyOptions,
        symlink_policy: SymlinkPolicy,
    ) -> Self {
        Self {
            file_system,
            source,
            target,
            deadline: CopyDeadline::new(options.deadline(), std::time::Instant::now),
            options: ResolvedCopyOptions::new(options, symlink_policy),
            state: AsyncCopyOperationState::Ready,
            writer: None,
            recovery: CopyRecoverySnapshot::unchanged(),
        }
    }

    /// Returns the immutable source path.
    ///
    /// # Returns
    /// The source path captured when the operation was created.
    #[inline]
    #[must_use]
    pub const fn source(&self) -> &Path {
        &self.source
    }

    /// Returns the immutable destination path.
    ///
    /// # Returns
    /// The destination path captured when the operation was created.
    #[inline]
    #[must_use]
    pub const fn target(&self) -> &Path {
        &self.target
    }

    /// Returns the current operation lifecycle state.
    ///
    /// # Returns
    /// The state most recently recorded by this operation.
    #[inline]
    #[must_use]
    pub const fn state(&self) -> AsyncCopyOperationState {
        self.state
    }

    /// Returns whether a recovery writer is retained by this operation.
    ///
    /// # Returns
    /// `true` when a recovery writer is retained, or `false` otherwise.
    #[inline]
    #[must_use]
    pub const fn has_recovery(&self) -> bool {
        self.writer.is_some()
    }

    /// Borrows the retained recovery writer, if one exists.
    ///
    /// # Returns
    /// `Some` with the retained writer, or `None` when no writer is retained.
    #[inline]
    pub fn recovery(&mut self) -> Option<&mut AsyncWriterRecovery> {
        self.writer.as_mut()
    }

    /// Takes ownership of the retained recovery writer, if one exists.
    ///
    /// # Returns
    /// `Some` with the removed writer, or `None` when no writer was retained.
    #[inline]
    pub fn take_recovery(&mut self) -> Option<AsyncWriterRecovery> {
        self.writer.take()
    }

    /// Executes the operation exactly once.
    ///
    /// The operation becomes running only when this future is first polled.
    /// Dropping a polled pending future records indeterminate state and does
    /// not invoke provider cleanup or start any additional I/O. The deadline
    /// includes time spent waiting before execution and is cooperative: a
    /// pending provider future is not forcibly woken by this operation, and
    /// external cancellation does not roll back provider publication.
    ///
    /// The returned [`AsyncCopyFailure`] owns the error, publication state, and
    /// copy statistics. This operation retains any recovery writer; inspect it
    /// with [`Self::recovery`] or transfer it with [`Self::take_recovery`].
    /// Keep the operation outside the cancellation scope and cancel only
    /// this `execute` future so those facts and recovery ownership remain
    /// available.
    ///
    /// # Returns
    /// The provider-confirmed copy outcome.
    ///
    /// # Errors
    /// Returns [`AsyncCopyFailure`] with the confirmed copy state and any
    /// retained writer when preflight, provider execution, fallback, or
    /// outcome validation fails.
    pub async fn execute(&mut self) -> Result<CopyOutcome, AsyncCopyFailure> {
        if self.state != AsyncCopyOperationState::Ready {
            return Err(invalid_state_failure(
                &self.source,
                &self.target,
                self.file_system.properties().info().provider_id(),
                self.recovery,
            ));
        }
        let Self {
            file_system,
            source,
            target,
            options,
            state,
            writer,
            deadline,
            recovery,
        } = self;
        let mut guard = CopyCancellationGuard::start(state, writer, recovery);
        let result = execute_copy(file_system, source, target, options, *deadline, guard.writer_mut()).await;
        guard.finish(&result);
        result
    }
}

/// Dispatches the asynchronous provider attempt and falls back only when the
/// provider explicitly declines it.
///
/// # Parameters
/// - `filesystem`: Facade used for provider execution and fallback.
/// - `source`: Validated source path.
/// - `target`: Destination path associated with the copy.
/// - `options`: Copy policy resolved by the facade.
/// - `deadline`: Caller budget shared by provider and fallback work.
/// - `writer`: Retained recovery writer, if fallback has opened one.
///
/// # Returns
/// The completed copy outcome when the provider or fallback succeeds.
///
/// # Errors
/// The contextual failure when limits, provider execution, or outcome
/// validation fails.
async fn execute_copy(
    filesystem: &AsyncFileSystem,
    source: &Path,
    target: &Path,
    options: &ResolvedCopyOptions,
    deadline: CopyDeadline,
    writer: &mut Option<AsyncWriterRecovery>,
) -> Result<CopyOutcome, AsyncCopyFailure> {
    let caller_options = options.options();
    if caller_options.max_entries() == Some(0) {
        return Err(filesystem.contextual_copy_failure(
            budget_error(source, target, "copy entry limit was exceeded"),
            CopyFailureState::Unchanged,
            CopyStats::default(),
            source,
            target,
        ));
    }
    if deadline.expired() {
        return Err(filesystem.contextual_copy_failure(
            budget_error(source, target, "copy deadline was exceeded"),
            CopyFailureState::Unchanged,
            CopyStats::default(),
            source,
            target,
        ));
    }
    if !filesystem.core().provider_supports(ProviderOperation::TryCopy) {
        return stream_copy_fallback(filesystem, source, target, options, deadline, writer).await;
    }
    match filesystem
        .spi()
        .try_copy(CopyRequest::new(source, target, options.clone()))
        .await
    {
        Ok(CopyAttempt::Completed(outcome)) => {
            let outcome = filesystem.verify_completed_copy(outcome, options.options(), source, target)?;
            if deadline.expired() {
                return Err(filesystem.contextual_copy_failure(
                    budget_error(source, target, "copy deadline was exceeded"),
                    from_completed_stats(outcome.stats()),
                    *outcome.stats(),
                    source,
                    target,
                ));
            }
            Ok(outcome)
        }
        Ok(CopyAttempt::Declined(_)) => {
            stream_copy_fallback(filesystem, source, target, options, deadline, writer).await
        }
        Err(failure) => {
            let (error, state, stats) = failure.into_parts();
            Err(filesystem.contextual_copy_failure(error, state, stats, source, target))
        }
    }
}

/// Streams a declined asynchronous copy while retaining any recovery writer
/// in `writer_slot` until publication or cleanup completes.
///
/// # Parameters
/// - `filesystem`: Facade used to read and write the copied resource.
/// - `source`: Validated source path.
/// - `target`: Validated destination path.
/// - `options`: Copy policy resolved by the facade.
/// - `deadline`: Caller budget checked throughout the transfer.
/// - `writer_slot`: Slot that retains the writer while recovery is possible.
///
/// # Returns
/// A future that resolves to the streamed copy outcome on success.
///
/// # Errors
/// The contextual failure when preflight, streaming, publication, or cleanup
/// fails.
#[inline]
fn stream_copy_fallback<'a>(
    filesystem: &'a AsyncFileSystem,
    source: &'a Path,
    target: &'a Path,
    options: &'a ResolvedCopyOptions,
    deadline: CopyDeadline,
    writer_slot: &'a mut Option<AsyncWriterRecovery>,
) -> SpiFuture<'a, Result<CopyOutcome, AsyncCopyFailure>> {
    Box::pin(async move {
        let options = options.options();
        let plan = StreamCopyPlan::new(options, filesystem.properties().limits(), source, target);
        if let Err(error) = plan.validate_options(filesystem.properties().symlink_policy()) {
            return Err(filesystem.contextual_copy_failure(
                error,
                CopyFailureState::Unchanged,
                CopyStats::default(),
                source,
                target,
            ));
        }
        if deadline.expired() {
            return Err(filesystem.contextual_copy_failure(
                budget_error(source, target, "copy deadline was exceeded"),
                CopyFailureState::Unchanged,
                CopyStats::default(),
                source,
                target,
            ));
        }
        filesystem
            .core()
            .require_stream_copy_primitives(source, target)
            .map_err(|error| {
                filesystem.contextual_copy_failure(
                    error,
                    CopyFailureState::Unchanged,
                    CopyStats::default(),
                    source,
                    target,
                )
            })?;
        let metadata = filesystem.stat(source).await.map_err(|error| {
            filesystem.contextual_copy_failure(error, CopyFailureState::Unchanged, CopyStats::default(), source, target)
        })?;
        if deadline.expired() {
            return Err(filesystem.contextual_copy_failure(
                budget_error(source, target, "copy deadline was exceeded"),
                CopyFailureState::Unchanged,
                CopyStats::default(),
                source,
                target,
            ));
        }
        if let Err(error) = plan.validate_metadata(&metadata) {
            return Err(filesystem.contextual_copy_failure(
                error,
                CopyFailureState::Unchanged,
                CopyStats::default(),
                source,
                target,
            ));
        }
        let mut reader = filesystem
            .open_reader(source, ReadOptions::default())
            .await
            .map_err(|error| {
                filesystem.contextual_copy_failure(
                    error,
                    CopyFailureState::Unchanged,
                    CopyStats::default(),
                    source,
                    target,
                )
            })?;
        if deadline.expired() {
            return Err(filesystem.contextual_copy_failure(
                budget_error(source, target, "copy deadline was exceeded"),
                CopyFailureState::Unchanged,
                CopyStats::default(),
                source,
                target,
            ));
        }
        let writer_options = plan.writer_options();
        match filesystem.open_writer(target, writer_options).await {
            Ok(writer) => *writer_slot = Some(AsyncWriterRecovery::Opened(Box::new(writer))),
            Err(error)
                if error.stage() == OpenFailureStage::ProviderOpen
                    && error.recovery().is_none()
                    && error.error().kind() == FsErrorKind::AlreadyExists
                    && is_unchanged_open_failure(error.error())
                    && options.conflict() == CopyConflictPolicy::Skip =>
            {
                let stats = CopyStats {
                    skipped: 1,
                    ..CopyStats::default()
                };
                if deadline.expired() {
                    return Err(filesystem.contextual_copy_failure(
                        budget_error(source, target, "copy deadline was exceeded"),
                        CopyFailureState::Unchanged,
                        stats,
                        source,
                        target,
                    ));
                }
                return Ok(CopyOutcome::streamed_fallback(
                    stats,
                    crate::metadata::AchievedAtomicity::NonAtomic,
                    false,
                ));
            }
            Err(error) => {
                let (error, stage, recovery) = error.into_parts();
                *writer_slot = recovery.map(AsyncWriterRecovery::Rejected);
                let state = match stage {
                    OpenFailureStage::Preflight => CopyFailureState::Unchanged,
                    OpenFailureStage::ProviderOpen => from_write_failure_state(open_failure_state(&error)),
                    OpenFailureStage::OutcomeValidation => CopyFailureState::Indeterminate,
                };
                return Err(filesystem.contextual_copy_failure(error, state, CopyStats::default(), source, target));
            }
        }
        let writer = writer_slot
            .as_mut()
            .and_then(AsyncWriterRecovery::opened_mut)
            .expect("writer is retained before transfer");
        let bytes =
            super::internal::transfer_stream(filesystem, source, target, &mut reader, writer, &plan, deadline).await?;
        super::internal::finish_stream_copy(
            filesystem,
            source,
            target,
            writer_slot,
            &plan,
            deadline,
            metadata.kind(),
            bytes,
        )
        .await
    })
}

/// Builds a caller-budget error for an asynchronous copy.
///
/// # Parameters
/// - `source`: Source path associated with the copy.
/// - `target`: Destination path associated with the copy.
/// - `message`: Human-readable reason the caller budget was exceeded.
///
/// # Returns
/// A resource-limit error associated with the source and destination paths.
fn budget_error(source: &Path, target: &Path, message: &str) -> FsError {
    FsError::new(FsErrorKind::ResourceLimitExceeded, FsOperation::Copy, message)
        .with_path(source.clone())
        .with_target(target.clone())
}

/// Builds the stable failure used for an invalid execute retry.
///
/// # Parameters
/// - `source`: Source path captured by the operation.
/// - `target`: Destination path captured by the operation.
/// - `provider`: Provider identifier associated with the operation.
/// - `snapshot`: Last confirmed publication state and transfer statistics.
///
/// # Returns
/// An invalid-state failure containing the saved publication state and stats.
fn invalid_state_failure(
    source: &Path,
    target: &Path,
    provider: &str,
    snapshot: CopyRecoverySnapshot,
) -> AsyncCopyFailure {
    AsyncCopyFailure::new(
        FsError::new(
            FsErrorKind::InvalidState,
            FsOperation::Copy,
            "copy operation cannot execute in its current state",
        )
        .with_path(source.clone())
        .with_target(target.clone())
        .with_provider(provider),
        snapshot.state,
        snapshot.stats,
    )
}

#[cfg(test)]
mod tests {
    use std::cell::Cell;
    use std::io::Result as IoResult;
    use std::pin::Pin;
    use std::sync::Arc;
    use std::sync::atomic::AtomicUsize;
    use std::sync::atomic::Ordering;
    use std::task::Context;
    use std::task::Poll;
    use std::task::Waker;
    use std::time::Duration;
    use std::time::Instant;

    use qubit_io::AsyncInput;
    use qubit_io::AsyncOutput;

    use super::AsyncCopyOperation;
    use super::CopyDeadline;
    use crate::copy::AsyncCopyOperationState;
    use crate::copy::CopyConflictPolicy;
    use crate::copy::CopyFailureState;
    use crate::copy::CopyOptions;
    use crate::error::FsError;
    use crate::error::FsErrorKind;
    use crate::error::FsOperation;
    use crate::error::FsResult;
    use crate::metadata::AchievedAtomicity;
    use crate::metadata::FileKind;
    use crate::metadata::FileMetadata;
    use crate::metadata::FileSystemCapabilities;
    use crate::metadata::FileSystemCapability;
    use crate::metadata::FileSystemId;
    use crate::metadata::FileSystemInfo;
    use crate::metadata::FileSystemLimits;
    use crate::metadata::OpenedFileInfo;
    use crate::metadata::PublicationMethod;
    use crate::metadata::SymlinkPolicy;
    use crate::metadata::WriteOutcome;
    use crate::path::Path;
    use crate::path::PathConstraints;
    use crate::path::PathSemantics;
    use crate::spi::AsyncFileSystemSpi;
    use crate::spi::AsyncFileWriteSession;
    use crate::spi::OpenReaderRequest;
    use crate::spi::OpenWriterRequest;
    use crate::spi::OpenedAsyncReader;
    use crate::spi::OpenedAsyncWriter;
    use crate::spi::ProviderOperation;
    use crate::spi::ProviderOperations;
    use crate::spi::ProviderProperties;
    use crate::spi::SpiFuture;
    use crate::spi::StatRequest;
    use crate::spi::StatResponse;
    use crate::write::WriteAbortOutcome;
    use crate::write::WriteFailure;
    use crate::write::WriteFailureState;

    thread_local! { static NOW: Cell<Option<Instant>> = const { Cell::new(None) }; }
    fn test_now() -> Instant {
        NOW.with(|now| now.get().expect("test clock initialized"))
    }
    fn advance_clock() {
        NOW.with(|now| {
            now.set(Some(
                now.get().expect("test clock initialized") + Duration::from_secs(1),
            ))
        });
    }

    #[derive(Clone, Copy)]
    enum SuspendAt {
        Flush,
        Commit,
    }
    struct StageSpi {
        suspend_at: SuspendAt,
        fail_commit: bool,
        skip_open: bool,
        skip_commit: bool,
        abort_outcome: WriteAbortOutcome,
        source_len: usize,
        write_limit: usize,
        write_pending_once: bool,
        write_zero: bool,
        write_error: bool,
        calls: Arc<StageCalls>,
    }
    #[derive(Default)]
    struct StageCalls {
        writes: AtomicUsize,
        flushes: AtomicUsize,
        commits: AtomicUsize,
        aborts: AtomicUsize,
    }
    impl StageSpi {
        fn info(&self, path: &Path) -> OpenedFileInfo {
            OpenedFileInfo::new(
                FileSystemId::new("async-deadline-test").expect("valid id"),
                path.clone(),
            )
            .with_metadata(FileMetadata::new(FileKind::File).with_len(Some(1)))
        }
    }
    impl AsyncFileSystemSpi for StageSpi {
        fn properties(&self) -> ProviderProperties {
            ProviderProperties::new(
                FileSystemInfo::new(
                    FileSystemId::new("async-deadline-test").expect("valid id"),
                    "async-deadline-test",
                    PathSemantics::Hierarchical,
                ),
                ProviderOperations::new()
                    .with(ProviderOperation::Stat)
                    .with(ProviderOperation::OpenReader)
                    .with(ProviderOperation::OpenWriter),
                FileSystemCapabilities::new()
                    .with_guaranteed(FileSystemCapability::Read)
                    .with_guaranteed(FileSystemCapability::Write),
                FileSystemLimits::unknown(),
                PathConstraints::absolute(),
                SymlinkPolicy::Reject,
            )
            .expect("valid provider properties")
        }
        fn stat<'a>(&'a self, request: StatRequest<'a>) -> SpiFuture<'a, FsResult<StatResponse>> {
            Box::pin(async move {
                Ok(StatResponse::new(
                    request.path().clone(),
                    FileMetadata::new(FileKind::File).with_len(Some(1)),
                ))
            })
        }
        fn open_reader<'a>(&'a self, request: OpenReaderRequest<'a>) -> SpiFuture<'a, FsResult<OpenedAsyncReader>> {
            let info = self.info(request.path());
            let source_len = self.source_len;
            Box::pin(async move {
                Ok(OpenedAsyncReader::new(
                    info,
                    Box::new(StageReader {
                        read: false,
                        source_len,
                    }),
                ))
            })
        }
        fn open_writer<'a>(&'a self, request: OpenWriterRequest<'a>) -> SpiFuture<'a, FsResult<OpenedAsyncWriter>> {
            let info = self.info(request.path());
            let suspend_at = self.suspend_at;
            let fail_commit = self.fail_commit;
            let skip_open = self.skip_open;
            let skip_commit = self.skip_commit;
            let abort_outcome = self.abort_outcome;
            let write_limit = self.write_limit;
            let write_pending_once = self.write_pending_once;
            let write_zero = self.write_zero;
            let write_error = self.write_error;
            let calls = self.calls.clone();
            if skip_open {
                let mut yielded = false;
                return Box::pin(std::future::poll_fn(move |_| {
                    if !yielded {
                        yielded = true;
                        return Poll::Pending;
                    }
                    Poll::Ready(Err(FsError::new(
                        FsErrorKind::AlreadyExists,
                        FsOperation::OpenWriter,
                        "skip conflict",
                    )
                    .with_effect_state(crate::error::FsEffectState::Unchanged)))
                }));
            }
            Box::pin(async move {
                Ok(OpenedAsyncWriter::new(
                    info,
                    Box::new(StageWriter {
                        suspend_at,
                        fail_commit,
                        skip_commit,
                        abort_outcome,
                        flush_pending: false,
                        write_limit,
                        write_pending_once,
                        write_zero,
                        write_error,
                        calls,
                    }),
                ))
            })
        }
    }

    struct StageReader {
        read: bool,
        source_len: usize,
    }
    impl AsyncInput for StageReader {
        type Item = u8;
        unsafe fn poll_read_unchecked(
            mut self: Pin<&mut Self>,
            _: &mut Context<'_>,
            output: &mut [u8],
            index: usize,
            count: usize,
        ) -> Poll<IoResult<usize>> {
            let this = self.as_mut().get_mut();
            if this.read || count == 0 {
                return Poll::Ready(Ok(0));
            }
            for offset in 0..count.min(this.source_len) {
                output[index + offset] = b'x';
            }
            this.read = true;
            Poll::Ready(Ok(count.min(this.source_len)))
        }
    }
    struct StageWriter {
        suspend_at: SuspendAt,
        fail_commit: bool,
        skip_commit: bool,
        abort_outcome: WriteAbortOutcome,
        flush_pending: bool,
        write_limit: usize,
        write_pending_once: bool,
        write_zero: bool,
        write_error: bool,
        calls: Arc<StageCalls>,
    }
    impl AsyncOutput for StageWriter {
        type Item = u8;
        unsafe fn poll_write_unchecked(
            self: Pin<&mut Self>,
            cx: &mut Context<'_>,
            _: &[u8],
            _: usize,
            count: usize,
        ) -> Poll<IoResult<usize>> {
            let this = self.get_mut();
            let attempts = this.calls.writes.fetch_add(1, Ordering::SeqCst);
            if this.write_pending_once && attempts == 0 {
                cx.waker().wake_by_ref();
                return Poll::Pending;
            }
            if attempts == usize::from(this.write_pending_once) && this.write_limit == 1 && count > 1 {
                advance_clock();
            }
            if this.write_zero {
                return Poll::Ready(Ok(0));
            }
            if this.write_error {
                advance_clock();
                return Poll::Ready(Err(std::io::Error::other("provider write failed")));
            }
            Poll::Ready(Ok(count.min(this.write_limit.max(1))))
        }
        fn poll_flush(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<IoResult<()>> {
            let this = self.as_mut().get_mut();
            this.calls.flushes.fetch_add(1, Ordering::SeqCst);
            if matches!(this.suspend_at, SuspendAt::Flush) && !this.flush_pending {
                this.flush_pending = true;
                Poll::Pending
            } else {
                Poll::Ready(Ok(()))
            }
        }
    }
    impl AsyncFileWriteSession for StageWriter {
        fn commit_async<'a>(mut self: Pin<&'a mut Self>) -> SpiFuture<'a, Result<WriteOutcome, WriteFailure>> {
            let this = self.as_mut().get_mut();
            this.calls.commits.fetch_add(1, Ordering::SeqCst);
            let fail = this.fail_commit;
            let skip = this.skip_commit;
            let suspend = matches!(this.suspend_at, SuspendAt::Commit) || skip;
            let mut yielded = false;
            Box::pin(std::future::poll_fn(move |_| {
                if suspend && !yielded {
                    yielded = true;
                    return Poll::Pending;
                }
                advance_clock();
                Poll::Ready(if skip {
                    Err(WriteFailure::new(
                        FsError::new(FsErrorKind::AlreadyExists, FsOperation::CommitWriter, "skip conflict"),
                        WriteFailureState::RetryableNotPublished,
                    ))
                } else if fail {
                    Err(WriteFailure::new(
                        FsError::new(FsErrorKind::Io, FsOperation::CommitWriter, "late async commit failure"),
                        WriteFailureState::RetryableNotPublished,
                    ))
                } else {
                    Ok(WriteOutcome::new(
                        AchievedAtomicity::NonAtomic,
                        PublicationMethod::Direct,
                    ))
                })
            }))
        }
        fn abort_async<'a>(self: Pin<&'a mut Self>) -> SpiFuture<'a, FsResult<WriteAbortOutcome>> {
            let this = self.get_mut();
            this.calls.aborts.fetch_add(1, Ordering::SeqCst);
            let outcome = this.abort_outcome;
            Box::pin(async move {
                advance_clock();
                Ok(outcome)
            })
        }
    }

    struct WriteTestConfig {
        suspend_at: SuspendAt,
        fail_commit: bool,
        source_len: usize,
        write_limit: usize,
        write_pending_once: bool,
        write_zero: bool,
        write_error: bool,
        with_deadline: bool,
        calls: Arc<StageCalls>,
    }
    impl Default for WriteTestConfig {
        fn default() -> Self {
            Self {
                suspend_at: SuspendAt::Commit,
                fail_commit: false,
                source_len: 1,
                write_limit: 1,
                write_pending_once: false,
                write_zero: false,
                write_error: false,
                with_deadline: true,
                calls: Arc::new(StageCalls::default()),
            }
        }
    }

    fn operation(suspend_at: SuspendAt, fail_commit: bool) -> AsyncCopyOperation {
        operation_with_writes(WriteTestConfig {
            suspend_at,
            fail_commit,
            ..WriteTestConfig::default()
        })
    }

    fn operation_with_writes(config: WriteTestConfig) -> AsyncCopyOperation {
        let with_deadline = config.with_deadline;
        let file_system = crate::AsyncFileSystem::from_spi(StageSpi {
            suspend_at: config.suspend_at,
            fail_commit: config.fail_commit,
            skip_open: false,
            skip_commit: false,
            abort_outcome: WriteAbortOutcome::NotPublished,
            source_len: config.source_len,
            write_limit: config.write_limit,
            write_pending_once: config.write_pending_once,
            write_zero: config.write_zero,
            write_error: config.write_error,
            calls: config.calls,
        })
        .expect("valid async filesystem");
        let start = Instant::now();
        NOW.with(|now| now.set(Some(start)));
        let mut operation = AsyncCopyOperation::new(
            file_system,
            Path::parse("/source").expect("source"),
            Path::parse("/target").expect("target"),
            if with_deadline {
                CopyOptions::file().with_deadline(Some(Duration::from_secs(1)))
            } else {
                CopyOptions::file()
            },
            SymlinkPolicy::Reject,
        );
        operation.deadline = CopyDeadline::new(with_deadline.then_some(Duration::from_secs(1)), test_now);
        operation
    }

    fn skip_operation(skip_open: bool, abort_outcome: WriteAbortOutcome, with_deadline: bool) -> AsyncCopyOperation {
        let file_system = crate::AsyncFileSystem::from_spi(StageSpi {
            suspend_at: SuspendAt::Commit,
            fail_commit: false,
            skip_open,
            skip_commit: !skip_open,
            abort_outcome,
            source_len: 1,
            write_limit: usize::MAX,
            write_pending_once: false,
            write_zero: false,
            write_error: false,
            calls: Arc::new(StageCalls::default()),
        })
        .expect("valid async filesystem");
        let start = Instant::now();
        NOW.with(|now| now.set(Some(start)));
        let mut options = CopyOptions::default().with_conflict(CopyConflictPolicy::Skip);
        if with_deadline {
            options = options.with_deadline(Some(Duration::from_secs(1)));
        }
        let mut operation = AsyncCopyOperation::new(
            file_system,
            Path::parse("/source").expect("source"),
            Path::parse("/target").expect("target"),
            options,
            SymlinkPolicy::Reject,
        );
        if with_deadline {
            operation.deadline = CopyDeadline::new(Some(Duration::from_secs(1)), test_now);
        }
        operation
    }

    #[test]
    fn test_async_copy_deadline_after_flush_preserves_indeterminate_recovery() {
        let mut operation = operation(SuspendAt::Flush, false);
        let mut future = Box::pin(operation.execute());
        let mut context = Context::from_waker(Waker::noop());
        assert!(
            future.as_mut().poll(&mut context).is_pending(),
            "flush must suspend on first poll"
        );
        advance_clock();
        let failure = match future.as_mut().poll(&mut context) {
            Poll::Ready(Err(failure)) => failure,
            _ => panic!("expired flush must fail"),
        };
        drop(future);
        assert_eq!(CopyFailureState::Indeterminate, failure.state());
        assert_eq!(1, failure.partial_stats().bytes);
        assert!(operation.has_recovery());
        assert_eq!(
            AsyncCopyOperationState::Failed(CopyFailureState::Indeterminate),
            operation.state()
        );
    }

    #[test]
    fn test_async_copy_deadline_after_commit_is_published_without_recovery() {
        let mut operation = operation(SuspendAt::Commit, false);
        let mut future = Box::pin(operation.execute());
        let mut context = Context::from_waker(Waker::noop());
        assert!(
            future.as_mut().poll(&mut context).is_pending(),
            "commit must suspend on first poll"
        );
        advance_clock();
        let failure = match future.as_mut().poll(&mut context) {
            Poll::Ready(Err(failure)) => failure,
            _ => panic!("expired commit must fail"),
        };
        drop(future);
        assert_eq!(CopyFailureState::Published, failure.state());
        assert_eq!(1, failure.partial_stats().bytes);
        assert!(!operation.has_recovery());
    }

    #[test]
    fn test_async_copy_deadline_preserves_late_provider_commit_error() {
        let mut operation = operation(SuspendAt::Commit, true);
        let mut future = Box::pin(operation.execute());
        let mut context = Context::from_waker(Waker::noop());
        assert!(future.as_mut().poll(&mut context).is_pending());
        advance_clock();
        let failure = match future.as_mut().poll(&mut context) {
            Poll::Ready(Err(failure)) => failure,
            _ => panic!("provider error must win"),
        };
        drop(future);
        assert_eq!(FsErrorKind::Io, failure.error().kind());
        assert_eq!(CopyFailureState::Unchanged, failure.state());
    }

    #[test]
    fn test_async_copy_deadline_after_open_skip_preserves_skipped_stats() {
        let mut operation = skip_operation(true, WriteAbortOutcome::NotPublished, true);
        let mut future = Box::pin(operation.execute());
        let mut context = Context::from_waker(Waker::noop());
        assert!(
            future.as_mut().poll(&mut context).is_pending(),
            "provider open must suspend first"
        );
        advance_clock();
        let failure = match future.as_mut().poll(&mut context) {
            Poll::Ready(Err(failure)) => failure,
            _ => panic!("expired skipped open must fail"),
        };
        drop(future);
        assert_eq!(CopyFailureState::Unchanged, failure.state());
        assert_eq!(1, failure.partial_stats().skipped);
        assert!(!operation.has_recovery());
    }

    #[test]
    fn test_async_copy_deadline_after_skip_abort_keeps_abort_publication_state() {
        for abort_outcome in [WriteAbortOutcome::Published, WriteAbortOutcome::Indeterminate] {
            let mut operation = skip_operation(false, abort_outcome, true);
            let mut future = Box::pin(operation.execute());
            let mut context = Context::from_waker(Waker::noop());
            assert!(
                future.as_mut().poll(&mut context).is_pending(),
                "commit must suspend first"
            );
            advance_clock();
            let failure = match future.as_mut().poll(&mut context) {
                Poll::Ready(Err(failure)) => failure,
                _ => panic!("expired skipped commit must fail"),
            };
            drop(future);
            assert_eq!(
                if abort_outcome == WriteAbortOutcome::Published {
                    CopyFailureState::Published
                } else {
                    CopyFailureState::Indeterminate
                },
                failure.state(),
            );
            assert_eq!(1, failure.partial_stats().skipped);
            assert!(!operation.has_recovery());
        }
    }

    #[test]
    fn test_async_copy_skip_without_deadline_remains_successful() {
        let mut operation = skip_operation(true, WriteAbortOutcome::NotPublished, false);
        let mut future = Box::pin(operation.execute());
        let mut context = Context::from_waker(Waker::noop());
        assert!(
            future.as_mut().poll(&mut context).is_pending(),
            "provider open must suspend first"
        );
        let outcome = match future.as_mut().poll(&mut context) {
            Poll::Ready(Ok(outcome)) => outcome,
            _ => panic!("unbounded skip should succeed"),
        };
        drop(future);
        assert_eq!(1, outcome.stats().skipped);
        assert_eq!(AsyncCopyOperationState::Completed, operation.state());
    }

    #[test]
    fn test_async_copy_deadline_after_first_short_write_stops_before_second_write() {
        let calls = Arc::new(StageCalls::default());
        let mut operation = operation_with_writes(WriteTestConfig {
            source_len: 4,
            calls: calls.clone(),
            ..WriteTestConfig::default()
        });
        let mut future = Box::pin(operation.execute());
        let mut context = Context::from_waker(Waker::noop());
        let failure = match future.as_mut().poll(&mut context) {
            Poll::Ready(Err(failure)) => failure,
            _ => panic!("deadline after first short write must fail"),
        };
        drop(future);
        assert_eq!(FsErrorKind::ResourceLimitExceeded, failure.error().kind());
        assert_eq!(1, failure.partial_stats().bytes);
        assert_eq!(1, calls.writes.load(Ordering::SeqCst));
        assert_eq!(0, calls.flushes.load(Ordering::SeqCst));
        assert_eq!(0, calls.commits.load(Ordering::SeqCst));
        assert_eq!(0, calls.aborts.load(Ordering::SeqCst));
        assert_eq!(0, failure.partial_stats().files);
        assert!(operation.has_recovery());
    }

    #[test]
    fn test_async_copy_deadline_after_pending_then_short_write_stops_before_second_write() {
        let calls = Arc::new(StageCalls::default());
        let mut operation = operation_with_writes(WriteTestConfig {
            source_len: 4,
            write_pending_once: true,
            calls: calls.clone(),
            ..WriteTestConfig::default()
        });
        let mut future = Box::pin(operation.execute());
        let mut context = Context::from_waker(Waker::noop());
        assert!(future.as_mut().poll(&mut context).is_pending());
        let failure = match future.as_mut().poll(&mut context) {
            Poll::Ready(Err(failure)) => failure,
            _ => panic!("deadline after pending write must fail"),
        };
        drop(future);
        assert_eq!(FsErrorKind::ResourceLimitExceeded, failure.error().kind());
        assert_eq!(1, failure.partial_stats().bytes);
        assert_eq!(2, calls.writes.load(Ordering::SeqCst));
        assert_eq!(0, calls.flushes.load(Ordering::SeqCst));
        assert_eq!(0, calls.commits.load(Ordering::SeqCst));
        assert_eq!(0, calls.aborts.load(Ordering::SeqCst));
        assert!(operation.has_recovery());
    }

    #[test]
    fn test_async_copy_short_writes_without_deadline_complete() {
        let calls = Arc::new(StageCalls::default());
        let mut operation = operation_with_writes(WriteTestConfig {
            source_len: 4,
            with_deadline: false,
            calls: calls.clone(),
            ..WriteTestConfig::default()
        });
        let mut future = Box::pin(operation.execute());
        let mut context = Context::from_waker(Waker::noop());
        assert!(future.as_mut().poll(&mut context).is_pending());
        let outcome = match future.as_mut().poll(&mut context) {
            Poll::Ready(Ok(outcome)) => outcome,
            _ => panic!("short writes should complete without a deadline"),
        };
        assert_eq!(4, outcome.stats().bytes);
        assert_eq!(4, calls.writes.load(Ordering::SeqCst));
        assert_eq!(1, calls.flushes.load(Ordering::SeqCst));
        assert_eq!(1, calls.commits.load(Ordering::SeqCst));
        assert_eq!(0, calls.aborts.load(Ordering::SeqCst));
    }

    #[test]
    fn test_async_copy_zero_progress_preserves_write_zero_error() {
        let calls = Arc::new(StageCalls::default());
        let mut operation = operation_with_writes(WriteTestConfig {
            source_len: 4,
            write_zero: true,
            with_deadline: false,
            calls: calls.clone(),
            ..WriteTestConfig::default()
        });
        let mut future = Box::pin(operation.execute());
        let mut context = Context::from_waker(Waker::noop());
        let failure = match future.as_mut().poll(&mut context) {
            Poll::Ready(Err(failure)) => failure,
            _ => panic!("zero progress must fail"),
        };
        drop(future);
        let source = std::error::Error::source(failure.error()).expect("stream error source");
        assert_eq!(
            Some(std::io::ErrorKind::WriteZero),
            source.downcast_ref::<std::io::Error>().map(std::io::Error::kind),
        );
        assert_eq!(0, failure.partial_stats().bytes);
        assert_eq!(1, calls.writes.load(Ordering::SeqCst));
        assert_eq!(0, calls.flushes.load(Ordering::SeqCst));
        assert_eq!(0, calls.commits.load(Ordering::SeqCst));
        assert_eq!(0, calls.aborts.load(Ordering::SeqCst));
        assert!(operation.has_recovery());
    }

    #[test]
    fn test_async_copy_provider_write_error_wins_when_deadline_expires() {
        let calls = Arc::new(StageCalls::default());
        let mut operation = operation_with_writes(WriteTestConfig {
            source_len: 4,
            write_error: true,
            calls: calls.clone(),
            ..WriteTestConfig::default()
        });
        let mut future = Box::pin(operation.execute());
        let mut context = Context::from_waker(Waker::noop());
        let failure = match future.as_mut().poll(&mut context) {
            Poll::Ready(Err(failure)) => failure,
            _ => panic!("provider write error must win"),
        };
        assert_eq!(FsErrorKind::Io, failure.error().kind());
        assert_eq!(0, failure.partial_stats().bytes);
        assert_eq!(1, calls.writes.load(Ordering::SeqCst));
        assert_eq!(0, calls.flushes.load(Ordering::SeqCst));
        assert_eq!(0, calls.commits.load(Ordering::SeqCst));
        assert_eq!(0, calls.aborts.load(Ordering::SeqCst));
    }

    #[test]
    fn test_async_copy_ready_short_writes_yield_after_sixty_four_calls() {
        let calls = Arc::new(StageCalls::default());
        let mut operation = operation_with_writes(WriteTestConfig {
            source_len: 65,
            with_deadline: false,
            calls: calls.clone(),
            ..WriteTestConfig::default()
        });
        let mut future = Box::pin(operation.execute());
        let mut context = Context::from_waker(Waker::noop());
        assert!(future.as_mut().poll(&mut context).is_pending());
        assert_eq!(64, calls.writes.load(Ordering::SeqCst));
        loop {
            match future.as_mut().poll(&mut context) {
                Poll::Pending => continue,
                Poll::Ready(Ok(outcome)) => {
                    assert_eq!(65, outcome.stats().bytes);
                    break;
                }
                Poll::Ready(Err(failure)) => panic!("copy failed: {}", failure.error()),
            }
        }
        assert_eq!(65, calls.writes.load(Ordering::SeqCst));
    }
}