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
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
#![allow(clippy::all)]
//! Metamorphic testing for Barrier wait correctness under spurious wakeups.
//!
//! This module implements comprehensive metamorphic relations for the `Barrier`
//! synchronization primitive, verifying that barrier behavior remains correct
//! under various execution interleavings, cancellation patterns, and spurious wakeup scenarios.
//!
//! # Metamorphic Relations
//!
//! 1. **Party Count Invariant** (MR1): N parties pass iff N wait() calls
//! 2. **Spurious Wakeup Preservation** (MR2): Spurious wakeup retry preserves party count
//! 3. **Drop Cleanup Correctness** (MR3): Drop-before-wait decrements count correctly
//! 4. **Deterministic Replay** (MR4): LabRuntime replay identical across seeds
//! 5. **Leader Election Determinism** (MR5): Leader promotion after last wait is deterministic
//!
//! # Testing Strategy
//!
//! Each metamorphic relation is implemented as a property-based test using `proptest`,
//! with configurable test scenarios including party counts, cancellation patterns,
//! spurious wakeup injection, and concurrent execution patterns.

#![allow(dead_code)]

use crate::cx::Cx;
use crate::lab::{LabConfig, LabRuntime};
use crate::sync::{Barrier, BarrierWaitError};
use crate::types::Budget;
use parking_lot::Mutex;
use proptest::prelude::*;
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::time::Duration;

/// Configuration for barrier metamorphic tests.
#[derive(Debug, Clone)]
pub struct BarrierTestConfig {
    /// Number of parties required for barrier.
    pub parties: usize,
    /// Whether to inject spurious wakeups.
    pub inject_spurious_wakeups: bool,
    /// Probability of cancelling a waiter mid-flight (0.0 to 1.0).
    pub cancel_probability: f64,
    /// Probability of dropping a waiter future without completion (0.0 to 1.0).
    pub drop_probability: f64,
    /// Random seed for deterministic test execution.
    pub seed: u64,
}

impl BarrierTestConfig {
    /// Creates a basic configuration for testing.
    pub fn basic(parties: usize, seed: u64) -> Self {
        Self {
            parties,
            inject_spurious_wakeups: false,
            cancel_probability: 0.0,
            drop_probability: 0.0,
            seed,
        }
    }

    /// Creates a stress configuration with cancellation and drops.
    pub fn with_cancellation(parties: usize, cancel_prob: f64, drop_prob: f64, seed: u64) -> Self {
        Self {
            parties,
            inject_spurious_wakeups: true,
            cancel_probability: cancel_prob,
            drop_probability: drop_prob,
            seed,
        }
    }
}

/// Test workunit representing a single party's interaction with the barrier.
#[derive(Debug, Clone)]
pub struct BarrierWorkUnit {
    /// Unique identifier for this work unit.
    pub id: usize,
    /// Whether this unit should be cancelled before completion.
    pub should_cancel: bool,
    /// Whether this unit should be dropped mid-wait.
    pub should_drop: bool,
    /// Delay before starting wait (milliseconds).
    pub start_delay_ms: u64,
}

impl BarrierWorkUnit {
    pub fn new(id: usize) -> Self {
        Self {
            id,
            should_cancel: false,
            should_drop: false,
            start_delay_ms: 0,
        }
    }

    pub fn with_cancel(mut self) -> Self {
        self.should_cancel = true;
        self
    }

    pub fn with_drop(mut self) -> Self {
        self.should_drop = true;
        self
    }

    pub fn with_delay(mut self, delay_ms: u64) -> Self {
        self.start_delay_ms = delay_ms;
        self
    }
}

/// Result of executing a barrier work unit.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BarrierWorkResult {
    /// Successfully completed barrier wait.
    Completed { is_leader: bool },
    /// Wait was cancelled.
    Cancelled,
    /// Future was dropped before completion.
    Dropped,
    /// Task panicked during execution.
    Panicked(String),
}

impl BarrierWorkResult {
    pub fn is_completed(&self) -> bool {
        matches!(self, Self::Completed { .. })
    }

    pub fn is_leader(&self) -> bool {
        matches!(self, Self::Completed { is_leader: true })
    }

    pub fn is_cancelled(&self) -> bool {
        matches!(self, Self::Cancelled)
    }

