asupersync 0.3.0

Spec-first, cancel-correct, capability-secure async runtime for Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
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
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
//! Conformance testing infrastructure for runtime implementations.
//!
//! This module provides traits and utilities for running conformance tests across
//! different runtime implementations (Lab, production, etc.).
//!
//! # Overview
//!
//! The conformance framework allows the same test suite to be run against multiple
//! runtime implementations, ensuring they all provide consistent behavior.
//!
//! # Example
//!
//! ```ignore
//! use asupersync::conformance::{ConformanceTarget, TestConfig, conformance_test};
//!
//! // Define a conformance test
//! conformance_test!(test_basic_spawn, |target, config| {
//!     let runtime = target.create_runtime(config);
//!     target.block_on(&runtime, async {
//!         // Test that basic spawning works
//!         let cx = Cx::current().unwrap();
//!         let handle = target.spawn(&cx, async { 42 });
//!         assert_eq!(handle.await, 42);
//!     });
//! });
//! ```

use crate::channel::oneshot;
use crate::cx::Cx;
use crate::types::{Budget, CancelReason, Outcome, RegionId, TaskId};
use parking_lot::Mutex;
use std::cell::RefCell;
use std::collections::VecDeque;
use std::future::{Future, poll_fn};
use std::pin::Pin;
use std::rc::Rc;
use std::sync::Arc;
use std::time::Duration;

/// Configuration for conformance tests.
///
/// Controls test execution parameters like timeouts, randomness, and tracing.
#[derive(Debug, Clone)]
pub struct TestConfig {
    /// Maximum duration for a test to complete.
    pub timeout: Duration,
    /// Optional RNG seed for deterministic execution.
    ///
    /// When `Some(seed)`, the runtime should use this seed for any random decisions,
    /// making test execution reproducible.
    pub rng_seed: Option<u64>,
    /// Whether to enable detailed tracing during test execution.
    pub tracing_enabled: bool,
    /// Maximum number of steps to execute (for Lab runtime).
    ///
    /// Prevents infinite loops in deterministic tests.
    pub max_steps: Option<u64>,
    /// Budget allocated to the root region.
    pub root_budget: Budget,
}

impl Default for TestConfig {
    fn default() -> Self {
        Self {
            timeout: Duration::from_secs(30),
            rng_seed: Some(0xDEAD_BEEF),
            tracing_enabled: false,
            max_steps: Some(100_000),
            root_budget: Budget::INFINITE,
        }
    }
}

impl TestConfig {
    /// Create a new test configuration with default values.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the timeout duration.
    #[must_use]
    pub const fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Set the RNG seed for deterministic execution.
    #[must_use]
    pub const fn with_seed(mut self, seed: u64) -> Self {
        self.rng_seed = Some(seed);
        self
    }

    /// Disable the RNG seed (use system randomness).
    #[must_use]
    pub const fn without_seed(mut self) -> Self {
        self.rng_seed = None;
        self
    }

    /// Enable or disable tracing.
    #[must_use]
    pub const fn with_tracing(mut self, enabled: bool) -> Self {
        self.tracing_enabled = enabled;
        self
    }

    /// Set the maximum number of steps.
    #[must_use]
    pub const fn with_max_steps(mut self, steps: u64) -> Self {
        self.max_steps = Some(steps);
        self
    }

    /// Set the root region budget.
    #[must_use]
    pub const fn with_budget(mut self, budget: Budget) -> Self {
        self.root_budget = budget;
        self
    }
}

/// Handle to a spawned task.
///
/// Allows waiting for task completion and retrieving the result.
pub struct TaskHandle<T> {
    /// The task ID once the runtime has registered the task.
    task_id: Arc<Mutex<Option<TaskId>>>,
    /// Boxed future that resolves to the task outcome.
    result: Pin<Box<dyn Future<Output = Outcome<T, ()>> + Send>>,
}

impl<T> TaskHandle<T> {
    /// Create a new task handle.
    pub fn new(
        task_id: TaskId,
        result: impl Future<Output = Outcome<T, ()>> + Send + 'static,
    ) -> Self {
        Self {
            task_id: Arc::new(Mutex::new(Some(task_id))),
            result: Box::pin(result),
        }
    }

    fn pending(
        task_id: Arc<Mutex<Option<TaskId>>>,
        result: impl Future<Output = Outcome<T, ()>> + Send + 'static,
    ) -> Self {
        Self {
            task_id,
            result: Box::pin(result),
        }
    }

