asupersync 0.3.1

Spec-first, cancel-correct, capability-secure async runtime 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
//! First-ok combinator: try operations until one succeeds.
//!
//! The first_ok combinator tries a sequence of operations, returning the first
//! `Ok` result. If all operations fail, returns an aggregated error containing
//! all failures. This is essential for fallback chains, service discovery,
//! and graceful degradation.
//!
//! # Distinction from Race
//!
//! - **race**: Run all concurrently, first to *complete* wins (regardless of outcome)
//! - **first_ok**: Try sequentially, first *success* wins (errors cause fallback)
//!
//! For Phase 0 (single-threaded), this implements sequential first_ok.
//! Concurrent variants will be added in Phase 1.
//!
//! # Semantics
//!
//! ```text
//! first_ok([f1, f2, ..., fn]):
//!   errors ← []
//!   for f in [f1, f2, ..., fn]:
//!     check_cancellation()
//!     result ← await(f)
//!     if result is Ok:
//!       return Ok(result)
//!     else:
//!       errors.push(result)
//!   return Err(errors)
//! ```
//!
//! # Use Cases
//!
//! - **Service fallback**: Primary → Secondary → Tertiary endpoint
//! - **Configuration sources**: File → Environment → Defaults
//! - **Parser fallback**: Try parsers in preference order
//! - **Cache hierarchy**: L1 → L2 → L3 → Origin
//!
//! # Cancellation Handling
//!
//! - Check cancellation status before each attempt
//! - If cancelled: return Cancelled with errors collected so far
//! - Do not start new attempts after cancellation

use core::fmt;
use std::marker::PhantomData;

use crate::types::Outcome;
use crate::types::cancel::CancelReason;
use crate::types::outcome::PanicPayload;

/// A first_ok combinator for fallback chains.
///
/// This is a builder/marker type; actual execution happens via the runtime.
#[derive(Debug)]
pub struct FirstOk<T, E> {
    _t: PhantomData<T>,
    _e: PhantomData<E>,
}

impl<T, E> FirstOk<T, E> {
    /// Creates a new first_ok combinator (internal use).
    #[inline]
    #[must_use]
    pub const fn new() -> Self {
        Self {
            _t: PhantomData,
            _e: PhantomData,
        }
    }
}

impl<T, E> Default for FirstOk<T, E> {
    fn default() -> Self {
        Self::new()
    }
}

/// Error type for first_ok operations.
///
/// When no operation succeeds, this error contains all the failures encountered.
#[derive(Debug, Clone)]
pub enum FirstOkError<E> {
    /// All operations failed with errors.
    ///
    /// Contains the errors from each operation in attempt order.
    AllFailed {
        /// Errors from each failed operation.
        errors: Vec<E>,
        /// Total number of operations attempted.
        attempted: usize,
    },
    /// The operation was cancelled before any succeeded.
    ///
    /// Contains errors collected before cancellation.
    Cancelled {
        /// The cancellation reason.
        reason: CancelReason,
        /// Errors collected before cancellation.
        errors_before_cancel: Vec<E>,
        /// Number of operations attempted before cancellation.
        attempted_before_cancel: usize,
    },
    /// One of the operations panicked.
    Panicked(PanicPayload),
    /// No operations were provided.
    Empty,
}

impl<E: fmt::Display> fmt::Display for FirstOkError<E> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::AllFailed { errors, attempted } => {
                write!(
                    f,
                    "all {} operations failed: {} errors",
                    attempted,
                    errors.len()
                )
            }
            Self::Cancelled {
                reason,
                errors_before_cancel,
                attempted_before_cancel,
            } => {
                write!(
                    f,
                    "cancelled after {} attempts ({} errors): {}",
                    attempted_before_cancel,
                    errors_before_cancel.len(),
                    reason
                )
            }
            Self::Panicked(p) => write!(f, "operation panicked: {p}"),
            Self::Empty => write!(f, "no operations provided"),
        }
    }
}

impl<E: fmt::Debug + fmt::Display> std::error::Error for FirstOkError<E> {}

/// A single failure in a first_ok chain.
#[derive(Debug, Clone)]
pub enum FirstOkFailure<E> {
    /// Application error.
    Error(E),
    /// Cancelled.
    Cancelled(CancelReason),
    /// Panicked.
    Panicked(PanicPayload),
}

impl<E: fmt::Display> fmt::Display for FirstOkFailure<E> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Error(e) => write!(f, "error: {e}"),
            Self::Cancelled(r) => write!(f, "cancelled: {r}"),
            Self::Panicked(p) => write!(f, "panicked: {p}"),
        }
    }
}