    pub fn is_dropped(&self) -> bool {
        matches!(self, Self::Dropped)
    }
}

/// Global state for coordinating barrier metamorphic tests.
#[derive(Debug)]
pub struct GlobalBarrierState {
    /// Results from each work unit execution.
    pub results: Mutex<HashMap<usize, BarrierWorkResult>>,
    /// Count of work units that completed successfully.
    pub completed_count: AtomicUsize,
    /// Count of work units that were cancelled.
    pub cancelled_count: AtomicUsize,
    /// Count of work units that were dropped.
    pub dropped_count: AtomicUsize,
    /// Count of leaders elected.
    pub leader_count: AtomicUsize,
    /// Whether any spurious wakeups were injected.
    pub spurious_wakeups_injected: AtomicBool,
}

impl GlobalBarrierState {
    pub fn new() -> Arc<Self> {
        Arc::new(Self {
            results: Mutex::new(HashMap::new()),
            completed_count: AtomicUsize::new(0),
            cancelled_count: AtomicUsize::new(0),
            dropped_count: AtomicUsize::new(0),
            leader_count: AtomicUsize::new(0),
            spurious_wakeups_injected: AtomicBool::new(false),
        })
    }

    pub fn record_result(&self, id: usize, result: BarrierWorkResult) {
        match &result {
            BarrierWorkResult::Completed { is_leader } => {
                self.completed_count.fetch_add(1, Ordering::SeqCst);
                if *is_leader {
                    self.leader_count.fetch_add(1, Ordering::SeqCst);
                }
            }
            BarrierWorkResult::Cancelled => {
                self.cancelled_count.fetch_add(1, Ordering::SeqCst);
            }
            BarrierWorkResult::Dropped => {
                self.dropped_count.fetch_add(1, Ordering::SeqCst);
            }
            BarrierWorkResult::Panicked(_) => {
                // Panics are handled separately and don't affect counts
            }
        }
        self.results.lock().insert(id, result);
    }

    pub fn summary(&self) -> BarrierTestSummary {
        BarrierTestSummary {
            total_units: self.results.lock().len(),
            completed: self.completed_count.load(Ordering::SeqCst),
            cancelled: self.cancelled_count.load(Ordering::SeqCst),
            dropped: self.dropped_count.load(Ordering::SeqCst),
            leaders: self.leader_count.load(Ordering::SeqCst),
            spurious_wakeups: self.spurious_wakeups_injected.load(Ordering::SeqCst),
        }
    }
}

/// Summary of barrier test execution.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BarrierTestSummary {
    pub total_units: usize,
    pub completed: usize,
    pub cancelled: usize,
    pub dropped: usize,
    pub leaders: usize,
    pub spurious_wakeups: bool,
}

impl BarrierTestSummary {
    /// Returns the effective party count (completed + dropped units that registered).
    pub fn effective_parties(&self) -> usize {
        // Dropped units may have registered before being dropped, affecting party count
        self.completed + self.dropped
    }

    /// Returns true if the barrier should have tripped.
    pub fn should_trip(&self, expected_parties: usize) -> bool {
        self.effective_parties() >= expected_parties
    }
}

/// Execute a barrier work unit within a LabRuntime task.
async fn execute_barrier_work_unit(
    cx: &Cx,
    barrier: &Barrier,
    work_unit: BarrierWorkUnit,
    config: &BarrierTestConfig,
    global_state: Arc<GlobalBarrierState>,
) {
    let id = work_unit.id;

    // Apply start delay if configured
    if work_unit.start_delay_ms > 0 {
        crate::time::sleep(cx.now(), Duration::from_millis(work_unit.start_delay_ms)).await;
    }

    // Simulate spurious wakeup injection if enabled
    if config.inject_spurious_wakeups {
        let mut rng = crate::util::det_rng::DetRng::new(config.seed.wrapping_add(id as u64));
        if rng.next_u64() % 10 == 0 {
            global_state
                .spurious_wakeups_injected
                .store(true, Ordering::SeqCst);
            futures_lite::future::yield_now().await;
        }
    }

    let result = if work_unit.should_cancel {
        // Cancel before or during wait
        cx.set_cancel_requested(true);
        match barrier.wait(cx).await {
            Ok(result) => BarrierWorkResult::Completed {
                is_leader: result.is_leader(),
            },
            Err(BarrierWaitError::Cancelled) => BarrierWorkResult::Cancelled,
            Err(BarrierWaitError::PolledAfterCompletion) => {
                BarrierWorkResult::Panicked("polled after completion".to_string())
            }
        }
    } else if work_unit.should_drop {
        // Start the wait, then drop the future (simulates select! cancellation)
        let wait_future = barrier.wait(cx);
        // Poll once to register with the barrier
        let _ = futures_lite::future::poll_once(wait_future).await;
        // Future is dropped here, triggering cleanup
        BarrierWorkResult::Dropped
    } else {
        // Normal completion path
        match barrier.wait(cx).await {
            Ok(result) => BarrierWorkResult::Completed {
                is_leader: result.is_leader(),
            },
            Err(BarrierWaitError::Cancelled) => BarrierWorkResult::Cancelled,
            Err(BarrierWaitError::PolledAfterCompletion) => {
                BarrierWorkResult::Panicked("polled after completion".to_string())
            }
        }
    };

    global_state.record_result(id, result);
}

