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
//! Comprehensive channel atomicity verification suite.
//!
//! This module provides the main entry point for verifying atomicity guarantees
//! across all channel types under various stress conditions, cancellation
//! scenarios, and edge cases.

#![allow(dead_code)]

use super::atomicity_test::{AtomicityOracle, AtomicityTestConfig};
use super::stress_test::{StressTestConfig, mpsc_stress_test};
use crate::channel::{broadcast, mpsc, oneshot, watch};
use crate::cx::Cx;
use crate::runtime::RuntimeBuilder;
use crate::time::{timeout, wall_now};

use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, Instant};

/// Comprehensive test suite configuration.
#[derive(Debug, Clone)]
pub struct VerificationSuiteConfig {
    /// Test all channel types.
    pub test_all_channels: bool,
    /// Include high-stress scenarios.
    pub include_stress_tests: bool,
    /// Include edge case scenarios.
    pub include_edge_cases: bool,
    /// Include cancellation timing tests.
    pub include_cancellation_tests: bool,
    /// Maximum time to spend on verification.
    pub max_duration: Duration,
    /// Fail fast on first violation.
    pub fail_fast: bool,
}

impl Default for VerificationSuiteConfig {
    fn default() -> Self {
        Self {
            test_all_channels: true,
            include_stress_tests: true,
            include_edge_cases: true,
            include_cancellation_tests: true,
            max_duration: Duration::from_secs(60),
            fail_fast: true,
        }
    }
}

/// Results from the complete verification suite.
#[derive(Debug, Clone)]
pub struct VerificationResult {
    /// Total test duration.
    pub total_duration: Duration,
    /// Number of test cases executed.
    pub tests_executed: usize,
    /// Number of test cases passed.
    pub tests_passed: usize,
    /// Results by test category.
    pub results_by_category: HashMap<String, CategoryResult>,
    /// Overall pass/fail status.
    pub overall_success: bool,
    /// Summary of any violations found.
    pub violation_summary: String,
}

/// Results for a category of tests.
#[derive(Debug, Clone)]
pub struct CategoryResult {
    /// Number of tests in this category.
    pub test_count: usize,
    /// Number of passed tests.
    pub passed_count: usize,
    /// Total messages processed.
    pub total_messages: u64,
    /// Average throughput.
    pub avg_throughput: f64,
    /// Any violations detected.
    pub violations: u64,
    /// Details of failures.
    pub failure_details: Vec<String>,
}

impl Default for CategoryResult {
    fn default() -> Self {
        Self {
            test_count: 0,
            passed_count: 0,
            total_messages: 0,
            avg_throughput: 0.0,
            violations: 0,
            failure_details: Vec::new(),
        }
    }
}

/// Main verification suite runner.
pub struct VerificationSuite {
    config: VerificationSuiteConfig,
    start_time: Instant,
    results: HashMap<String, CategoryResult>,
}

impl VerificationSuite {
    /// Creates a new verification suite with the given configuration.
    pub fn new(config: VerificationSuiteConfig) -> Self {
        Self {
            config,
            start_time: Instant::now(),
            results: HashMap::new(),
        }
    }

    /// Runs the complete verification suite.
    pub async fn run(&mut self) -> VerificationResult {
        let start_time = Instant::now();
        let mut total_tests = 0;
        let mut total_passed = 0;
        let mut overall_success = true;
        let mut violation_summary = String::new();

        // Test MPSC channels
        if self.config.test_all_channels {
            let (tests, passed, success) = self.test_mpsc_channels().await;
            total_tests += tests;
            total_passed += passed;
            if !success {
                overall_success = false;
                violation_summary.push_str("MPSC violations detected; ");
            }
        }

        // Test other channel types
        if self.config.test_all_channels {
            let (tests, passed, success) = self.test_other_channels().await;
            total_tests += tests;
            total_passed += passed;
            if !success {
                overall_success = false;
                violation_summary.push_str("Other channel violations detected; ");
            }
        }

        // Edge case testing
        if self.config.include_edge_cases {
            let (tests, passed, success) = self.test_edge_cases().await;
            total_tests += tests;
            total_passed += passed;
            if !success {
                overall_success = false;
                violation_summary.push_str("Edge case violations detected; ");
            }
        }

        // Cancellation timing tests
        if self.config.include_cancellation_tests {
            let (tests, passed, success) = self.test_cancellation_timing().await;
            total_tests += tests;
            total_passed += passed;
            if !success {
                overall_success = false;
                violation_summary.push_str("Cancellation timing violations detected; ");
            }
        }

        if violation_summary.is_empty() {
            violation_summary = "No violations detected".to_string();
        }

        VerificationResult {
            total_duration: start_time.elapsed(),
            tests_executed: total_tests,
            tests_passed: total_passed,
            results_by_category: self.results.clone(),
            overall_success,
            violation_summary,
        }
    }