/// Result of a first_ok operation.
///
/// Contains either the successful value or all failures encountered.
#[derive(Debug)]
pub struct FirstOkResult<T, E> {
    /// Whether any operation succeeded.
    pub success: Option<FirstOkSuccess<T>>,
    /// All failures encountered before success (or all failures if none succeeded).
    pub failures: Vec<(usize, FirstOkFailure<E>)>,
    /// Total number of operations.
    pub total: usize,
    /// Whether a cancellation was encountered.
    pub was_cancelled: bool,
    /// Whether a panic was encountered.
    pub had_panic: bool,
}

/// A successful result in a first_ok chain.
#[derive(Debug)]
pub struct FirstOkSuccess<T> {
    /// Index of the successful operation.
    pub index: usize,
    /// The successful value.
    pub value: T,
}

impl<T, E> FirstOkResult<T, E> {
    /// Creates a new first_ok result with a success.
    #[must_use]
    pub fn success(
        index: usize,
        value: T,
        failures: Vec<(usize, FirstOkFailure<E>)>,
        total: usize,
    ) -> Self {
        Self {
            success: Some(FirstOkSuccess { index, value }),
            failures,
            total,
            was_cancelled: false,
            had_panic: false,
        }
    }

    /// Creates a new first_ok result with no success.
    #[must_use]
    pub fn failure(failures: Vec<(usize, FirstOkFailure<E>)>, total: usize) -> Self {
        let was_cancelled = failures
            .iter()
            .any(|(_, f)| matches!(f, FirstOkFailure::Cancelled(_)));
        let had_panic = failures
            .iter()
            .any(|(_, f)| matches!(f, FirstOkFailure::Panicked(_)));

        Self {
            success: None,
            failures,
            total,
            was_cancelled,
            had_panic,
        }
    }

    /// Returns true if any operation succeeded.
    #[must_use]
    pub const fn is_success(&self) -> bool {
        self.success.is_some()
    }

    /// Returns the number of operations attempted before success (or total if no success).
    #[must_use]
    pub fn attempts(&self) -> usize {
        self.success
            .as_ref()
            .map_or(self.failures.len(), |s| s.index + 1)
    }
}

/// Aggregates outcomes with first-ok semantics.
///
/// This is the semantic core of the first_ok combinator. It processes
/// outcomes in order and returns on the first success.
///
/// # Arguments
/// * `outcomes` - All outcomes from the operations in attempt order
///
/// # Returns
/// A `FirstOkResult` containing either the first success or all failures.
///
/// # Example
/// ```
/// use asupersync::combinator::first_ok::first_ok_outcomes;
/// use asupersync::types::Outcome;
///
/// // Second operation succeeds
/// let outcomes: Vec<Outcome<i32, &str>> = vec![
///     Outcome::Err("first failed"),
///     Outcome::Ok(42),
///     Outcome::Err("never reached"),
/// ];
/// let result = first_ok_outcomes(outcomes);
/// assert!(result.is_success());
/// assert_eq!(result.success.unwrap().index, 1);
/// ```
#[must_use]
pub fn first_ok_outcomes<T, E>(outcomes: Vec<Outcome<T, E>>) -> FirstOkResult<T, E> {
    let total = outcomes.len();

    // Handle empty case
    if total == 0 {
        return FirstOkResult::failure(Vec::new(), 0);
    }

    let mut failures = Vec::with_capacity(total);

    for (i, outcome) in outcomes.into_iter().enumerate() {
        match outcome {
            Outcome::Ok(v) => {
                // First success - return immediately
                return FirstOkResult::success(i, v, failures, total);
            }
            Outcome::Err(e) => {
                failures.push((i, FirstOkFailure::Error(e)));
            }
            Outcome::Cancelled(r) => {
                failures.push((i, FirstOkFailure::Cancelled(r)));
                // Cancellation stops the chain
                return FirstOkResult::failure(failures, total);
            }
            Outcome::Panicked(p) => {
                failures.push((i, FirstOkFailure::Panicked(p)));
                // Panic stops the chain
                return FirstOkResult::failure(failures, total);
            }
        }
    }

    // All failed
    FirstOkResult::failure(failures, total)
}