// ================================================================
// METAMORPHIC RELATIONS
// ================================================================

/// MR1: Party Count Invariant
///
/// N parties pass iff N wait() calls. The barrier should trip exactly when
/// the required number of parties have arrived, regardless of execution order
/// or timing variations.
fn mr1_party_count_invariant(
    config: BarrierTestConfig,
    work_units: Vec<BarrierWorkUnit>,
) -> Result<(), String> {
    let lab_config = LabConfig::new(config.seed).worker_count(4);
    let mut runtime = LabRuntime::new(lab_config);
    let root = runtime.state.create_root_region(Budget::INFINITE);

    let barrier = Arc::new(Barrier::new(config.parties));
    let global_state = GlobalBarrierState::new();

    // Execute all work units concurrently
    for work_unit in work_units.iter() {
        let barrier_clone = Arc::clone(&barrier);
        let config_clone = config.clone();
        let global_state_clone = Arc::clone(&global_state);
        let work_unit_clone = work_unit.clone();

        let (task_id, _handle) = runtime
            .state
            .create_task(root, Budget::INFINITE, async move {
                let cx = Cx::new(
                    crate::types::RegionId::new_for_test(1, 0),
                    crate::types::TaskId::new_for_test(1, 0),
                    crate::types::Budget::INFINITE,
                );
                execute_barrier_work_unit(
                    &cx,
                    &barrier_clone,
                    work_unit_clone,
                    &config_clone,
                    global_state_clone,
                )
                .await;
            })
            .map_err(|e| format!("create task failed: {}", e))?;

        runtime.scheduler.lock().schedule(task_id, 0);
    }

    runtime.run_until_quiescent();
    let summary = global_state.summary();

    // MR1: Verify party count invariant
    let expected_completions = if summary.effective_parties() >= config.parties {
        config.parties.min(summary.completed + summary.dropped)
    } else {
        0
    };

    if summary.completed != expected_completions {
        return Err(format!(
            "MR1 violation: expected {} completions, got {}. Config: {:?}, Summary: {:?}",
            expected_completions, summary.completed, config, summary
        ));
    }

    // Verify exactly one leader per barrier trip
    let expected_leaders = usize::from(summary.completed > 0);
    if summary.leaders != expected_leaders {
        return Err(format!(
            "MR1 leader violation: expected {} leaders, got {}. Summary: {:?}",
            expected_leaders, summary.leaders, summary
        ));
    }

    Ok(())
}

/// MR2: Spurious Wakeup Preservation
///
/// Spurious wakeup retry preserves party count. Waker updates and re-polling
/// should not affect the fundamental barrier semantics or party counting.
fn mr2_spurious_wakeup_preservation(
    config: BarrierTestConfig,
    work_units: Vec<BarrierWorkUnit>,
) -> Result<(), String> {
    // Run the same scenario with and without spurious wakeups
    let config_no_spurious = BarrierTestConfig {
        inject_spurious_wakeups: false,
        ..config.clone()
    };
    let config_with_spurious = BarrierTestConfig {
        inject_spurious_wakeups: true,
        ..config
    };

    let summary1 = execute_barrier_scenario(config_no_spurious, work_units.clone())?;
    let summary2 = execute_barrier_scenario(config_with_spurious, work_units)?;

    // MR2: Core semantics should be preserved despite spurious wakeups
    if summary1.completed != summary2.completed {
        return Err(format!(
            "MR2 violation: spurious wakeups changed completion count. Without: {}, With: {}",
            summary1.completed, summary2.completed
        ));
    }

    if summary1.leaders != summary2.leaders {
        return Err(format!(
            "MR2 violation: spurious wakeups changed leader count. Without: {}, With: {}",
            summary1.leaders, summary2.leaders
        ));
    }

    Ok(())
}