    /// Get the task ID.
    #[must_use]
    pub fn id(&self) -> Option<TaskId> {
        *self.task_id.lock()
    }
}

impl<T> Future for TaskHandle<T> {
    type Output = Outcome<T, ()>;

    fn poll(
        mut self: Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Self::Output> {
        self.result.as_mut().poll(cx)
    }
}

/// Handle to a created region.
///
/// Allows waiting for region quiescence and managing the region lifecycle.
pub struct RegionHandle {
    /// The region ID once the runtime has created the region.
    region_id: Arc<Mutex<Option<RegionId>>>,
    /// Boxed future that resolves when the region closes.
    completion: Pin<Box<dyn Future<Output = ()> + Send>>,
}

impl RegionHandle {
    /// Create a new region handle.
    pub fn new(region_id: RegionId, completion: impl Future<Output = ()> + Send + 'static) -> Self {
        Self {
            region_id: Arc::new(Mutex::new(Some(region_id))),
            completion: Box::pin(completion),
        }
    }

    fn pending(
        region_id: Arc<Mutex<Option<RegionId>>>,
        completion: impl Future<Output = ()> + Send + 'static,
    ) -> Self {
        Self {
            region_id,
            completion: Box::pin(completion),
        }
    }

    /// Get the region ID.
    #[must_use]
    pub fn id(&self) -> Option<RegionId> {
        *self.region_id.lock()
    }
}

impl Future for RegionHandle {
    type Output = ();

    fn poll(
        mut self: Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Self::Output> {
        self.completion.as_mut().poll(cx)
    }
}

/// Trait for runtime implementations to support conformance testing.
///
/// This trait defines the operations that a runtime must implement to run
/// conformance tests. Both the Lab runtime and production runtime should
/// implement this trait.
///
/// # Type Parameters
///
/// The trait uses associated types to allow different runtime implementations
/// to use their own concrete types while maintaining a common interface.
///
/// # Example Implementation
///
/// ```ignore
/// impl ConformanceTarget for LabRuntimeTarget {
///     type Runtime = LabRuntime;
///
///     fn create_runtime(config: TestConfig) -> Self::Runtime {
///         let mut lab_config = LabConfig::new(config.rng_seed.unwrap_or(42));
///         if let Some(max_steps) = config.max_steps {
///             lab_config = lab_config.max_steps(max_steps);
///         }
///         LabRuntime::new(lab_config)
///     }
///
///     fn block_on<F>(runtime: &Self::Runtime, f: F) -> F::Output
///     where
///         F: Future + Send + 'static,
///         F::Output: Send + 'static,
///     {
///         // Lab runtime implementation
///     }
///     // ...
/// }
/// ```
pub trait ConformanceTarget: Sized + Send + Sync {
    /// The concrete runtime type.
    type Runtime: Send;

    /// Create a new runtime instance for testing.
    ///
    /// The runtime should be configured according to the provided `TestConfig`,
    /// including setting up deterministic RNG if a seed is provided.
    fn create_runtime(config: TestConfig) -> Self::Runtime;

    /// Run a future to completion on the runtime.
    ///
    /// This is the primary entry point for executing async code in tests.
    /// For Lab runtime, this typically runs until quiescence.
    /// For production runtime, this blocks until the future completes.
    fn block_on<F>(runtime: &mut Self::Runtime, f: F) -> F::Output
    where
        F: Future + Send + 'static,
        F::Output: Send + 'static;

    /// Spawn a task within the current region.
    ///
    /// The task should be spawned with the given budget and tracked by the runtime.
    /// Returns a handle that can be awaited to get the task result.
    fn spawn<T, F>(cx: &Cx, budget: Budget, f: F) -> TaskHandle<T>
    where
        T: Send + 'static,
        F: Future<Output = T> + Send + 'static;

    /// Create a child region.
    ///
    /// The child region should be a sub-region of the current context's region.
    /// Returns a handle that can be awaited to wait for region closure.
    fn create_region(cx: &Cx, budget: Budget) -> RegionHandle;

    /// Request cancellation of a region.
    ///
    /// This initiates the cancellation protocol:
    /// 1. Set cancel flag
    /// 2. Wait for tasks to reach checkpoints and drain
    /// 3. Run finalizers
    /// 4. Region closes
    fn cancel(cx: &Cx, region: &RegionHandle, reason: CancelReason);

    /// Advance virtual time (Lab runtime only).
    ///
    /// For production runtime, this may be a no-op or sleep for the given duration.
    /// For Lab runtime, this advances the virtual clock without real time passing.
    fn advance_time(runtime: &mut Self::Runtime, duration: Duration);

