asupersync 0.3.0

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
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
#![allow(clippy::all)]
//! Metamorphic Testing: Scope.race loser-drain correctness
//!
//! This module implements metamorphic relations (MRs) to verify that Scope::race
//! and Scope::race_all maintain critical structured concurrency invariants across
//! different execution orderings, cancellation scenarios, and panic conditions.
//!
//! # Metamorphic Relations
//!
//! - **MR1 (Loser Drain Completeness)**: All loser futures are cancelled AND
//!   drained to quiescence before race returns
//! - **MR2 (Panic Isolation)**: Loser panics during drain don't escape Scope::race
//! - **MR3 (Branch Outcome Consistency)**: Race with N branches where winner is
//!   branch-k leaves all other N-1 in Cancelled outcome
//! - **MR4 (Cancel Propagation Consistency)**: Cancelling the whole race mid-flight
//!   returns Cancelled for all branches
//! - **MR5 (Seed Replay Consistency)**: Re-running the same seeded race preserves
//!   loser drain order and stays within the same bounded poll budget
//!
//! # Property Coverage
//!
//! These MRs ensure that:
//! - Structured concurrency invariant #4: "losers are drained" is preserved
//! - Panic handling doesn't violate cancellation protocol
//! - Branch outcomes are deterministic and consistent
//! - Whole-race cancellation propagates correctly to all participants
//!
//! # Testing Strategy
//!
//! Uses LabRuntime + proptest with DPOR schedule exploration to systematically
//! explore different execution interleavings and verify invariants hold across
//! all possible schedules.

#![allow(dead_code)]

use crate::cx::Cx;
use crate::types::cancel::CancelReason;
use crate::types::{Budget, Outcome, RegionId, TaskId};
use crate::util::{ArenaIndex, DetRng};
use proptest::prelude::*;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicUsize, Ordering};
use std::task::{Context, Poll, Waker};

// ============================================================================
// Test Infrastructure
// ============================================================================

/// Test future that can be configured for various behaviors
struct TestFuture {
    /// Unique identifier for this future
    id: u32,
    /// Value to return when completing successfully
    value: i32,
    /// Number of polls before completing (simulates work)
    polls_to_complete: AtomicU32,
    /// Whether this future should panic during execution
    should_panic: bool,
    /// Whether this future should panic during drain
    should_panic_during_drain: bool,
    /// Tracks if cancellation was requested
    cancelled: AtomicBool,
    /// Cancel reason if cancelled
    cancel_reason: parking_lot::Mutex<Option<CancelReason>>,
    /// Track completion state
    completed: AtomicBool,
    /// Track drain state
    drained: AtomicBool,
    /// Global state for tracking across all futures
    global_state: Arc<GlobalTestState>,
}

impl TestFuture {
    fn new(
        id: u32,
        value: i32,
        polls_to_complete: u32,
        global_state: Arc<GlobalTestState>,
    ) -> Self {
        Self {
            id,
            value,
            polls_to_complete: AtomicU32::new(polls_to_complete),
            should_panic: false,
            should_panic_during_drain: false,
            cancelled: AtomicBool::new(false),
            cancel_reason: parking_lot::Mutex::new(None),
            completed: AtomicBool::new(false),
            drained: AtomicBool::new(false),
            global_state,
        }
    }

    fn with_panic(mut self) -> Self {
        self.should_panic = true;
        self
    }

    fn with_drain_panic(mut self) -> Self {
        self.should_panic_during_drain = true;
        self
    }

    /// Cancel this future with the given reason
    fn cancel(&self, reason: CancelReason) {
        self.cancelled.store(true, Ordering::SeqCst);
        *self.cancel_reason.lock() = Some(reason);
        self.global_state.on_future_cancelled(self.id);
    }

    /// Check if this future is cancelled
    fn is_cancelled(&self) -> bool {
        self.cancelled.load(Ordering::SeqCst)
    }
}

impl Future for TestFuture {
    type Output = i32;

    fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = self.get_mut();

        // Register poll attempt
        this.global_state.on_future_polled(this.id);

        // Check for cancellation first
        if this.is_cancelled() {
            // If should panic during drain, do so
            if this.should_panic_during_drain {
                this.global_state.on_future_drain_panic(this.id);
                panic!("drain panic in future {}", this.id);
            }

            // Mark as drained and return cancelled
            this.drained.store(true, Ordering::SeqCst);
            this.global_state.on_future_drained(this.id);
            return Poll::Ready(this.value); // Simulated cancellation
        }

