asupersync 0.3.4

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
//! 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};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum StopReason {
    FailFast,
    MaxDuration,
}

impl StopReason {
    const fn message(self) -> &'static str {
        match self {
            Self::FailFast => "fail-fast triggered",
            Self::MaxDuration => "verification duration exceeded",
        }
    }
}

/// 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, Default)]
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>,
}

/// 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 {
        self.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();

        if self.stop_reason_after(true) == Some(StopReason::MaxDuration) {
            Self::append_summary(&mut violation_summary, StopReason::MaxDuration.message());
            overall_success = false;
            return self.build_result(
                total_tests,
                total_passed,
                overall_success,
                violation_summary,
            );
        }

        // 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;
                Self::append_summary(&mut violation_summary, "MPSC violations detected");
            }
            if self.apply_stop_reason_after(success, &mut violation_summary, &mut overall_success) {
                return self.build_result(
                    total_tests,
                    total_passed,
                    overall_success,
                    violation_summary,
                );
            }
        }

        // 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;
                Self::append_summary(&mut violation_summary, "Other channel violations detected");
            }
            if self.apply_stop_reason_after(success, &mut violation_summary, &mut overall_success) {
                return self.build_result(
                    total_tests,
                    total_passed,
                    overall_success,
                    violation_summary,
                );
            }
        }

        // 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;
                Self::append_summary(&mut violation_summary, "Edge case violations detected");
            }
            if self.apply_stop_reason_after(success, &mut violation_summary, &mut overall_success) {
                return self.build_result(
                    total_tests,
                    total_passed,
                    overall_success,
                    violation_summary,
                );
            }
        }

        // 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;
                Self::append_summary(
                    &mut violation_summary,
                    "Cancellation timing violations detected",
                );
            }
            if self.apply_stop_reason_after(success, &mut violation_summary, &mut overall_success) {
                return self.build_result(
                    total_tests,
                    total_passed,
                    overall_success,
                    violation_summary,
                );
            }
        }

        self.build_result(
            total_tests,
            total_passed,
            overall_success,
            violation_summary,
        )
    }

    fn build_result(
        &self,
        total_tests: usize,
        total_passed: usize,
        overall_success: bool,
        mut violation_summary: String,
    ) -> VerificationResult {
        if violation_summary.is_empty() {
            violation_summary = "No violations detected".to_string();
        }

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

    fn apply_stop_reason_after(
        &self,
        category_success: bool,
        violation_summary: &mut String,
        overall_success: &mut bool,
    ) -> bool {
        let Some(reason) = self.stop_reason_after(category_success) else {
            return false;
        };

        Self::append_summary(violation_summary, reason.message());
        *overall_success = false;
        true
    }

    fn stop_reason_after(&self, category_success: bool) -> Option<StopReason> {
        if self.config.fail_fast && !category_success {
            Some(StopReason::FailFast)
        } else if self.start_time.elapsed() >= self.config.max_duration {
            Some(StopReason::MaxDuration)
        } else {
            None
        }
    }

    fn append_summary(summary: &mut String, message: &str) {
        if !summary.is_empty() {
            summary.push_str("; ");
        }
        summary.push_str(message);
    }

    fn should_stop_category(&self, all_passed: bool) -> bool {
        self.stop_reason_after(all_passed).is_some()
    }

    fn finish_category(
        &mut self,
        name: &str,
        category: CategoryResult,
        all_passed: bool,
    ) -> (usize, usize, bool) {
        self.results.insert(name.to_string(), category);
        (
            self.results[name].test_count,
            self.results[name].passed_count,
            all_passed,
        )
    }

    /// 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());
        }
        if self.should_stop_category(all_passed) {
            return self.finish_category("MPSC", category, all_passed);
        }

        // 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}"));
                }
            }
            if self.should_stop_category(all_passed) {
                return self.finish_category("MPSC", category, all_passed);
            }
        }

        // 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.finish_category("MPSC", category, 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());
        }
        if self.should_stop_category(all_passed) {
            return self.finish_category("Other", category, all_passed);
        }

        // 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());
        }
        if self.should_stop_category(all_passed) {
            return self.finish_category("Other", category, all_passed);
        }

        // 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.finish_category("Other", category, 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.0,
            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());
        }
        if self.should_stop_category(all_passed) {
            return self.finish_category("EdgeCases", category, all_passed);
        }

        // Very large capacity channel
        category.test_count += 1;
        let large_config = AtomicityTestConfig {
            capacity: 1000,
            num_producers: 2,
            messages_per_producer: 10,
            cancel_probability: 0.0,
            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.finish_category("EdgeCases", category, 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: 2,
                messages_per_producer: 5,
                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"));
            }
            if self.should_stop_category(all_passed) {
                return self.finish_category("CancellationTiming", category, all_passed);
            }
        }

        self.finish_category("CancellationTiming", category, 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, initial_receiver) = broadcast::channel::<u32>(50);

                let mut receivers = vec![initial_receiver];
                for _ in 1..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 missed_messages = 0;
                    let mut received = Vec::new();
                    loop {
                        match receiver.recv(&cx).await {
                            Ok(value) => received.push(value),
                            Err(broadcast::RecvError::Lagged(missed)) => {
                                missed_messages += missed;
                            }
                            Err(broadcast::RecvError::Closed) => break,
                            Err(_) => return false,
                        }
                    }

                    if missed_messages != 50 {
                        return false;
                    }
                    if received.len() != 50 || !received.iter().copied().eq(50..100) {
                        return false;
                    }
                }
                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: false, // Cancellation timing is covered by the full suite
        max_duration: Duration::from_secs(30),
        fail_fast: true,
    };
    let mut suite = VerificationSuite::new(config);
    suite.run().await
}

#[cfg(test)]
mod tests {
    #![allow(
        clippy::pedantic,
        clippy::nursery,
        clippy::expect_fun_call,
        clippy::map_unwrap_or,
        clippy::cast_possible_wrap,
        clippy::future_not_send
    )]
    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]
    fn fail_fast_stop_reason_is_configured() {
        let fail_fast_suite = VerificationSuite::new(VerificationSuiteConfig {
            fail_fast: true,
            max_duration: Duration::from_secs(60),
            ..VerificationSuiteConfig::default()
        });
        assert_eq!(
            fail_fast_suite.stop_reason_after(false),
            Some(StopReason::FailFast)
        );

        let keep_going_suite = VerificationSuite::new(VerificationSuiteConfig {
            fail_fast: false,
            max_duration: Duration::from_secs(60),
            ..VerificationSuiteConfig::default()
        });
        assert_eq!(keep_going_suite.stop_reason_after(false), None);
    }

    #[test]
    fn zero_max_duration_stops_before_running_categories() {
        let result = future::block_on(async {
            let mut suite = VerificationSuite::new(VerificationSuiteConfig {
                max_duration: Duration::ZERO,
                ..VerificationSuiteConfig::default()
            });
            suite.run().await
        });

        assert_eq!(result.tests_executed, 0);
        assert_eq!(result.tests_passed, 0);
        assert!(!result.overall_success);
        assert!(
            result
                .violation_summary
                .contains(StopReason::MaxDuration.message())
        );
        assert!(result.results_by_category.is_empty());
    }

    #[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
        );
    }
}