/// MR3: Drop Cleanup Correctness
///
/// Drop-before-wait decrements count correctly. When a future is dropped
/// after registering but before completion, the barrier state should be
/// properly cleaned up for subsequent operations.
fn mr3_drop_cleanup_correctness(
    config: BarrierTestConfig,
    work_units: Vec<BarrierWorkUnit>,
) -> Result<(), String> {
    let lab_config = LabConfig::new(config.seed).worker_count(4);
    let mut runtime = LabRuntime::new(lab_config);
    let root = runtime.state.create_root_region(Budget::INFINITE);

    let barrier = Arc::new(Barrier::new(config.parties));
    let global_state = GlobalBarrierState::new();

    // Phase 1: Execute work units with drops
    for work_unit in work_units.iter() {
        let barrier_clone = Arc::clone(&barrier);
        let config_clone = config.clone();
        let global_state_clone = Arc::clone(&global_state);
        let work_unit_clone = work_unit.clone();

        let (task_id, _handle) = runtime
            .state
            .create_task(root, Budget::INFINITE, async move {
                let cx = Cx::new(
                    crate::types::RegionId::new_for_test(1, 0),
                    crate::types::TaskId::new_for_test(1, 0),
                    crate::types::Budget::INFINITE,
                );
                execute_barrier_work_unit(
                    &cx,
                    &barrier_clone,
                    work_unit_clone,
                    &config_clone,
                    global_state_clone,
                )
                .await;
            })
            .map_err(|e| format!("create task failed: {}", e))?;

        runtime.scheduler.lock().schedule(task_id, 0);
    }

    runtime.run_until_quiescent();
    let phase1_summary = global_state.summary();

    // Phase 2: Verify barrier is still functional with fresh parties
    if phase1_summary.completed < config.parties {
        let remaining_parties = config.parties;
        let fresh_global_state = GlobalBarrierState::new();

        for i in 0..remaining_parties {
            let barrier_clone = Arc::clone(&barrier);
            let fresh_global_state_clone = Arc::clone(&fresh_global_state);
            let fresh_work_unit = BarrierWorkUnit::new(1000 + i); // Different ID space

            let (task_id, _handle) = runtime
                .state
                .create_task(root, Budget::INFINITE, async move {
                    let cx = Cx::new(
                        crate::types::RegionId::new_for_test(1, 0),
                        crate::types::TaskId::new_for_test(1, 0),
                        crate::types::Budget::INFINITE,
                    );
                    match barrier_clone.wait(&cx).await {
                        Ok(result) => {
                            fresh_global_state_clone.record_result(
                                fresh_work_unit.id,
                                BarrierWorkResult::Completed {
                                    is_leader: result.is_leader(),
                                },
                            );
                        }
                        Err(_) => {
                            fresh_global_state_clone
                                .record_result(fresh_work_unit.id, BarrierWorkResult::Cancelled);
                        }
                    }
                })
                .map_err(|e| format!("create fresh task failed: {}", e))?;

            runtime.scheduler.lock().schedule(task_id, 0);
        }

        runtime.run_until_quiescent();
        let phase2_summary = fresh_global_state.summary();

        // MR3: Fresh parties should be able to trip the barrier normally
        if phase2_summary.completed != remaining_parties {
            return Err(format!(
                "MR3 violation: barrier not functional after drops. Expected {} fresh completions, got {}",
                remaining_parties, phase2_summary.completed
            ));
        }

        if phase2_summary.leaders != 1 {
            return Err(format!(
                "MR3 violation: incorrect leader count in fresh generation. Expected 1, got {}",
                phase2_summary.leaders
            ));
        }
    }

    Ok(())
}