/// Converts a first_ok result to a Result for fail-fast handling.
///
/// If any operation succeeded, returns `Ok` with the value.
/// If all failed, returns `Err` with all errors.
///
/// # Example
/// ```
/// use asupersync::combinator::first_ok::{first_ok_outcomes, first_ok_to_result};
/// use asupersync::types::Outcome;
///
/// let outcomes: Vec<Outcome<i32, &str>> = vec![
///     Outcome::Err("first failed"),
///     Outcome::Ok(42),
/// ];
/// let result = first_ok_outcomes(outcomes);
/// let value = first_ok_to_result(result);
/// assert_eq!(value.unwrap(), 42);
/// ```
pub fn first_ok_to_result<T, E>(result: FirstOkResult<T, E>) -> Result<T, FirstOkError<E>> {
    // Check for success first
    if let Some(success) = result.success {
        return Ok(success.value);
    }

    // Handle empty case
    if result.total == 0 {
        return Err(FirstOkError::Empty);
    }

    // Check for panics first (highest severity)
    for (_, failure) in &result.failures {
        if let FirstOkFailure::Panicked(p) = failure {
            return Err(FirstOkError::Panicked(p.clone()));
        }
    }

    // Check for cancellations
    if let Some(cancel_idx) = result
        .failures
        .iter()
        .position(|(_, f)| matches!(f, FirstOkFailure::Cancelled(_)))
    {
        let _attempted = result.failures.len();
        let mut failures = result.failures;
        let cancel_failure = failures.remove(cancel_idx);
        let FirstOkFailure::Cancelled(reason) = cancel_failure.1 else {
            unreachable!()
        };

        // Collect errors before the cancellation
        let errors_before: Vec<E> = failures
            .into_iter()
            .take(cancel_idx)
            .filter_map(|(_, f)| match f {
                FirstOkFailure::Error(e) => Some(e),
                _ => None,
            })
            .collect();

        return Err(FirstOkError::Cancelled {
            reason,
            errors_before_cancel: errors_before,
            attempted_before_cancel: cancel_idx, // Number of attempts before the cancelled one
        });
    }

    // All errors - collect them
    let attempted = result.failures.len();
    let errors: Vec<E> = result
        .failures
        .into_iter()
        .filter_map(|(_, f)| match f {
            FirstOkFailure::Error(e) => Some(e),
            _ => None,
        })
        .collect();

    Err(FirstOkError::AllFailed { errors, attempted })
}

/// Checks if first_ok can still succeed given current state.
///
/// This is useful for early termination in concurrent implementations:
/// if cancellation or panic occurred, we should stop trying.
///
/// # Arguments
/// * `was_cancelled` - Whether a cancellation has been encountered
/// * `had_panic` - Whether a panic has been encountered
/// * `remaining` - Number of operations not yet tried
///
/// # Returns
/// `true` if first_ok can still succeed, `false` if impossible.
#[must_use]
pub const fn first_ok_still_possible(
    was_cancelled: bool,
    had_panic: bool,
    remaining: usize,
) -> bool {
    !was_cancelled && !had_panic && remaining > 0
}