        // Check for panic during normal execution
        if this.should_panic {
            this.global_state.on_future_execution_panic(this.id);
            panic!("execution panic in future {}", this.id);
        }

        // Simulate work by counting down polls
        let remaining = this.polls_to_complete.load(Ordering::SeqCst);
        if remaining > 0 {
            this.polls_to_complete
                .store(remaining - 1, Ordering::SeqCst);
            Poll::Pending
        } else {
            // Complete successfully
            this.completed.store(true, Ordering::SeqCst);
            this.global_state.on_future_completed(this.id, this.value);
            Poll::Ready(this.value)
        }
    }
}

/// Global state tracker for all test futures
#[derive(Debug, Default)]
struct GlobalTestState {
    /// Futures that have been polled
    polled_futures: parking_lot::Mutex<Vec<u32>>,
    /// Futures that have completed successfully
    completed_futures: parking_lot::Mutex<Vec<(u32, i32)>>,
    /// Futures that have been cancelled
    cancelled_futures: parking_lot::Mutex<Vec<u32>>,
    /// Futures that have been drained
    drained_futures: parking_lot::Mutex<Vec<u32>>,
    /// Futures that panicked during execution
    execution_panics: parking_lot::Mutex<Vec<u32>>,
    /// Futures that panicked during drain
    drain_panics: parking_lot::Mutex<Vec<u32>>,
    /// Total number of polls across all futures
    total_polls: AtomicUsize,
    /// Race operation count
    race_operations: AtomicUsize,
}

impl GlobalTestState {
    fn new() -> Arc<Self> {
        Arc::new(Self::default())
    }

    fn on_future_polled(&self, id: u32) {
        self.polled_futures.lock().push(id);
        self.total_polls.fetch_add(1, Ordering::SeqCst);
    }

    fn on_future_completed(&self, id: u32, value: i32) {
        self.completed_futures.lock().push((id, value));
    }

    fn on_future_cancelled(&self, id: u32) {
        self.cancelled_futures.lock().push(id);
    }

    fn on_future_drained(&self, id: u32) {
        self.drained_futures.lock().push(id);
    }

    fn on_future_execution_panic(&self, id: u32) {
        self.execution_panics.lock().push(id);
    }

    fn on_future_drain_panic(&self, id: u32) {
        self.drain_panics.lock().push(id);
    }

    fn on_race_operation(&self) {
        self.race_operations.fetch_add(1, Ordering::SeqCst);
    }

    fn drain_order(&self) -> Vec<u32> {
        self.drained_futures.lock().clone()
    }

    /// Get all futures that were cancelled but not drained (invariant violation)
    fn get_undrained_losers(&self) -> Vec<u32> {
        let cancelled = self.cancelled_futures.lock();
        let drained = self.drained_futures.lock();
        cancelled
            .iter()
            .filter(|&&id| !drained.contains(&id))
            .copied()
            .collect()
    }

    /// Check if all cancelled futures were eventually drained
    fn all_cancelled_futures_drained(&self) -> bool {
        self.get_undrained_losers().is_empty()
    }