    /// Test MPSC channel atomicity under various conditions.
    async fn test_mpsc_channels(&mut self) -> (usize, usize, bool) {
        let mut category = CategoryResult::default();
        let mut all_passed = true;

        println!("=== Testing MPSC Channel Atomicity ===");

        // Basic atomicity test
        category.test_count += 1;
        let basic_config = AtomicityTestConfig {
            capacity: 10,
            num_producers: 4,
            messages_per_producer: 100,
            cancel_probability: 0.0,
            check_invariants: true,
            ..Default::default()
        };

        if self.run_basic_mpsc_test(basic_config, "Basic MPSC").await {
            category.passed_count += 1;
            category.total_messages += 400;
        } else {
            all_passed = false;
            category
                .failure_details
                .push("Basic MPSC test failed".to_string());
        }

        // High concurrency test
        if self.config.include_stress_tests {
            category.test_count += 1;
            let stress_config = StressTestConfig {
                base: AtomicityTestConfig {
                    capacity: 16,
                    num_producers: 12,
                    messages_per_producer: 500,
                    cancel_probability: 0.15,
                    check_invariants: true,
                    ..Default::default()
                },
                stress_rounds: 3,
                round_duration: Duration::from_secs(4),
                escalating_cancellation: true,
            };

            match mpsc_stress_test(stress_config).await {
                Ok(result) => {
                    if result.atomicity_maintained {
                        category.passed_count += 1;
                        category.total_messages += result.total_messages;
                        category.avg_throughput += result.avg_throughput;
                        println!(
                            "  High concurrency MPSC: PASSED ({} msg/s)",
                            result.avg_throughput
                        );
                    } else {
                        all_passed = false;
                        category.violations += result.total_violations;
                        category.failure_details.push(format!(
                            "High concurrency MPSC failed: {} violations",
                            result.total_violations
                        ));
                    }
                }
                Err(e) => {
                    all_passed = false;
                    category
                        .failure_details
                        .push(format!("High concurrency MPSC error: {e}"));
                }
            }
        }

        // Extreme cancellation test
        if self.config.include_cancellation_tests {
            category.test_count += 1;
            let cancel_config = AtomicityTestConfig {
                capacity: 5,
                num_producers: 6,
                messages_per_producer: 200,
                cancel_probability: 0.6, // Very high cancellation rate
                check_invariants: true,
                ..Default::default()
            };

            if self
                .run_basic_mpsc_test(cancel_config, "Extreme Cancellation MPSC")
                .await
            {
                category.passed_count += 1;
                category.total_messages += 200; // Approximate due to cancellations
            } else {
                all_passed = false;
                category
                    .failure_details
                    .push("Extreme cancellation MPSC test failed".to_string());
            }
        }

        self.results.insert("MPSC".to_string(), category);
        (
            self.results["MPSC"].test_count,
            self.results["MPSC"].passed_count,
            all_passed,
        )
    }

    /// Test other channel types for basic correctness.
    async fn test_other_channels(&mut self) -> (usize, usize, bool) {
        let mut category = CategoryResult::default();
        let mut all_passed = true;

        println!("=== Testing Other Channel Types ===");

        // Oneshot channel test
        category.test_count += 1;
        if self.test_oneshot_atomicity().await {
            category.passed_count += 1;
            println!("  Oneshot channels: PASSED");
        } else {
            all_passed = false;
            category
                .failure_details
                .push("Oneshot test failed".to_string());
        }

        // Broadcast channel test
        category.test_count += 1;
        if self.test_broadcast_atomicity().await {
            category.passed_count += 1;
            println!("  Broadcast channels: PASSED");
        } else {
            all_passed = false;
            category
                .failure_details
                .push("Broadcast test failed".to_string());
        }

        // Watch channel test
        category.test_count += 1;
        if self.test_watch_atomicity().await {
            category.passed_count += 1;
            println!("  Watch channels: PASSED");
        } else {
            all_passed = false;
            category
                .failure_details
                .push("Watch test failed".to_string());
        }

        self.results.insert("Other".to_string(), category);
        (
            self.results["Other"].test_count,
            self.results["Other"].passed_count,
            all_passed,
        )
    }