    /// Check if the runtime is quiescent.
    ///
    /// A runtime is quiescent when:
    /// - No tasks are ready to run
    /// - No pending wakeups
    /// - All regions have completed or are waiting
    fn is_quiescent(runtime: &Self::Runtime) -> bool;

    /// Get the current virtual time.
    ///
    /// For Lab runtime, returns the virtual clock time.
    /// For production runtime, may return wall-clock time.
    fn now(runtime: &Self::Runtime) -> Duration;
}

/// A registered conformance test.
#[derive(Clone)]
pub struct ConformanceTestFn {
    /// Test name.
    pub name: &'static str,
    /// Test function.
    pub test_fn: fn(&TestConfig),
}

/// Conformance test execution events.
#[derive(Clone, Debug)]
pub enum ConformanceEvent {
    /// A test started.
    TestStart {
        /// Test name.
        name: &'static str,
    },
    /// A test completed successfully.
    TestPassed {
        /// Test name.
        name: &'static str,
    },
    /// A test failed (panic or error).
    TestFailed {
        /// Test name.
        name: &'static str,
        /// Optional failure message extracted from the panic payload.
        message: Option<String>,
    },
}

/// Run a slice of conformance tests with the given configuration,
/// reporting progress via a callback.
///
/// Returns the number of tests that passed and failed.
#[must_use]
pub fn run_conformance_tests_with_reporter<F>(
    tests: &[ConformanceTestFn],
    config: &TestConfig,
    mut report: F,
) -> (usize, usize)
where
    F: FnMut(ConformanceEvent),
{
    let mut passed = 0;
    let mut failed = 0;

    for test in tests {
        report(ConformanceEvent::TestStart { name: test.name });
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            (test.test_fn)(config);
        }));

        match result {
            Ok(()) => {
                report(ConformanceEvent::TestPassed { name: test.name });
                passed += 1;
            }
            Err(e) => {
                let message = e.downcast_ref::<&str>().map_or_else(
                    || e.downcast_ref::<String>().cloned(),
                    |msg| Some((*msg).to_string()),
                );
                report(ConformanceEvent::TestFailed {
                    name: test.name,
                    message,
                });
                failed += 1;
            }
        }
    }

    (passed, failed)
}

/// Run a slice of conformance tests with the given configuration.
///
/// Returns the number of tests that passed and failed.
#[must_use]
pub fn run_conformance_tests(tests: &[ConformanceTestFn], config: &TestConfig) -> (usize, usize) {
    run_conformance_tests_with_reporter(tests, config, |_| {})
}

/// Render a deterministic markdown report from conformance execution events.
#[must_use]
pub fn render_conformance_report_markdown(
    passed: usize,
    failed: usize,
    events: &[ConformanceEvent],
    generated_at_epoch_secs: u64,
) -> String {
    let total = passed + failed;
    let mut report = format!(
        "# Conformance Report\n\nGenerated At: {generated_at_epoch_secs}\n\n## Summary\n- Total Completed: {total}\n- Passed: {passed}\n- Failed: {failed}\n\n## Results\n"
    );
    let mut completed = false;

    for event in events {
        match event {
            ConformanceEvent::TestStart { .. } => {}
            ConformanceEvent::TestPassed { name } => {
                completed = true;
                report.push_str(&format!("- `{name}`: PASS\n"));
            }
            ConformanceEvent::TestFailed { name, message } => {
                completed = true;
                report.push_str(&format!("- `{name}`: FAIL"));
                if let Some(message) = message {
                    report.push_str(&format!(" ({message})"));
                }
                report.push('\n');
            }
        }
    }

    if !completed {
        report.push_str("_No completed tests recorded._\n");
    }

    report
}

/// Macro for defining conformance tests.
///
/// This macro defines a test that will be run against conformance targets.
/// The test receives a `TestConfig` and should use a `ConformanceTarget` implementation
/// to execute the test.
///
/// # Example
///
/// ```ignore
/// use asupersync::conformance::{conformance_test, TestConfig};
///
/// conformance_test!(test_spawn_completes, |config: &TestConfig| {
///     use asupersync::conformance::ConformanceTarget;
///     use asupersync::lab::LabRuntime;
///
///     // Create runtime and run test
///     let mut runtime = LabRuntimeTarget::create_runtime(config.clone());
///     LabRuntimeTarget::block_on(&mut runtime, async {
///         // Test implementation
///     });
/// });
/// ```
#[macro_export]
macro_rules! conformance_test {
    ($name:ident, $body:expr) => {
        #[test]
        fn $name() {
            let config = $crate::conformance::TestConfig::default();
            let body: fn(&$crate::conformance::TestConfig) = $body;
            body(&config);
        }
    };
}