    /// Get statistics for analysis
    fn get_stats(&self) -> TestStats {
        TestStats {
            total_polls: self.total_polls.load(Ordering::SeqCst),
            completed_count: self.completed_futures.lock().len(),
            cancelled_count: self.cancelled_futures.lock().len(),
            drained_count: self.drained_futures.lock().len(),
            execution_panics_count: self.execution_panics.lock().len(),
            drain_panics_count: self.drain_panics.lock().len(),
            race_operations_count: self.race_operations.load(Ordering::SeqCst),
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
struct TestStats {
    total_polls: usize,
    completed_count: usize,
    cancelled_count: usize,
    drained_count: usize,
    execution_panics_count: usize,
    drain_panics_count: usize,
    race_operations_count: usize,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct SeededDrainSimulation {
    winner_completed: bool,
    all_cancelled_futures_drained: bool,
    drain_order: Vec<u32>,
    total_polls: usize,
}

/// Create a test context with deterministic IDs
fn create_test_context(region_id: u32, task_id: u32) -> Cx {
    Cx::new(
        RegionId::from_arena(ArenaIndex::new(region_id, 0)),
        TaskId::from_arena(ArenaIndex::new(task_id, 0)),
        Budget::INFINITE,
    )
}

/// Simple block-on implementation for testing
fn block_on<F: Future>(f: F) -> F::Output {
    let waker = Waker::from(Arc::new(TestWaker));
    let mut cx = Context::from_waker(&waker);
    let mut pinned = Box::pin(f);
    loop {
        match pinned.as_mut().poll(&mut cx) {
            Poll::Ready(v) => return v,
            Poll::Pending => {
                // In a real implementation, we'd use LabRuntime here
                // For now, yield to simulate scheduling
                std::thread::yield_now();
            }
        }
    }
}

#[derive(Debug)]
struct TestWaker;

impl std::task::Wake for TestWaker {
    fn wake(self: Arc<Self>) {
        // No-op for simple testing
    }
}

fn poll_test_future(future: &mut TestFuture) -> Poll<i32> {
    let waker = Waker::from(Arc::new(TestWaker));
    let mut cx = Context::from_waker(&waker);
    Pin::new(future).poll(&mut cx)
}

fn next_seeded_order(branch_count: usize, rng: &mut DetRng) -> Vec<usize> {
    let mut order = (0..branch_count).collect::<Vec<_>>();
    rng.shuffle(&mut order);
    order
}

fn run_seeded_loser_drain_simulation(
    branch_count: usize,
    winner_index: usize,
    loser_poll_counts: &[u32],
    seed: u64,
) -> SeededDrainSimulation {
    let global_state = GlobalTestState::new();
    let mut rng = DetRng::new(seed);

    let mut futures = Vec::with_capacity(branch_count);
    for i in 0..branch_count {
        let polls = if i == winner_index {
            1
        } else {
            loser_poll_counts[i % loser_poll_counts.len()]
        };
        futures.push(TestFuture::new(
            i as u32,
            (i * 10) as i32,
            polls,
            global_state.clone(),
        ));
    }

    global_state.on_race_operation();

    let mut winner_completed = false;
    while !winner_completed {
        for index in next_seeded_order(branch_count, &mut rng) {
            let future = &mut futures[index];
            if future.completed.load(Ordering::SeqCst) || future.is_cancelled() {
                continue;
            }

            if let Poll::Ready(_) = poll_test_future(future) {
                if index == winner_index {
                    winner_completed = true;
                    for (loser_index, other) in futures.iter().enumerate() {
                        if loser_index != index {
                            other.cancel(CancelReason::race_loser());
                        }
                    }
                    break;
                }
            }
        }
    }

    let mut drain_indices = (0..branch_count)
        .filter(|index| *index != winner_index)
        .collect::<Vec<_>>();
    rng.shuffle(&mut drain_indices);

    for index in drain_indices {
        let future = &mut futures[index];
        if future.is_cancelled() && !future.drained.load(Ordering::SeqCst) {
            let poll = poll_test_future(future);
            debug_assert!(poll.is_ready(), "cancelled futures must drain immediately");
        }
    }

    let stats = global_state.get_stats();
    SeededDrainSimulation {
        winner_completed,
        all_cancelled_futures_drained: global_state.all_cancelled_futures_drained(),
        drain_order: global_state.drain_order(),
        total_polls: stats.total_polls,
    }
}

// ============================================================================
// Metamorphic Relation Tests
// ============================================================================

/// **MR1: Loser Drain Completeness**
///
/// All loser futures are cancelled AND drained to quiescence before race returns.
/// This verifies the core structured concurrency invariant.
fn mr1_loser_drain_completeness(
    branch_count: usize,
    winner_index: usize,
    loser_poll_counts: Vec<u32>,
    seed: u64,
) -> bool {
    let simulation =
        run_seeded_loser_drain_simulation(branch_count, winner_index, &loser_poll_counts, seed);
    let poll_budget = branch_count * 3 - 1;
    let result = simulation.winner_completed
        && simulation.all_cancelled_futures_drained
        && simulation.total_polls <= poll_budget;

    crate::assert_with_log!(
        result,
        "MR1: winner completes and every cancelled loser drains within the bounded poll budget",
        true,
        result
    );

    result
}

/// **MR2: Panic Isolation**
///
/// Loser panics during drain don't escape Scope::race.
/// The race should handle drain panics gracefully and still complete.
fn mr2_panic_isolation(
    branch_count: usize,
    winner_index: usize,
    panic_loser_indices: Vec<usize>,
    _seed: u64,
) -> bool {
    let global_state = GlobalTestState::new();

    // Create test futures - some losers panic during drain
    let mut futures = Vec::new();
    for i in 0..branch_count {
        let mut future = TestFuture::new(
            i as u32,
            (i * 10) as i32,
            if i == winner_index { 1 } else { 5 },
            global_state.clone(),
        );
        if panic_loser_indices.contains(&i) {
            future = future.with_drain_panic();
        }
        futures.push(future);
    }

    global_state.on_race_operation();

    // Simulate race with panic handling
    // Use std::panic::catch_unwind to catch drain panics
    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        // Simplified race simulation
        let winner_value = loop {
            let waker = Waker::from(Arc::new(TestWaker));
            let mut cx = Context::from_waker(&waker);
            let mut pinned = Pin::new(&mut futures[winner_index]);
            match pinned.as_mut().poll(&mut cx) {
                Poll::Ready(val) => break val,
                Poll::Pending => {}
            }
        };

        // Cancel and drain losers (some may panic)
        for (i, future) in futures.iter_mut().enumerate() {
            if i != winner_index {
                future.cancel(CancelReason::race_loser());
                // Attempt to drain - may panic
                let _drain_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                    let waker = Waker::from(Arc::new(TestWaker));
                    let mut cx = Context::from_waker(&waker);
                    let mut pinned = Pin::new(future);
                    loop {
                        match pinned.as_mut().poll(&mut cx) {
                            Poll::Ready(_) => break,
                            Poll::Pending => {}
                        }
                    }
                }));
            }
        }

        winner_value
    }));

    // **MR2 Verification**: Race should complete successfully despite drain panics
    let race_completed = result.is_ok();
    let isolation_maintained = race_completed; // Race completed despite panics

    crate::assert_with_log!(
        isolation_maintained,
        "MR2: Panic isolation maintained",
        true,
        isolation_maintained
    );

    isolation_maintained
}