    /// Test edge cases and boundary conditions.
    async fn test_edge_cases(&mut self) -> (usize, usize, bool) {
        let mut category = CategoryResult::default();
        let mut all_passed = true;

        println!("=== Testing Edge Cases ===");

        // Capacity-1 channel
        category.test_count += 1;
        let tiny_config = AtomicityTestConfig {
            capacity: 1,
            num_producers: 3,
            messages_per_producer: 50,
            cancel_probability: 0.2,
            check_invariants: true,
            ..Default::default()
        };

        if self
            .run_basic_mpsc_test(tiny_config, "Capacity-1 Channel")
            .await
        {
            category.passed_count += 1;
        } else {
            all_passed = false;
            category
                .failure_details
                .push("Capacity-1 test failed".to_string());
        }

        // Very large capacity channel
        category.test_count += 1;
        let large_config = AtomicityTestConfig {
            capacity: 1000,
            num_producers: 2,
            messages_per_producer: 100,
            cancel_probability: 0.05,
            check_invariants: true,
            ..Default::default()
        };

        if self
            .run_basic_mpsc_test(large_config, "Large Capacity Channel")
            .await
        {
            category.passed_count += 1;
        } else {
            all_passed = false;
            category
                .failure_details
                .push("Large capacity test failed".to_string());
        }

        self.results.insert("EdgeCases".to_string(), category);
        (
            self.results["EdgeCases"].test_count,
            self.results["EdgeCases"].passed_count,
            all_passed,
        )
    }

    /// Test cancellation timing scenarios.
    async fn test_cancellation_timing(&mut self) -> (usize, usize, bool) {
        let mut category = CategoryResult::default();
        let mut all_passed = true;

        println!("=== Testing Cancellation Timing ===");

        // Test cancellation during different phases
        for (phase_name, cancel_prob) in [
            ("Reserve Phase", 0.8),
            ("Commit Phase", 0.3),
            ("Mixed Timing", 0.5),
        ] {
            category.test_count += 1;
            let timing_config = AtomicityTestConfig {
                capacity: 8,
                num_producers: 4,
                messages_per_producer: 150,
                cancel_probability: cancel_prob,
                check_invariants: true,
                ..Default::default()
            };

            if self.run_basic_mpsc_test(timing_config, phase_name).await {
                category.passed_count += 1;
            } else {
                all_passed = false;
                category
                    .failure_details
                    .push(format!("{phase_name} test failed"));
            }
        }

        self.results
            .insert("CancellationTiming".to_string(), category);
        (
            self.results["CancellationTiming"].test_count,
            self.results["CancellationTiming"].passed_count,
            all_passed,
        )
    }

    /// Run a basic MPSC atomicity test with the given configuration.
    async fn run_basic_mpsc_test(&self, config: AtomicityTestConfig, test_name: &str) -> bool {
        let oracle = Arc::new(AtomicityOracle::new(config.clone()));
        let (sender, receiver) = mpsc::channel::<u32>(config.capacity);
        let expected_messages = config.num_producers * config.messages_per_producer;

        let test_result = match RuntimeBuilder::current_thread().build() {
            Ok(runtime) => {
                let handle = runtime.handle();
                let oracle_for_test = Arc::clone(&oracle);
                runtime.block_on(async move {
                    match timeout(wall_now(), Duration::from_secs(10), async move {
                        // Start consumer
                        let consumer_oracle = Arc::clone(&oracle_for_test);
                        let consumer = handle.spawn(async move {
                            let cx = Cx::for_testing();
                            super::atomicity_test::consumer_task(
                                receiver,
                                consumer_oracle,
                                expected_messages,
                                &cx,
                            )
                            .await
                        });

                        // Start producers
                        let mut producers = Vec::new();
                        for i in 0..config.num_producers {
                            let sender = sender.clone();
                            let producer_oracle = Arc::clone(&oracle_for_test);
                            let injector =
                                Arc::new(super::atomicity_test::CancellationInjector::new(
                                    config.cancel_probability,
                                ));

                            let messages: Vec<u32> = (0..config.messages_per_producer)
                                .map(|j| (i * config.messages_per_producer + j) as u32)
                                .collect();

                            let producer = handle.spawn(async move {
                                let cx = Cx::for_testing();
                                super::atomicity_test::producer_task(
                                    sender,
                                    producer_oracle,
                                    injector,
                                    messages,
                                    &cx,
                                )
                                .await
                            });
                            producers.push(producer);
                        }

                        // Wait for producers
                        for producer in producers {
                            if producer.await.is_err() {
                                return false;
                            }
                        }

                        // Close channel and wait for consumer
                        drop(sender);
                        match consumer.await {
                            Ok(_) => oracle_for_test.verify_final_consistency(),
                            Err(_) => false,
                        }
                    })
                    .await
                    {
                        Ok(consistent) => consistent,
                        Err(_) => {
                            eprintln!("  {test_name}: TIMEOUT");
                            false
                        }
                    }
                })
            }
            Err(e) => {
                eprintln!("  {test_name}: runtime build failed: {e}");
                false
            }
        };

        if test_result {
            println!("  {test_name}: PASSED");
        } else {
            println!("  {test_name}: FAILED");
        }

        test_result
    }