/// Implementation of `ConformanceTarget` for the Lab runtime.
///
/// This allows conformance tests to run against the deterministic Lab runtime,
/// which provides virtual time and reproducible scheduling.
pub struct LabRuntimeTarget;

type PendingLabOperation = Box<dyn FnOnce(&mut crate::lab::LabRuntime)>;

#[derive(Clone)]
struct LabConformanceSession {
    pending_ops: Rc<RefCell<VecDeque<PendingLabOperation>>>,
}

thread_local! {
    static CURRENT_LAB_CONFORMANCE_SESSION: RefCell<Option<LabConformanceSession>> =
        const { RefCell::new(None) };
}

struct LabConformanceSessionGuard {
    prev: Option<LabConformanceSession>,
}

impl Drop for LabConformanceSessionGuard {
    fn drop(&mut self) {
        let prev = self.prev.take();
        let _ = CURRENT_LAB_CONFORMANCE_SESSION.try_with(|slot| {
            *slot.borrow_mut() = prev;
        });
    }
}

impl LabConformanceSession {
    fn new() -> Self {
        Self {
            pending_ops: Rc::new(RefCell::new(VecDeque::new())),
        }
    }

    fn current() -> Self {
        CURRENT_LAB_CONFORMANCE_SESSION.with(|slot| {
            slot.borrow()
                .clone()
                .expect("LabRuntimeTarget operations must run inside LabRuntimeTarget::block_on")
        })
    }

    fn enter(&self) -> LabConformanceSessionGuard {
        let prev = CURRENT_LAB_CONFORMANCE_SESSION.with(|slot| {
            let mut guard = slot.borrow_mut();
            let prev = guard.take();
            *guard = Some(self.clone());
            prev
        });
        LabConformanceSessionGuard { prev }
    }

    fn enqueue(&self, op: PendingLabOperation) {
        self.pending_ops.borrow_mut().push_back(op);
    }

    fn has_pending(&self) -> bool {
        !self.pending_ops.borrow().is_empty()
    }

    fn drain(&self, runtime: &mut crate::lab::LabRuntime) {
        loop {
            let next = self.pending_ops.borrow_mut().pop_front();
            let Some(op) = next else {
                break;
            };
            op(runtime);
        }
    }
}

fn schedule_lab_task(runtime: &crate::lab::LabRuntime, task_id: TaskId, priority: u8) {
    runtime.scheduler.lock().schedule(task_id, priority);
}

fn request_lab_region_cancel(
    runtime: &mut crate::lab::LabRuntime,
    region_id: RegionId,
    reason: &CancelReason,
) {
    let tasks_to_schedule = runtime.state.cancel_request(region_id, reason, None);
    let mut scheduler = runtime.scheduler.lock();
    for (task_id, priority) in tasks_to_schedule {
        scheduler.schedule_cancel(task_id, priority);
    }
}

impl ConformanceTarget for LabRuntimeTarget {
    type Runtime = crate::lab::LabRuntime;

    fn create_runtime(config: TestConfig) -> Self::Runtime {
        use crate::lab::LabConfig;

        let seed = config.rng_seed.unwrap_or(0xDEAD_BEEF);
        let mut lab_config = LabConfig::new(seed);

        if let Some(max_steps) = config.max_steps {
            lab_config = lab_config.max_steps(max_steps);
        }

        if config.tracing_enabled {
            lab_config = lab_config.trace_capacity(64 * 1024);
        }

        crate::lab::LabRuntime::new(lab_config)
    }

    fn block_on<F>(runtime: &mut Self::Runtime, f: F) -> F::Output
    where
        F: Future + Send + 'static,
        F::Output: Send + 'static,
    {
        // Create root region
        let root_region = runtime.state.create_root_region(Budget::INFINITE);

        // Store the result
        let result: Arc<Mutex<Option<F::Output>>> = Arc::new(Mutex::new(None));
        let result_clone = result.clone();

        // Box the future with result capture
        let wrapped = async move {
            let output = f.await;
            *result_clone.lock() = Some(output);
        };

        // Create and schedule the task
        let (task_id, _handle) = runtime
            .state
            .create_task(root_region, Budget::INFINITE, wrapped)
            .expect("failed to create task");

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

        let session = LabConformanceSession::new();
        let _session_guard = session.enter();

        loop {
            session.drain(runtime);

            if runtime.is_quiescent() && !session.has_pending() {
                break;
            }

            if let Some(max_steps) = runtime.config().max_steps {
                if runtime.steps() >= max_steps {
                    break;
                }
            }

            runtime.step_for_test();
        }

        session.drain(runtime);

        // Extract result
        let mut guard = result.lock();
        guard.take().expect("task did not complete")
    }