/// MR4: Deterministic Replay
///
/// LabRuntime replay identical across seeds. The same barrier scenario
/// should produce identical results when run multiple times with the
/// same seed under LabRuntime's deterministic execution.
fn mr4_deterministic_replay(
    config: BarrierTestConfig,
    work_units: Vec<BarrierWorkUnit>,
) -> Result<(), String> {
    let summary1 = execute_barrier_scenario(config.clone(), work_units.clone())?;
    let summary2 = execute_barrier_scenario(config.clone(), work_units)?;

    // MR4: Identical execution should produce identical results
    if summary1 != summary2 {
        return Err(format!(
            "MR4 violation: non-deterministic behavior detected. Run 1: {:?}, Run 2: {:?}",
            summary1, summary2
        ));
    }

    Ok(())
}

/// MR5: Leader Election Determinism
///
/// Leader promotion after last wait is deterministic. When multiple parties
/// arrive concurrently, the same party should be elected leader across
/// multiple runs with the same seed.
fn mr5_leader_election_determinism(
    config: BarrierTestConfig,
    work_units: Vec<BarrierWorkUnit>,
) -> Result<(), String> {
    let mut leader_ids = Vec::new();

    // Run the scenario multiple times and collect leader IDs
    for _ in 0..3 {
        let summary =
            execute_barrier_scenario_with_leader_tracking(config.clone(), work_units.clone())?;
        leader_ids.push(summary);
    }

    // MR5: The same party should be elected leader each time
    if leader_ids.windows(2).any(|w| w[0] != w[1]) {
        return Err(format!(
            "MR5 violation: leader election non-deterministic. Leaders across runs: {:?}",
            leader_ids
        ));
    }

    Ok(())
}

/// Helper function to execute a barrier scenario and return summary.
fn execute_barrier_scenario(
    config: BarrierTestConfig,
    work_units: Vec<BarrierWorkUnit>,
) -> Result<BarrierTestSummary, String> {
    // Enable auto-advance + cap max_steps. Proptest-generated scenarios
    // routinely use `start_delay_ms > 0` (which calls `crate::time::sleep`)
    // and parties/drop/cancel ratios that can leave fewer live waiters
    // than `parties`, so the barrier never trips. Without auto-advance the
    // LabRuntime's virtual clock never moves past a timer deadline, sleeps
    // never resolve, and `run_until_quiescent` iterates for the default
    // max_steps=100_000 per scenario — a multi-minute effective hang that
    // trips CI timeouts (this test was one of the ~17 hangs cleaned up in
    // the post-release deep-dive).
    let lab_config = LabConfig::new(config.seed)
        .worker_count(4)
        .max_steps(5_000)
        .with_auto_advance();
    let mut runtime = LabRuntime::new(lab_config);
    let root = runtime.state.create_root_region(Budget::INFINITE);

    let barrier = Arc::new(Barrier::new(config.parties));
    let global_state = GlobalBarrierState::new();

    for work_unit in work_units {
        let barrier_clone = Arc::clone(&barrier);
        let config_clone = config.clone();
        let global_state_clone = Arc::clone(&global_state);

        let (task_id, _handle) = runtime
            .state
            .create_task(root, Budget::INFINITE, async move {
                let cx = Cx::new(
                    crate::types::RegionId::new_for_test(1, 0),
                    crate::types::TaskId::new_for_test(1, 0),
                    crate::types::Budget::INFINITE,
                );
                execute_barrier_work_unit(
                    &cx,
                    &barrier_clone,
                    work_unit,
                    &config_clone,
                    global_state_clone,
                )
                .await;
            })
            .map_err(|e| format!("create task failed: {}", e))?;

        runtime.scheduler.lock().schedule(task_id, 0);
    }

    let _ = runtime.run_with_auto_advance();
    Ok(global_state.summary())
}