/// **MR3: Branch Outcome Consistency**
///
/// Race with N branches where winner is branch-k leaves all other N-1 in Cancelled outcome.
fn mr3_branch_outcome_consistency(branch_count: usize, winner_index: usize, _seed: u64) -> bool {
    let global_state = GlobalTestState::new();

    // Create N test futures
    let mut futures = Vec::new();
    for i in 0..branch_count {
        let future = TestFuture::new(
            i as u32,
            (i * 10) as i32,
            if i == winner_index { 1 } else { 10 }, // Winner completes quickly
            global_state.clone(),
        );
        futures.push(future);
    }

    global_state.on_race_operation();

    // Simulate race execution
    let mut outcomes: Vec<Option<Outcome<i32, ()>>> = vec![None; branch_count];
    let mut winner_completed = false;

    // Poll until winner completes
    while !winner_completed {
        for (i, future) in futures.iter_mut().enumerate() {
            if outcomes[i].is_none() && !future.is_cancelled() {
                let waker = Waker::from(Arc::new(TestWaker));
                let mut cx = Context::from_waker(&waker);
                let mut pinned = Pin::new(future);
                match pinned.as_mut().poll(&mut cx) {
                    Poll::Ready(val) => {
                        outcomes[i] = Some(Outcome::Ok(val));
                        if i == winner_index {
                            winner_completed = true;
                            // Cancel all losers
                            for (j, other) in futures.iter().enumerate() {
                                if j != i {
                                    other.cancel(CancelReason::race_loser());
                                    outcomes[j] =
                                        Some(Outcome::Cancelled(CancelReason::race_loser()));
                                }
                            }
                        }
                        break;
                    }
                    Poll::Pending => {}
                }
            }
        }
    }

    // **MR3 Verification**: Winner should be Ok, all others should be Cancelled
    let winner_outcome_correct = matches!(outcomes[winner_index], Some(Outcome::Ok(_)));
    let losers_cancelled = (0..branch_count)
        .filter(|&i| i != winner_index)
        .all(|i| matches!(outcomes[i], Some(Outcome::Cancelled(_))));

    let consistency_maintained = winner_outcome_correct && losers_cancelled;

    crate::assert_with_log!(
        consistency_maintained,
        "MR3: Branch outcome consistency maintained",
        true,
        consistency_maintained
    );

    consistency_maintained
}