    fn spawn<T, F>(cx: &Cx, budget: Budget, f: F) -> TaskHandle<T>
    where
        T: Send + 'static,
        F: Future<Output = T> + Send + 'static,
    {
        let session = LabConformanceSession::current();
        let task_id = Arc::new(Mutex::new(None));
        let join_cx = cx.clone();
        let op_cx = cx.clone();
        let task_id_for_op = Arc::clone(&task_id);
        let (registration_tx, mut registration_rx) = oneshot::channel();

        session.enqueue(Box::new(move |runtime| {
            let scope = op_cx.scope_with_budget(budget);
            let handle = scope
                .spawn_registered(&mut runtime.state, &op_cx, move |_child_cx| f)
                .expect("failed to create runtime-backed conformance task");
            let task_id_value = handle.task_id();
            *task_id_for_op.lock() = Some(task_id_value);

            let priority = runtime
                .state
                .task(task_id_value)
                .and_then(|record| record.cx_inner.as_ref())
                .map_or(budget.priority, |inner| inner.read().budget.priority);
            schedule_lab_task(runtime, task_id_value, priority);

            let _ = registration_tx.send(&op_cx, handle);
        }));

        TaskHandle::pending(task_id, async move {
            let mut handle = registration_rx
                .recv_uninterruptible()
                .await
                .expect("conformance task registration dropped before delivery");
            match handle.join(&join_cx).await {
                Ok(value) => Outcome::Ok(value),
                Err(crate::runtime::task_handle::JoinError::Cancelled(reason)) => {
                    Outcome::Cancelled(reason)
                }
                Err(crate::runtime::task_handle::JoinError::Panicked(payload)) => {
                    Outcome::Panicked(payload)
                }
                Err(crate::runtime::task_handle::JoinError::PolledAfterCompletion) => {
                    Outcome::Err(())
                }
            }
        })
    }

    fn create_region(cx: &Cx, budget: Budget) -> RegionHandle {
        let session = LabConformanceSession::current();
        let region_id = Arc::new(Mutex::new(None));
        let region_id_for_op = Arc::clone(&region_id);
        let op_cx = cx.clone();
        let (registration_tx, mut registration_rx) = oneshot::channel();

        session.enqueue(Box::new(move |runtime| {
            let region_id_value = runtime
                .state
                .create_child_region(op_cx.region_id(), budget)
                .expect("failed to create runtime-backed conformance region");
            let close_notify = runtime
                .state
                .region(region_id_value)
                .expect("created region must exist")
                .close_notify
                .clone();
            *region_id_for_op.lock() = Some(region_id_value);
            let _ = registration_tx.send(&op_cx, close_notify);
        }));

        RegionHandle::pending(region_id, async move {
            let close_notify = registration_rx
                .recv_uninterruptible()
                .await
                .expect("conformance region registration dropped before delivery");

            poll_fn(move |cx| {
                let mut state = close_notify.lock();
                if state.closed {
                    std::task::Poll::Ready(())
                } else {
                    if !state
                        .waker
                        .as_ref()
                        .is_some_and(|waker| waker.will_wake(cx.waker()))
                    {
                        state.waker = Some(cx.waker().clone());
                    }
                    std::task::Poll::Pending
                }
            })
            .await;
        })
    }

    fn cancel(_cx: &Cx, region: &RegionHandle, reason: CancelReason) {
        let session = LabConformanceSession::current();
        let region_id = Arc::clone(&region.region_id);

        session.enqueue(Box::new(move |runtime| {
            let region_id_value = (*region_id.lock())
                .expect("conformance region cancel issued before region registration completed");
            request_lab_region_cancel(runtime, region_id_value, &reason);
        }));
    }

    fn advance_time(runtime: &mut Self::Runtime, duration: Duration) {
        let nanos = u64::try_from(duration.as_nanos()).unwrap_or(u64::MAX);
        runtime.advance_time(nanos);
    }

    fn is_quiescent(runtime: &Self::Runtime) -> bool {
        runtime.is_quiescent()
    }