    /// Test oneshot channel atomicity.
    async fn test_oneshot_atomicity(&self) -> bool {
        // Oneshot is inherently atomic - test basic correctness
        match RuntimeBuilder::current_thread().build() {
            Ok(runtime) => runtime.block_on(async move {
                let cx = Cx::for_testing();

                for i in 0..100 {
                    let (sender, mut receiver) = oneshot::channel::<u32>();

                    if i % 2 == 0 {
                        sender.send(&cx, i).unwrap();
                        let value = receiver.recv(&cx).await.unwrap();
                        assert_eq!(value, i);
                    } else {
                        drop(sender);
                        assert!(receiver.recv(&cx).await.is_err());
                    }
                }
                true
            }),
            Err(_) => false,
        }
    }

    /// Test broadcast channel atomicity.
    async fn test_broadcast_atomicity(&self) -> bool {
        match RuntimeBuilder::current_thread().build() {
            Ok(runtime) => runtime.block_on(async move {
                let cx = Cx::for_testing();
                let (sender, _) = broadcast::channel::<u32>(50);

                let mut receivers = Vec::new();
                for _ in 0..5 {
                    receivers.push(sender.subscribe());
                }

                for i in 0..100 {
                    if sender.send(&cx, i).is_err() {
                        break;
                    }
                }

                drop(sender);

                for mut receiver in receivers {
                    let mut count = 0;
                    while receiver.recv(&cx).await.is_ok() {
                        count += 1;
                    }
                    assert!(count >= 50, "Receiver only got {count} messages");
                }
                true
            }),
            Err(_) => false,
        }
    }

    /// Test watch channel atomicity.
    async fn test_watch_atomicity(&self) -> bool {
        match RuntimeBuilder::current_thread().build() {
            Ok(runtime) => runtime.block_on(async move {
                let cx = Cx::for_testing();
                let (sender, _) = watch::channel::<u32>(0);

                let mut receiver = sender.subscribe();

                for i in 1..=50 {
                    sender.send(i).unwrap();
                }

                let _ = receiver.changed(&cx).await;
                let final_value = *receiver.borrow();
                assert_eq!(final_value, 50);
                true
            }),
            Err(_) => false,
        }
    }
}

/// Run the complete channel atomicity verification suite.
pub async fn run_verification_suite() -> VerificationResult {
    let config = VerificationSuiteConfig::default();
    let mut suite = VerificationSuite::new(config);
    suite.run().await
}

/// Run a quick verification suite for CI.
pub async fn run_quick_verification() -> VerificationResult {
    let config = VerificationSuiteConfig {
        test_all_channels: true,
        include_stress_tests: false, // Skip stress tests for speed
        include_edge_cases: true,
        include_cancellation_tests: true,
        max_duration: Duration::from_secs(30),
        fail_fast: true,
    };
    let mut suite = VerificationSuite::new(config);
    suite.run().await
}

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

    #[test]
    fn test_quick_verification_suite() {
        let result = future::block_on(run_quick_verification());

        println!("Quick Verification Results:");
        println!("  Duration: {:?}", result.total_duration);
        println!("  Tests: {}/{}", result.tests_passed, result.tests_executed);
        println!("  Success: {}", result.overall_success);
        println!("  Summary: {}", result.violation_summary);

        for (category, category_result) in &result.results_by_category {
            println!(
                "  {}: {}/{} passed",
                category, category_result.passed_count, category_result.test_count
            );
            if category_result.violations > 0 {
                println!("    Violations: {}", category_result.violations);
            }
            for failure in &category_result.failure_details {
                println!("    Failure: {failure}");
            }
        }

        assert!(
            result.overall_success,
            "Verification suite failed: {}",
            result.violation_summary
        );
        assert_eq!(
            result.tests_passed, result.tests_executed,
            "Some tests failed"
        );
    }

    #[test]
    #[ignore = "Long-running test"]
    fn test_full_verification_suite() {
        let result = future::block_on(run_verification_suite());

        println!("Full Verification Results:");
        println!("  Duration: {:?}", result.total_duration);
        println!("  Tests: {}/{}", result.tests_passed, result.tests_executed);
        println!("  Success: {}", result.overall_success);

        assert!(
            result.overall_success,
            "Verification suite failed: {}",
            result.violation_summary
        );
    }
}