/// Helper function with leader tracking for MR5.
fn execute_barrier_scenario_with_leader_tracking(
    config: BarrierTestConfig,
    work_units: Vec<BarrierWorkUnit>,
) -> Result<Vec<usize>, String> {
    let lab_config = LabConfig::new(config.seed).worker_count(4);
    let mut runtime = LabRuntime::new(lab_config);
    let root = runtime.state.create_root_region(Budget::INFINITE);

    let barrier = Arc::new(Barrier::new(config.parties));
    let leader_ids: Arc<Mutex<Vec<usize>>> = Arc::new(Mutex::new(Vec::new()));

    for work_unit in work_units {
        let barrier_clone = Arc::clone(&barrier);
        let leader_ids_clone = Arc::clone(&leader_ids);

        let (task_id, _handle) = runtime
            .state
            .create_task(root, Budget::INFINITE, async move {
                let cx = Cx::new(
                    crate::types::RegionId::new_for_test(1, 0),
                    crate::types::TaskId::new_for_test(1, 0),
                    crate::types::Budget::INFINITE,
                );
                if !work_unit.should_cancel && !work_unit.should_drop {
                    if let Ok(result) = barrier_clone.wait(&cx).await {
                        if result.is_leader() {
                            leader_ids_clone.lock().push(work_unit.id);
                        }
                    }
                }
            })
            .map_err(|e| format!("create task failed: {}", e))?;

        runtime.scheduler.lock().schedule(task_id, 0);
    }

    runtime.run_until_quiescent();
    Ok(leader_ids.lock().clone())
}

// ================================================================
// PROPTEST INTEGRATION
// ================================================================

/// Strategy for generating barrier test configurations.
fn barrier_config_strategy() -> impl Strategy<Value = BarrierTestConfig> {
    (
        1..=8_usize,   // parties
        any::<bool>(), // inject_spurious_wakeups
        0.0..0.3_f64,  // cancel_probability
        0.0..0.2_f64,  // drop_probability
        any::<u64>(),  // seed
    )
        .prop_map(
            |(parties, spurious, cancel_prob, drop_prob, seed)| BarrierTestConfig {
                parties,
                inject_spurious_wakeups: spurious,
                cancel_probability: cancel_prob,
                drop_probability: drop_prob,
                seed,
            },
        )
}

/// Strategy for generating work units.
fn work_units_strategy(max_units: usize) -> impl Strategy<Value = Vec<BarrierWorkUnit>> {
    prop::collection::vec(
        (
            any::<usize>(), // id
            any::<bool>(),  // should_cancel
            any::<bool>(),  // should_drop
            0..50_u64,      // start_delay_ms
        ),
        1..=max_units,
    )
    .prop_map(|units| {
        units
            .into_iter()
            .enumerate()
            .map(|(i, (_, should_cancel, should_drop, delay))| {
                let mut unit = BarrierWorkUnit::new(i);
                if should_cancel {
                    unit = unit.with_cancel();
                }
                if should_drop {
                    unit = unit.with_drop();
                }
                unit.with_delay(delay)
            })
            .collect()
    })
}