    fn now(runtime: &Self::Runtime) -> Duration {
        let time = runtime.now();
        Duration::from_nanos(time.as_nanos())
    }
}

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

    #[derive(Clone, Copy)]
    struct ConformanceManifestTest {
        name: &'static str,
        invariant: &'static str,
    }

    #[derive(Clone)]
    struct ConformanceManifestComponent {
        component: &'static str,
        target: &'static str,
        tests: Vec<ConformanceManifestTest>,
    }

    fn render_conformance_manifest_yaml(components: &[ConformanceManifestComponent]) -> String {
        let mut components = components.to_vec();
        components.sort_unstable_by(|left, right| {
            left.component
                .cmp(right.component)
                .then(left.target.cmp(right.target))
        });

        let mut rendered =
            String::from("schema_version: conformance-manifest/v1\nmodule: asupersync::conformance\ncomponents:\n");

        for component in &mut components {
            component
                .tests
                .sort_unstable_by(|left, right| left.name.cmp(right.name));
            rendered.push_str(&format!(
                "  - component: {}\n    target: {}\n    tests:\n",
                component.component, component.target
            ));

            for test in &component.tests {
                rendered.push_str(&format!(
                    "      - name: {}\n        invariant: {}\n",
                    test.name, test.invariant
                ));
            }
        }

        rendered
    }

    fn scrub_conformance_markdown(markdown: &str) -> String {
        markdown
            .lines()
            .map(|line| {
                if line.starts_with("Generated At: ") {
                    "Generated At: [TIMESTAMP]".to_string()
                } else {
                    line.to_string()
                }
            })
            .collect::<Vec<_>>()
            .join("\n")
    }

    fn scrub_conformance_report(events: &[ConformanceEvent]) -> serde_json::Value {
        json!(
            events
                .iter()
                .map(|event| match event {
                    ConformanceEvent::TestStart { name } => json!({
                        "event": "start",
                        "name": name,
                    }),
                    ConformanceEvent::TestPassed { name } => json!({
                        "event": "passed",
                        "name": name,
                    }),
                    ConformanceEvent::TestFailed { name, .. } => json!({
                        "event": "failed",
                        "name": name,
                        "message": "[MESSAGE]",
                    }),
                })
                .collect::<Vec<_>>()
        )
    }

    #[test]
    fn test_config_default() {
        let config = TestConfig::default();
        assert_eq!(config.timeout, Duration::from_secs(30));
        assert_eq!(config.rng_seed, Some(0xDEAD_BEEF));
        assert!(!config.tracing_enabled);
        assert_eq!(config.max_steps, Some(100_000));
    }

    #[test]
    fn test_config_builder() {
        let config = TestConfig::new()
            .with_timeout(Duration::from_secs(60))
            .with_seed(42)
            .with_tracing(true)
            .with_max_steps(1000);

        assert_eq!(config.timeout, Duration::from_secs(60));
        assert_eq!(config.rng_seed, Some(42));
        assert!(config.tracing_enabled);
        assert_eq!(config.max_steps, Some(1000));
    }

    #[test]
    fn test_lab_runtime_target_create() {
        let config = TestConfig::new().with_seed(12345);
        let runtime = LabRuntimeTarget::create_runtime(config);

        // Verify runtime was created with correct seed
        assert_eq!(runtime.config().seed, 12345);
    }

    #[test]
    fn test_lab_runtime_target_block_on() {
        let config = TestConfig::default();
        let mut runtime = LabRuntimeTarget::create_runtime(config);

        let result = LabRuntimeTarget::block_on(&mut runtime, async { 42 });

        assert_eq!(result, 42);
    }

    #[test]
    fn test_lab_runtime_target_advance_time() {
        let config = TestConfig::default();
        let mut runtime = LabRuntimeTarget::create_runtime(config);

        let before = LabRuntimeTarget::now(&runtime);
        LabRuntimeTarget::advance_time(&mut runtime, Duration::from_secs(1));
        let after = LabRuntimeTarget::now(&runtime);

        assert!(after > before);
        assert_eq!(after.checked_sub(before).unwrap(), Duration::from_secs(1));
    }

    #[test]
    fn test_lab_runtime_target_quiescence() {
        let config = TestConfig::default();
        let runtime = LabRuntimeTarget::create_runtime(config);

        // Fresh runtime should be quiescent
        assert!(LabRuntimeTarget::is_quiescent(&runtime));
    }

    #[test]
    fn test_config_debug() {
        let cfg = TestConfig::default();
        let dbg = format!("{cfg:?}");
        assert!(dbg.contains("TestConfig"));
    }

    #[test]
    fn test_config_clone() {
        let cfg = TestConfig::new().with_seed(99).with_tracing(true);
        let cfg2 = cfg;
        assert_eq!(cfg2.rng_seed, Some(99));
        assert!(cfg2.tracing_enabled);
    }

    #[test]
    fn test_config_without_seed() {
        let cfg = TestConfig::new().without_seed();
        assert!(cfg.rng_seed.is_none());
    }

    #[test]
    fn test_config_with_budget() {
        let budget = Budget::with_deadline_secs(100);
        let cfg = TestConfig::new().with_budget(budget);
        assert_eq!(cfg.root_budget, budget);
    }

    #[test]
    fn test_config_with_timeout() {
        let cfg = TestConfig::new().with_timeout(Duration::from_secs(60));
        assert_eq!(cfg.timeout, Duration::from_secs(60));
    }

    #[test]
    fn task_handle_id() {
        let tid = TaskId::new_for_test(5, 0);
        let handle = TaskHandle::new(tid, async { Outcome::Ok(42) });
        assert_eq!(handle.id(), Some(tid));
    }

    #[test]
    fn region_handle_id() {
        let rid = RegionId::new_for_test(3, 0);
        let handle = RegionHandle::new(rid, async {});
        assert_eq!(handle.id(), Some(rid));
    }

    #[test]
    fn lab_runtime_target_with_tracing() {
        let config = TestConfig::new().with_seed(42).with_tracing(true);
        let runtime = LabRuntimeTarget::create_runtime(config);
        assert_eq!(runtime.config().seed, 42);
        assert_eq!(runtime.config().trace_capacity, 64 * 1024);
    }

    #[test]
    fn lab_runtime_target_without_seed() {
        let config = TestConfig::new().without_seed();
        let runtime = LabRuntimeTarget::create_runtime(config);
        // Should use default seed 0xDEAD_BEEF when None
        assert_eq!(runtime.config().seed, 0xDEAD_BEEF);
    }

    #[test]
    fn lab_runtime_target_spawn_registers_real_task_handle() {
        let config = TestConfig::default();
        let mut runtime = LabRuntimeTarget::create_runtime(config);

        let (task_id, outcome) = LabRuntimeTarget::block_on(&mut runtime, async {
            let cx = Cx::current().expect("root task should have a current Cx");
            let handle = LabRuntimeTarget::spawn(&cx, Budget::INFINITE, async { 42_u8 });

            assert_eq!(handle.id(), None);
            crate::runtime::yield_now().await;

            let task_id = handle
                .id()
                .expect("task id should be resolved after the first scheduler turn");
            let outcome = handle.await;
            (task_id, outcome)
        });

        assert_ne!(task_id, TaskId::new_for_test(0, 0));
        assert_eq!(outcome, Outcome::Ok(42));
    }

    #[test]
    fn lab_runtime_target_create_region_and_cancel_before_registration_closes_region() {
        let config = TestConfig::default();
        let mut runtime = LabRuntimeTarget::create_runtime(config);

        let region_id = LabRuntimeTarget::block_on(&mut runtime, async {
            let cx = Cx::current().expect("root task should have a current Cx");
            let region = LabRuntimeTarget::create_region(&cx, Budget::INFINITE);
            let region_id = Arc::clone(&region.region_id);
            assert_eq!(region.id(), None);

            LabRuntimeTarget::cancel(&cx, &region, CancelReason::user("conformance-test"));
            region.await;
            (*region_id.lock()).expect("region id should resolve once the region has been created")
        });

        assert_ne!(region_id, RegionId::new_for_test(0, 0));
    }

    #[test]
    fn reporter_snapshot_scrubs_failure_messages() {
        fn passing_test(_config: &TestConfig) {}

        fn failing_test(_config: &TestConfig) {
            std::panic::resume_unwind(Box::new(String::from(
                "expected deterministic failure payload",
            )));
        }

        let tests = [
            ConformanceTestFn {
                name: "pass_case",
                test_fn: passing_test,
            },
            ConformanceTestFn {
                name: "fail_case",
                test_fn: failing_test,
            },
        ];
        let mut events = Vec::new();
        let (passed, failed) =
            run_conformance_tests_with_reporter(&tests, &TestConfig::default(), |event| {
                events.push(event);
            });

        assert_eq!((passed, failed), (1, 1));
        insta::assert_json_snapshot!(
            "conformance_report_scrubbed",
            json!({
                "summary": {
                    "passed": passed,
                    "failed": failed,
                },
                "events": scrub_conformance_report(&events),
            })
        );
    }

    #[test]
    fn report_markdown_snapshot_scrubs_generated_timestamps() {
        fn passing_test(_config: &TestConfig) {}

        fn failing_test(_config: &TestConfig) {
            std::panic::resume_unwind(Box::new(String::from("deterministic markdown failure")));
        }

        fn render_scenario_markdown(
            tests: &[ConformanceTestFn],
            generated_at_epoch_secs: u64,
        ) -> String {
            let mut events = Vec::new();
            let (passed, failed) =
                run_conformance_tests_with_reporter(tests, &TestConfig::default(), |event| {
                    events.push(event);
                });
            scrub_conformance_markdown(&render_conformance_report_markdown(
                passed,
                failed,
                &events,
                generated_at_epoch_secs,
            ))
        }

        let snapshot = [
            "## passing".to_string(),
            render_scenario_markdown(
                &[ConformanceTestFn {
                    name: "pass_only",
                    test_fn: passing_test,
                }],
                1_700_000_001,
            ),
            "## failing".to_string(),
            render_scenario_markdown(
                &[ConformanceTestFn {
                    name: "fail_only",
                    test_fn: failing_test,
                }],
                1_800_000_002,
            ),
            "## mixed".to_string(),
            render_scenario_markdown(
                &[
                    ConformanceTestFn {
                        name: "pass_first",
                        test_fn: passing_test,
                    },
                    ConformanceTestFn {
                        name: "fail_second",
                        test_fn: failing_test,
                    },
                    ConformanceTestFn {
                        name: "pass_third",
                        test_fn: passing_test,
                    },
                ],
                1_900_000_003,
            ),
        ]
        .join("\n\n");

        insta::assert_snapshot!("conformance_report_markdown_scrubbed", snapshot);
    }

    #[test]
    fn conformance_manifest_yaml_component_matrix_snapshot() {
        let snapshot = render_conformance_manifest_yaml(&[
            ConformanceManifestComponent {
                component: "runtime-target",
                target: "LabRuntimeTarget",
                tests: vec![
                    ConformanceManifestTest {
                        name: "test_lab_runtime_target_advance_time",
                        invariant: "virtual time advances by the requested duration without wall-clock drift",
                    },
                    ConformanceManifestTest {
                        name: "lab_runtime_target_spawn_registers_real_task_handle",
                        invariant: "spawned conformance tasks resolve from pending handles to registered task ids",
                    },
                    ConformanceManifestTest {
                        name: "lab_runtime_target_create_region_and_cancel_before_registration_closes_region",
                        invariant: "region registration resolves before cancellation completes closure",
                    },
                    ConformanceManifestTest {
                        name: "test_lab_runtime_target_create",
                        invariant: "runtime creation forwards the requested deterministic seed",
                    },
                ],
            },
            ConformanceManifestComponent {
                component: "config",
                target: "TestConfig",
                tests: vec![
                    ConformanceManifestTest {
                        name: "test_config_default",
                        invariant: "default config preserves the canonical timeout, seed, tracing, and step budget",
                    },
                    ConformanceManifestTest {
                        name: "test_config_with_budget",
                        invariant: "root budget overrides are preserved in the default config chain",
                    },
                    ConformanceManifestTest {
                        name: "test_config_builder",
                        invariant: "builder setters preserve explicit timeout, seed, tracing, and max-step overrides",
                    },
                    ConformanceManifestTest {
                        name: "test_config_without_seed",
                        invariant: "seedless configuration is represented explicitly for nondeterministic targets",
                    },
                ],
            },
            ConformanceManifestComponent {
                component: "reporting",
                target: "ConformanceEvent",
                tests: vec![
                    ConformanceManifestTest {
                        name: "report_markdown_snapshot_scrubs_generated_timestamps",
                        invariant: "markdown reports scrub generated timestamps while preserving summary ordering",
                    },
                    ConformanceManifestTest {
                        name: "reporter_snapshot_scrubs_failure_messages",
                        invariant: "structured reports preserve pass-fail ordering while redacting failure payloads",
                    },
                ],
            },
            ConformanceManifestComponent {
                component: "handles",
                target: "TaskHandle/RegionHandle",
                tests: vec![
                    ConformanceManifestTest {
                        name: "region_handle_id",
                        invariant: "region handles surface the registered region id once available",
                    },
                    ConformanceManifestTest {
                        name: "task_handle_id",
                        invariant: "task handles surface the registered task id once available",
                    },
                ],
            },
        ]);

        insta::assert_snapshot!("conformance_manifest_yaml_component_matrix", snapshot);
    }
}