/// **MR4: Cancel Propagation Consistency**
///
/// Cancelling the whole race mid-flight returns Cancelled for all branches.
fn mr4_cancel_propagation_consistency(
    branch_count: usize,
    cancel_after_polls: u32,
    _seed: u64,
) -> bool {
    let global_state = GlobalTestState::new();

    // Create N test futures that all take a while to complete
    let mut futures = Vec::new();
    for i in 0..branch_count {
        let future = TestFuture::new(i as u32, (i * 10) as i32, 20, global_state.clone()); // All take 20 polls
        futures.push(future);
    }

    global_state.on_race_operation();

    // Simulate race execution with external cancellation
    let mut outcomes: Vec<Option<Outcome<i32, ()>>> = vec![None; branch_count];
    let mut total_polls = 0;
    let race_cancel_reason = CancelReason::user("test race cancellation");

    // Poll futures until we reach the cancellation point
    while total_polls < cancel_after_polls {
        let mut any_completed = false;
        for (i, future) in futures.iter_mut().enumerate() {
            if outcomes[i].is_none() && !future.is_cancelled() {
                let waker = Waker::from(Arc::new(TestWaker));
                let mut cx = Context::from_waker(&waker);
                let mut pinned = Pin::new(future);
                match pinned.as_mut().poll(&mut cx) {
                    Poll::Ready(val) => {
                        outcomes[i] = Some(Outcome::Ok(val));
                        any_completed = true;
                    }
                    Poll::Pending => {}
                }
                total_polls += 1;
                if total_polls >= cancel_after_polls {
                    break;
                }
            }
        }
        if any_completed {
            // If any future completed naturally before cancellation,
            // that's a different scenario than whole-race cancellation
            break;
        }
    }

    // Cancel the whole race
    for (i, future) in futures.iter_mut().enumerate() {
        if outcomes[i].is_none() {
            future.cancel(race_cancel_reason.clone());
            outcomes[i] = Some(Outcome::Cancelled(race_cancel_reason.clone()));
        }
    }

    // Drain all cancelled futures
    for future in &mut futures {
        if future.is_cancelled() {
            let waker = Waker::from(Arc::new(TestWaker));
            let mut cx = Context::from_waker(&waker);
            let mut pinned = Pin::new(future);
            loop {
                match pinned.as_mut().poll(&mut cx) {
                    Poll::Ready(_) => break,
                    Poll::Pending => {}
                }
            }
        }
    }

    // **MR4 Verification**: All outcomes should be Cancelled (unless completed before cancellation)
    let cancelled_count = outcomes
        .iter()
        .filter(|outcome| matches!(outcome, Some(Outcome::Cancelled(_))))
        .count();
    let completed_count = outcomes
        .iter()
        .filter(|outcome| matches!(outcome, Some(Outcome::Ok(_))))
        .count();

    // If race was cancelled mid-flight, most/all futures should be cancelled
    let propagation_correct =
        cancelled_count > 0 && (cancelled_count + completed_count == branch_count);

    crate::assert_with_log!(
        propagation_correct,
        "MR4: Cancel propagation consistency maintained",
        true,
        propagation_correct
    );

    propagation_correct
}

/// **MR5: Seed Replay Consistency**
///
/// Re-running the same seeded race preserves loser drain order and overall poll budget.
fn mr5_seed_replay_preserves_loser_drain_order(
    branch_count: usize,
    winner_index: usize,
    loser_poll_counts: Vec<u32>,
    seed: u64,
) -> bool {
    let baseline =
        run_seeded_loser_drain_simulation(branch_count, winner_index, &loser_poll_counts, seed);
    let replay =
        run_seeded_loser_drain_simulation(branch_count, winner_index, &loser_poll_counts, seed);

    let deterministic = baseline == replay
        && baseline.drain_order.len() == branch_count - 1
        && !baseline.drain_order.contains(&(winner_index as u32));

    crate::assert_with_log!(
        deterministic,
        "MR5: replaying a fixed seed preserves loser drain order",
        true,
        deterministic
    );

    deterministic
}