/// Tries operations sequentially until one succeeds.
///
/// Returns the first success, or a collection of all errors if all fail.
///
/// # Semantics
///
/// ```ignore
/// let result = first_ok!(
///     try_cache(),
///     try_database(),
///     try_fallback(),
/// ).await;
/// ```
///
/// Operations are tried in order. Unlike `race!`, this is sequential:
/// the second operation only starts after the first fails.
#[macro_export]
macro_rules! first_ok {
    (@count $head:expr $(, $tail:expr)*) => {
        1usize $(+ $crate::first_ok!(@count $tail))*
    };
    ($($operation:expr),+ $(,)?) => {{
        async move {
            let __first_ok_total = $crate::first_ok!(@count $($operation),+);
            let mut __first_ok_failures = ::std::vec::Vec::with_capacity(__first_ok_total);
            let mut __first_ok_index = 0usize;

            $(
                match ($operation).await {
                    $crate::types::Outcome::Ok(__first_ok_value) => {
                        return $crate::combinator::first_ok::FirstOkResult::success(
                            __first_ok_index,
                            __first_ok_value,
                            __first_ok_failures,
                            __first_ok_total,
                        );
                    }
                    $crate::types::Outcome::Err(__first_ok_error) => {
                        __first_ok_failures.push((
                            __first_ok_index,
                            $crate::combinator::first_ok::FirstOkFailure::Error(__first_ok_error),
                        ));
                    }
                    $crate::types::Outcome::Cancelled(__first_ok_reason) => {
                        __first_ok_failures.push((
                            __first_ok_index,
                            $crate::combinator::first_ok::FirstOkFailure::Cancelled(__first_ok_reason),
                        ));
                        return $crate::combinator::first_ok::FirstOkResult::failure(
                            __first_ok_failures,
                            __first_ok_total,
                        );
                    }
                    $crate::types::Outcome::Panicked(__first_ok_payload) => {
                        __first_ok_failures.push((
                            __first_ok_index,
                            $crate::combinator::first_ok::FirstOkFailure::Panicked(__first_ok_payload),
                        ));
                        return $crate::combinator::first_ok::FirstOkResult::failure(
                            __first_ok_failures,
                            __first_ok_total,
                        );
                    }
                }
                __first_ok_index += 1;
            )+

            $crate::combinator::first_ok::FirstOkResult::failure(
                __first_ok_failures,
                __first_ok_total,
            )
        }
    }};
}

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

    #[test]
    fn first_ok_first_succeeds() {
        let outcomes: Vec<Outcome<i32, &str>> =
            vec![Outcome::Ok(1), Outcome::Ok(2), Outcome::Ok(3)];
        let result = first_ok_outcomes(outcomes);

        assert!(result.is_success());
        let success = result.success.unwrap();
        assert_eq!(success.index, 0);
        assert_eq!(success.value, 1);
        assert!(result.failures.is_empty());
    }

    #[test]
    fn first_ok_middle_succeeds() {
        let outcomes: Vec<Outcome<i32, &str>> =
            vec![Outcome::Err("e1"), Outcome::Ok(42), Outcome::Err("e3")];
        let result = first_ok_outcomes(outcomes);

        assert!(result.is_success());
        let success = result.success.unwrap();
        assert_eq!(success.index, 1);
        assert_eq!(success.value, 42);
        assert_eq!(result.failures.len(), 1); // Only first failure collected
    }

    #[test]
    fn first_ok_last_succeeds() {
        let outcomes: Vec<Outcome<i32, &str>> =
            vec![Outcome::Err("e1"), Outcome::Err("e2"), Outcome::Ok(99)];
        let result = first_ok_outcomes(outcomes);

        assert!(result.is_success());
        let success = result.success.unwrap();
        assert_eq!(success.index, 2);
        assert_eq!(success.value, 99);
        assert_eq!(result.failures.len(), 2);
    }

    #[test]
    fn first_ok_all_fail() {
        let outcomes: Vec<Outcome<i32, &str>> =
            vec![Outcome::Err("e1"), Outcome::Err("e2"), Outcome::Err("e3")];
        let result = first_ok_outcomes(outcomes);

        assert!(!result.is_success());
        assert!(result.success.is_none());
        assert_eq!(result.failures.len(), 3);
    }

    #[test]
    fn first_ok_empty() {
        let outcomes: Vec<Outcome<i32, &str>> = vec![];
        let result = first_ok_outcomes(outcomes);

        assert!(!result.is_success());
        assert_eq!(result.total, 0);
    }

    #[test]
    fn first_ok_single_success() {
        let outcomes: Vec<Outcome<i32, &str>> = vec![Outcome::Ok(42)];
        let result = first_ok_outcomes(outcomes);

        assert!(result.is_success());
        assert_eq!(result.success.unwrap().value, 42);
    }

    #[test]
    fn first_ok_single_failure() {
        let outcomes: Vec<Outcome<i32, &str>> = vec![Outcome::Err("fail")];
        let result = first_ok_outcomes(outcomes);

        assert!(!result.is_success());
        assert_eq!(result.failures.len(), 1);
    }

    #[test]
    fn first_ok_cancellation_stops() {
        let outcomes: Vec<Outcome<i32, &str>> = vec![
            Outcome::Err("e1"),
            Outcome::Cancelled(CancelReason::timeout()),
            Outcome::Ok(42), // Never reached
        ];
        let result = first_ok_outcomes(outcomes);

        assert!(!result.is_success());
        assert!(result.was_cancelled);
        // The Ok at index 2 is not processed
        assert_eq!(result.failures.len(), 2);
    }

    #[test]
    fn first_ok_panic_stops() {
        let outcomes: Vec<Outcome<i32, &str>> = vec![
            Outcome::Err("e1"),
            Outcome::Panicked(PanicPayload::new("boom")),
            Outcome::Ok(42), // Never reached
        ];
        let result = first_ok_outcomes(outcomes);

        assert!(!result.is_success());
        assert!(result.had_panic);
        assert_eq!(result.failures.len(), 2);
    }

    #[test]
    fn first_ok_to_result_success() {
        let outcomes: Vec<Outcome<i32, &str>> = vec![Outcome::Err("e1"), Outcome::Ok(42)];
        let result = first_ok_outcomes(outcomes);
        let value = first_ok_to_result(result);

        assert!(value.is_ok());
        assert_eq!(value.unwrap(), 42);
    }

    #[test]
    fn first_ok_to_result_all_failed() {
        let outcomes: Vec<Outcome<i32, &str>> = vec![Outcome::Err("e1"), Outcome::Err("e2")];
        let result = first_ok_outcomes(outcomes);
        let value = first_ok_to_result(result);

        assert!(value.is_err());
        match value.unwrap_err() {
            FirstOkError::AllFailed { errors, attempted } => {
                assert_eq!(errors.len(), 2);
                assert_eq!(attempted, 2);
            }
            _ => panic!("Expected AllFailed"),
        }
    }

    #[test]
    fn first_ok_to_result_cancelled() {
        let outcomes: Vec<Outcome<i32, &str>> = vec![
            Outcome::Err("e1"),
            Outcome::Cancelled(CancelReason::timeout()),
        ];
        let result = first_ok_outcomes(outcomes);
        let value = first_ok_to_result(result);

        assert!(value.is_err());
        match value.unwrap_err() {
            FirstOkError::Cancelled {
                errors_before_cancel,
                attempted_before_cancel,
                ..
            } => {
                assert_eq!(errors_before_cancel.len(), 1);
                assert_eq!(attempted_before_cancel, 1);
            }
            _ => panic!("Expected Cancelled"),
        }
    }

    #[test]
    fn first_ok_to_result_panicked() {
        let outcomes: Vec<Outcome<i32, &str>> = vec![Outcome::Panicked(PanicPayload::new("boom"))];
        let result = first_ok_outcomes(outcomes);
        let value = first_ok_to_result(result);

        assert!(value.is_err());
        assert!(matches!(value.unwrap_err(), FirstOkError::Panicked(_)));
    }

    #[test]
    fn first_ok_to_result_empty() {
        let outcomes: Vec<Outcome<i32, &str>> = vec![];
        let result = first_ok_outcomes(outcomes);
        let value = first_ok_to_result(result);

        assert!(value.is_err());
        assert!(matches!(value.unwrap_err(), FirstOkError::Empty));
    }

    #[test]
    fn first_ok_error_display() {
        let err: FirstOkError<&str> = FirstOkError::AllFailed {
            errors: vec!["e1", "e2"],
            attempted: 2,
        };
        assert!(err.to_string().contains("2 operations failed"));

        let err: FirstOkError<&str> = FirstOkError::Cancelled {
            reason: CancelReason::timeout(),
            errors_before_cancel: vec!["e1"],
            attempted_before_cancel: 2,
        };
        assert!(err.to_string().contains("cancelled"));

        let err: FirstOkError<&str> = FirstOkError::Panicked(PanicPayload::new("boom"));
        assert!(err.to_string().contains("panicked"));

        let err: FirstOkError<&str> = FirstOkError::Empty;
        assert!(err.to_string().contains("no operations"));
    }

    #[test]
    fn first_ok_still_possible_test() {
        // Not cancelled, not panicked, has remaining
        assert!(first_ok_still_possible(false, false, 3));

        // Not cancelled, not panicked, no remaining
        assert!(!first_ok_still_possible(false, false, 0));

        // Cancelled
        assert!(!first_ok_still_possible(true, false, 3));

        // Panicked
        assert!(!first_ok_still_possible(false, true, 3));

        // Both
        assert!(!first_ok_still_possible(true, true, 3));
    }

    #[test]
    fn first_ok_attempts_count() {
        // Success at index 1 means 2 attempts
        let outcomes: Vec<Outcome<i32, &str>> =
            vec![Outcome::Err("e1"), Outcome::Ok(42), Outcome::Err("e3")];
        let result = first_ok_outcomes(outcomes);
        assert_eq!(result.attempts(), 2);

        // All fail means attempts == failures.len()
        let outcomes: Vec<Outcome<i32, &str>> = vec![Outcome::Err("e1"), Outcome::Err("e2")];
        let result = first_ok_outcomes(outcomes);
        assert_eq!(result.attempts(), 2);
    }

    #[test]
    fn first_ok_preserves_failure_indices() {
        let outcomes: Vec<Outcome<i32, &str>> =
            vec![Outcome::Err("e0"), Outcome::Err("e1"), Outcome::Ok(2)];
        let result = first_ok_outcomes(outcomes);

        assert!(result.is_success());
        assert_eq!(result.failures.len(), 2);
        assert_eq!(result.failures[0].0, 0);
        assert_eq!(result.failures[1].0, 1);
    }

    // Semantic property tests
    #[test]
    fn first_ok_short_circuits() {
        // After first success, later outcomes don't affect result
        let outcomes1: Vec<Outcome<i32, &str>> =
            vec![Outcome::Err("e"), Outcome::Ok(1), Outcome::Ok(2)];
        let outcomes2: Vec<Outcome<i32, &str>> =
            vec![Outcome::Err("e"), Outcome::Ok(1), Outcome::Err("ignored")];

        let r1 = first_ok_outcomes(outcomes1);
        let r2 = first_ok_outcomes(outcomes2);

        // Both should have same success
        assert_eq!(
            r1.success.as_ref().unwrap().value,
            r2.success.as_ref().unwrap().value
        );
        assert_eq!(
            r1.success.as_ref().unwrap().index,
            r2.success.as_ref().unwrap().index
        );
    }

    #[test]
    fn first_ok_macro_returns_first_success() {
        let result = futures_lite::future::block_on(first_ok!(
            async { Outcome::<i32, &str>::Err("e1") },
            async { Outcome::<i32, &str>::Ok(42) },
            async { Outcome::<i32, &str>::Err("never reached") },
        ));

        assert!(result.is_success());
        let success = result.success.expect("success expected");
        assert_eq!(success.index, 1);
        assert_eq!(success.value, 42);
        assert_eq!(result.failures.len(), 1);
    }

    #[test]
    fn first_ok_macro_short_circuits_late_operations() {
        let touched = Arc::new(AtomicUsize::new(0));
        let touched_late = Arc::clone(&touched);
        let result = futures_lite::future::block_on(first_ok!(
            async { Outcome::<i32, &str>::Err("e1") },
            async { Outcome::<i32, &str>::Ok(7) },
            async move {
                touched_late.fetch_add(1, Ordering::Relaxed);
                Outcome::<i32, &str>::Err("late")
            },
        ));

        assert!(result.is_success());
        assert_eq!(touched.load(Ordering::Relaxed), 0);
    }

    #[test]
    fn first_ok_macro_stops_on_cancelled() {
        let result = futures_lite::future::block_on(first_ok!(
            async { Outcome::<i32, &str>::Err("e1") },
            async { Outcome::<i32, &str>::Cancelled(CancelReason::timeout()) },
            async { Outcome::<i32, &str>::Ok(99) },
        ));

        assert!(!result.is_success());
        assert!(result.was_cancelled);
        assert_eq!(result.failures.len(), 2);
    }

    #[test]
    fn first_ok_err_after_success_not_collected() {
        // Errors after the first success are not collected
        let outcomes: Vec<Outcome<i32, &str>> =
            vec![Outcome::Ok(1), Outcome::Err("e2"), Outcome::Err("e3")];
        let result = first_ok_outcomes(outcomes);

        assert!(result.is_success());
        // No failures collected because first succeeded
        assert!(result.failures.is_empty());
    }

    #[test]
    fn first_ok_vs_race_semantic_difference() {
        // In first_ok, a failing operation before success doesn't win
        // This is different from race where first completion wins
        let outcomes: Vec<Outcome<i32, &str>> = vec![Outcome::Err("fast_error"), Outcome::Ok(42)];

        let result = first_ok_outcomes(outcomes);

        // first_ok: second operation wins because it's Ok
        assert!(result.is_success());
        assert_eq!(result.success.unwrap().value, 42);

        // In race, the first to complete (Err) would win
        // This test documents the semantic difference
    }

    // --- wave 79 trait coverage ---

    #[test]
    fn first_ok_error_debug_clone() {
        let e: FirstOkError<&str> = FirstOkError::AllFailed {
            errors: vec!["e1", "e2"],
            attempted: 2,
        };
        let e2 = e.clone();
        let dbg = format!("{e:?}");
        assert!(dbg.contains("AllFailed"));
        let dbg2 = format!("{e2:?}");
        assert!(dbg2.contains("AllFailed"));
    }

    #[test]
    fn first_ok_failure_debug_clone() {
        let f: FirstOkFailure<&str> = FirstOkFailure::Error("msg");
        let f2 = f.clone();
        let dbg = format!("{f:?}");
        assert!(dbg.contains("Error"));
        let dbg2 = format!("{f2:?}");
        assert!(dbg2.contains("Error"));
    }
}