// ================================================================
// TEST FUNCTIONS
// ================================================================

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

    fn init_test(name: &str) {
        init_test_logging();
        crate::test_phase!(name);
    }

    /// Test MR1: Party Count Invariant
    #[test]
    fn mr1_party_count_invariant_basic() {
        init_test("mr1_party_count_invariant_basic");

        let config = BarrierTestConfig::basic(3, 42);
        let work_units = vec![
            BarrierWorkUnit::new(0),
            BarrierWorkUnit::new(1),
            BarrierWorkUnit::new(2),
        ];

        let result = mr1_party_count_invariant(config, work_units);
        crate::assert_with_log!(
            result.is_ok(),
            "MR1 basic scenario should pass",
            true,
            result.is_ok()
        );

        crate::test_complete!("mr1_party_count_invariant_basic");
    }

    /// Test MR2: Spurious Wakeup Preservation
    #[test]
    fn mr2_spurious_wakeup_preservation_basic() {
        init_test("mr2_spurious_wakeup_preservation_basic");

        let config = BarrierTestConfig::basic(2, 123);
        let work_units = vec![BarrierWorkUnit::new(0), BarrierWorkUnit::new(1)];

        let result = mr2_spurious_wakeup_preservation(config, work_units);
        crate::assert_with_log!(
            result.is_ok(),
            "MR2 basic scenario should pass",
            true,
            result.is_ok()
        );

        crate::test_complete!("mr2_spurious_wakeup_preservation_basic");
    }

    /// Test MR3: Drop Cleanup Correctness
    #[test]
    fn mr3_drop_cleanup_correctness_basic() {
        init_test("mr3_drop_cleanup_correctness_basic");

        let config = BarrierTestConfig::basic(3, 456);
        let work_units = vec![
            BarrierWorkUnit::new(0),
            BarrierWorkUnit::new(1).with_drop(),
            BarrierWorkUnit::new(2),
        ];

        let result = mr3_drop_cleanup_correctness(config, work_units);
        crate::assert_with_log!(
            result.is_ok(),
            "MR3 basic scenario should pass",
            true,
            result.is_ok()
        );

        crate::test_complete!("mr3_drop_cleanup_correctness_basic");
    }

    /// Test MR4: Deterministic Replay
    #[test]
    fn mr4_deterministic_replay_basic() {
        init_test("mr4_deterministic_replay_basic");

        let config = BarrierTestConfig::basic(2, 789);
        let work_units = vec![BarrierWorkUnit::new(0), BarrierWorkUnit::new(1)];

        let result = mr4_deterministic_replay(config, work_units);
        crate::assert_with_log!(
            result.is_ok(),
            "MR4 basic scenario should pass",
            true,
            result.is_ok()
        );

        crate::test_complete!("mr4_deterministic_replay_basic");
    }

    /// Test MR5: Leader Election Determinism
    #[test]
    fn mr5_leader_election_determinism_basic() {
        init_test("mr5_leader_election_determinism_basic");

        let config = BarrierTestConfig::basic(3, 999);
        let work_units = vec![
            BarrierWorkUnit::new(0),
            BarrierWorkUnit::new(1),
            BarrierWorkUnit::new(2),
        ];

        let result = mr5_leader_election_determinism(config, work_units);
        crate::assert_with_log!(
            result.is_ok(),
            "MR5 basic scenario should pass",
            true,
            result.is_ok()
        );

        crate::test_complete!("mr5_leader_election_determinism_basic");
    }

    proptest! {
        #[test]
        fn mr1_party_count_invariant_property(
            config in barrier_config_strategy(),
            work_units in work_units_strategy(10),
        ) {
            let result = mr1_party_count_invariant(config, work_units);
            prop_assert!(result.is_ok(), "MR1 property failed: {:?}", result);
        }

        #[test]
        fn mr2_spurious_wakeup_preservation_property(
            config in barrier_config_strategy().prop_filter("parties > 1", |c| c.parties > 1),
            work_units in work_units_strategy(8),
        ) {
            let result = mr2_spurious_wakeup_preservation(config, work_units);
            prop_assert!(result.is_ok(), "MR2 property failed: {:?}", result);
        }

        #[test]
        fn mr4_deterministic_replay_property(
            config in barrier_config_strategy(),
            work_units in work_units_strategy(6),
        ) {
            let result = mr4_deterministic_replay(config, work_units);
            prop_assert!(result.is_ok(), "MR4 property failed: {:?}", result);
        }
    }

    /// Stress test combining all metamorphic relations.
    #[test]
    fn barrier_metamorphic_stress_test() {
        init_test("barrier_metamorphic_stress_test");

        let config = BarrierTestConfig::with_cancellation(4, 0.1, 0.05, 12345);
        let work_units = vec![
            BarrierWorkUnit::new(0),
            BarrierWorkUnit::new(1).with_delay(5),
            BarrierWorkUnit::new(2).with_cancel(),
            BarrierWorkUnit::new(3),
            BarrierWorkUnit::new(4).with_drop(),
            BarrierWorkUnit::new(5),
        ];

        // Test all metamorphic relations
        let mr1_result = mr1_party_count_invariant(config.clone(), work_units.clone());
        let mr2_result = mr2_spurious_wakeup_preservation(config.clone(), work_units.clone());
        let mr4_result = mr4_deterministic_replay(config, work_units);

        crate::assert_with_log!(
            mr1_result.is_ok(),
            "MR1 stress test should pass",
            true,
            mr1_result.is_ok()
        );
        crate::assert_with_log!(
            mr2_result.is_ok(),
            "MR2 stress test should pass",
            true,
            mr2_result.is_ok()
        );
        crate::assert_with_log!(
            mr4_result.is_ok(),
            "MR4 stress test should pass",
            true,
            mr4_result.is_ok()
        );

        crate::test_complete!("barrier_metamorphic_stress_test");
    }
}