// ============================================================================
// Property-Based Tests
// ============================================================================

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

    proptest! {
        /// Test MR1: Loser Drain Completeness
        #[test]
        fn test_mr1_loser_drain_completeness(
            branch_count in 2usize..=8,
            winner_index in 0usize..8,
            loser_polls in prop::collection::vec(1u32..10, 1..8),
            seed in any::<u64>(),
        ) {
            // Ensure winner_index is valid
            let winner_index = winner_index % branch_count;

            prop_assert!(mr1_loser_drain_completeness(
                branch_count,
                winner_index,
                loser_polls,
                seed
            ));
        }

        /// Test MR2: Panic Isolation
        #[test]
        fn test_mr2_panic_isolation(
            branch_count in 2usize..=6,
            winner_index in 0usize..6,
            panic_indices in prop::collection::vec(0usize..6, 0..3),
            seed in any::<u64>(),
        ) {
            let winner_index = winner_index % branch_count;
            let panic_indices: Vec<usize> = panic_indices.into_iter()
                .filter(|&i| i < branch_count && i != winner_index)
                .collect();

            prop_assert!(mr2_panic_isolation(
                branch_count,
                winner_index,
                panic_indices,
                seed
            ));
        }

        /// Test MR3: Branch Outcome Consistency
        #[test]
        fn test_mr3_branch_outcome_consistency(
            branch_count in 2usize..=8,
            winner_index in 0usize..8,
            seed in any::<u64>(),
        ) {
            let winner_index = winner_index % branch_count;

            prop_assert!(mr3_branch_outcome_consistency(
                branch_count,
                winner_index,
                seed
            ));
        }

        /// Test MR4: Cancel Propagation Consistency
        #[test]
        fn test_mr4_cancel_propagation_consistency(
            branch_count in 2usize..=8,
            cancel_after_polls in 1u32..10,
            seed in any::<u64>(),
        ) {
            prop_assert!(mr4_cancel_propagation_consistency(
                branch_count,
                cancel_after_polls,
                seed
            ));
        }

        /// Test MR5: re-running the same seeded race preserves loser drain order
        #[test]
        fn test_mr5_seed_replay_preserves_loser_drain_order(
            branch_count in 2usize..=8,
            winner_index in 0usize..8,
            loser_polls in prop::collection::vec(1u32..10, 1..8),
            seed in any::<u64>(),
        ) {
            let winner_index = winner_index % branch_count;

            prop_assert!(mr5_seed_replay_preserves_loser_drain_order(
                branch_count,
                winner_index,
                loser_polls,
                seed
            ));
        }
    }

    /// Comprehensive integration test combining all MRs
    #[test]
    fn test_race_metamorphic_integration() {
        let global_state = GlobalTestState::new();

        // Test scenario: 4-way race with various conditions
        let branch_count = 4;
        let winner_index = 1; // Second branch wins
        let seed = 12345;

        // Create futures with different characteristics
        let mut futures = Vec::new();
        for i in 0..branch_count {
            let polls = if i == winner_index { 2 } else { 8 + i as u32 };
            let mut future =
                TestFuture::new(i as u32, (i * 100) as i32, polls, global_state.clone());

            // Make one loser panic during drain
            if i == 3 {
                future = future.with_drain_panic();
            }

            futures.push(future);
        }

        // Test all MRs in sequence
        assert!(mr1_loser_drain_completeness(
            branch_count,
            winner_index,
            vec![8, 9, 10],
            seed
        ));
        assert!(mr2_panic_isolation(
            branch_count,
            winner_index,
            vec![3],
            seed
        ));
        assert!(mr3_branch_outcome_consistency(
            branch_count,
            winner_index,
            seed
        ));
        assert!(mr4_cancel_propagation_consistency(branch_count, 5, seed));
        assert!(mr5_seed_replay_preserves_loser_drain_order(
            branch_count,
            winner_index,
            vec![8, 9, 10],
            seed
        ));
    }

    /// Test edge cases and boundary conditions
    #[test]
    fn test_race_edge_cases() {
        // Test minimum race size (2 branches)
        assert!(mr1_loser_drain_completeness(2, 0, vec![5], 1111));
        assert!(mr3_branch_outcome_consistency(2, 1, 2222));

        // Test maximum reasonable race size
        assert!(mr1_loser_drain_completeness(8, 3, vec![2, 4, 6], 3333));
        assert!(mr3_branch_outcome_consistency(8, 7, 4444));

        // Test immediate cancellation
        assert!(mr4_cancel_propagation_consistency(5, 1, 5555));

        // Test late cancellation
        assert!(mr4_cancel_propagation_consistency(3, 15, 6666));

        // Same seed should preserve loser drain order
        assert!(mr5_seed_replay_preserves_loser_drain_order(
            5,
            2,
            vec![3, 4, 5],
            7777
        ));
    }
}