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
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
//! Conformance harness for ShardedState lock ordering and concurrency contracts.
//!
//! This module implements comprehensive conformance testing for the documented
//! specifications in [`ShardedState`], particularly:
//!
//! - **Lock Ordering Contract**: E (Config) → D (Instrumentation) → B (Regions) → A (Tasks) → C (Obligations)
//! - **Shard Responsibility Contract**: Each guard method accesses only its documented shards
//! - **Concurrency Safety Contract**: No deadlocks under concurrent access patterns
//! - **State Consistency Contract**: Atomic operations maintain consistency
//!
//! # Specification Source
//!
//! The specifications being tested are documented in:
//! - `src/runtime/sharded_state.rs` comments and doc strings
//! - Lock ordering table in module documentation
//! - Method → ShardGuard mapping table
//! - Debug assertions in `lock_order` module
//!
//! # Test Organization
//!
//! This follows **Pattern 4: Spec-Derived Test Matrix** - one test per documented requirement.

use crate::observability::ObservabilityConfig;
use crate::observability::metrics::{MetricsProvider, NoOpMetrics};
use crate::runtime::config::ObligationLeakResponse;
use crate::runtime::sharded_state::{
    ShardGuard, ShardedConfig, ShardedObservability, ShardedState,
};
use crate::trace::TraceBufferHandle;
use crate::trace::distributed::LogicalClockMode;
use crate::types::{CancelAttributionConfig, RegionId, Time};
use crate::util::{ArenaIndex, OsEntropy};
use std::sync::{Arc, Barrier};
use std::thread;
use std::time::Duration;

// Conditional access to lock order tracking functions
#[cfg(any(debug_assertions, feature = "lock-metrics"))]
fn held_count() -> usize {
    crate::runtime::sharded_state::lock_order::held_count()
}

#[cfg(any(debug_assertions, feature = "lock-metrics"))]
fn held_labels() -> Vec<&'static str> {
    crate::runtime::sharded_state::lock_order::held_labels()
}

#[cfg(not(any(debug_assertions, feature = "lock-metrics")))]
fn held_count() -> usize {
    0
}

#[cfg(not(any(debug_assertions, feature = "lock-metrics")))]
fn held_labels() -> Vec<&'static str> {
    Vec::new()
}

fn lock_order_tracking_skip() -> Option<ConformanceResult> {
    if cfg!(any(debug_assertions, feature = "lock-metrics")) {
        None
    } else {
        Some(ConformanceResult::Skip {
            reason: "lock-order tracking is compiled out in release builds without lock-metrics"
                .to_string(),
        })
    }
}

/// Conformance test result for structured reporting.
#[derive(Debug, Clone, PartialEq)]
pub enum ConformanceResult {
    Pass,
    Fail { reason: String },
    Skip { reason: String },
}

/// Requirement levels for coverage tracking.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum RequirementLevel {
    Must,   // MUST requirements from specification
    Should, // SHOULD requirements
    May,    // MAY requirements or edge cases
}

/// Conformance test case for structured execution.
#[derive(Debug)]
pub struct ConformanceTestCase {
    pub id: &'static str,
    pub section: &'static str,
    pub level: RequirementLevel,
    pub description: &'static str,
}

impl ConformanceTestCase {
    pub const fn new(
        id: &'static str,
        section: &'static str,
        level: RequirementLevel,
        description: &'static str,
    ) -> Self {
        Self {
            id,
            section,
            level,
            description,
        }
    }
}

/// Test fixture for creating consistent ShardedState instances.
pub struct ConformanceFixture {
    pub state: ShardedState,
}

impl ConformanceFixture {
    pub fn new() -> Self {
        let trace = TraceBufferHandle::new(1024);
        let metrics: Arc<dyn MetricsProvider> = Arc::new(NoOpMetrics);
        let config = ShardedConfig {
            io_driver: None,
            timer_driver: None,
            logical_clock_mode: LogicalClockMode::Lamport,
            cancel_attribution: CancelAttributionConfig::default(),
            entropy_source: Arc::new(OsEntropy),
            blocking_pool: None,
            obligation_leak_response: ObligationLeakResponse::Log,
            leak_escalation: None,
            observability: Some(ShardedObservability::new(ObservabilityConfig::default())),
        };

        let state = ShardedState::new(trace, metrics, config);
        Self { state }
    }
}

/// Comprehensive conformance test suite for ShardedState.
pub struct ShardedStateConformanceSuite;

impl ShardedStateConformanceSuite {
    /// Execute the complete conformance test suite.
    pub fn run_all() -> (usize, usize) {
        let test_cases = [
            // ─── Lock Ordering Compliance Tests ───
            ConformanceTestCase::new(
                "LOCK-ORD-001",
                "lock_order",
                RequirementLevel::Must,
                "tasks_only guard must acquire only Task shard (A)",
            ),
            ConformanceTestCase::new(
                "LOCK-ORD-002",
                "lock_order",
                RequirementLevel::Must,
                "regions_only guard must acquire only Region shard (B)",
            ),
            ConformanceTestCase::new(
                "LOCK-ORD-003",
                "lock_order",
                RequirementLevel::Must,
                "obligations_only guard must acquire only Obligation shard (C)",
            ),
            ConformanceTestCase::new(
                "LOCK-ORD-004",
                "lock_order",
                RequirementLevel::Must,
                "for_spawn guard must acquire B→A in correct order",
            ),
            ConformanceTestCase::new(
                "LOCK-ORD-005",
                "lock_order",
                RequirementLevel::Must,
                "for_obligation guard must acquire B→C in correct order",
            ),
            ConformanceTestCase::new(
                "LOCK-ORD-006",
                "lock_order",
                RequirementLevel::Must,
                "for_task_completed guard must acquire B→A→C in correct order",
            ),
            ConformanceTestCase::new(
                "LOCK-ORD-007",
                "lock_order",
                RequirementLevel::Must,
                "for_cancel guard must acquire B→A→C in correct order",
            ),
            ConformanceTestCase::new(
                "LOCK-ORD-008",
                "lock_order",
                RequirementLevel::Must,
                "for_obligation_resolve guard must acquire B→A→C in correct order",
            ),
            ConformanceTestCase::new(
                "LOCK-ORD-009",
                "lock_order",
                RequirementLevel::Must,
                "all guard must acquire B→A→C in correct order",
            ),
            // ─── Shard Access Compliance Tests ───
            ConformanceTestCase::new(
                "SHARD-ACC-001",
                "shard_access",
                RequirementLevel::Must,
                "tasks_only guard provides tasks access, no regions/obligations",
            ),
            ConformanceTestCase::new(
                "SHARD-ACC-002",
                "shard_access",
                RequirementLevel::Must,
                "regions_only guard provides regions access, no tasks/obligations",
            ),
            ConformanceTestCase::new(
                "SHARD-ACC-003",
                "shard_access",
                RequirementLevel::Must,
                "obligations_only guard provides obligations access, no regions/tasks",
            ),
            ConformanceTestCase::new(
                "SHARD-ACC-004",
                "shard_access",
                RequirementLevel::Must,
                "for_spawn guard provides regions+tasks access, no obligations",
            ),
            ConformanceTestCase::new(
                "SHARD-ACC-005",
                "shard_access",
                RequirementLevel::Must,
                "for_obligation guard provides regions+obligations access, no tasks",
            ),
            // ─── State Consistency Tests ───
            ConformanceTestCase::new(
                "STATE-CON-001",
                "state_consistency",
                RequirementLevel::Must,
                "root_region atomic operations are consistent",
            ),
            ConformanceTestCase::new(
                "STATE-CON-002",
                "state_consistency",
                RequirementLevel::Must,
                "leak_count atomic operations are consistent",
            ),
            ConformanceTestCase::new(
                "STATE-CON-003",
                "state_consistency",
                RequirementLevel::Must,
                "current_time atomic operations are consistent",
            ),
            // ─── Deadlock Prevention Tests ───
            ConformanceTestCase::new(
                "DEADLOCK-001",
                "deadlock_prevention",
                RequirementLevel::Must,
                "concurrent guard acquisition must not deadlock",
            ),
            ConformanceTestCase::new(
                "DEADLOCK-002",
                "deadlock_prevention",
                RequirementLevel::Should,
                "stress test: high-concurrency guard operations complete",
            ),
        ];

        let mut passed = 0;
        let mut failed = 0;

        for case in &test_cases {
            let result = Self::run_test_case(case);
            match result {
                ConformanceResult::Pass => {
                    passed += 1;
                }
                ConformanceResult::Fail { reason: _ } => {
                    failed += 1;
                }
                ConformanceResult::Skip { reason: _ } => {
                    // Test skipped
                }
            }
        }

        let _total = passed + failed;
        // ShardedState Conformance: tests completed

        (passed, failed)
    }

    /// Run a specific conformance test case.
    fn run_test_case(case: &ConformanceTestCase) -> ConformanceResult {
        match case.id {
            // Lock ordering compliance tests
            "LOCK-ORD-001" => Self::test_tasks_only_lock_order(),
            "LOCK-ORD-002" => Self::test_regions_only_lock_order(),
            "LOCK-ORD-003" => Self::test_obligations_only_lock_order(),
            "LOCK-ORD-004" => Self::test_for_spawn_lock_order(),
            "LOCK-ORD-005" => Self::test_for_obligation_lock_order(),
            "LOCK-ORD-006" => Self::test_for_task_completed_lock_order(),
            "LOCK-ORD-007" => Self::test_for_cancel_lock_order(),
            "LOCK-ORD-008" => Self::test_for_obligation_resolve_lock_order(),
            "LOCK-ORD-009" => Self::test_all_lock_order(),

            // Shard access compliance tests
            "SHARD-ACC-001" => Self::test_tasks_only_shard_access(),
            "SHARD-ACC-002" => Self::test_regions_only_shard_access(),
            "SHARD-ACC-003" => Self::test_obligations_only_shard_access(),
            "SHARD-ACC-004" => Self::test_for_spawn_shard_access(),
            "SHARD-ACC-005" => Self::test_for_obligation_shard_access(),

            // State consistency tests
            "STATE-CON-001" => Self::test_root_region_consistency(),
            "STATE-CON-002" => Self::test_leak_count_consistency(),
            "STATE-CON-003" => Self::test_current_time_consistency(),

            // Deadlock prevention tests
            "DEADLOCK-001" => Self::test_concurrent_guard_acquisition(),
            "DEADLOCK-002" => Self::test_stress_concurrency(),

            _ => ConformanceResult::Skip {
                reason: format!("Unknown conformance test case id {}", case.id),
            },
        }
    }

    // ─── Lock Ordering Compliance Tests ───

    fn test_tasks_only_lock_order() -> ConformanceResult {
        if let Some(result) = lock_order_tracking_skip() {
            return result;
        }

        let fixture = ConformanceFixture::new();
        assert_eq!(held_count(), 0, "no locks held before test");

        {
            let _guard = ShardGuard::tasks_only(&fixture.state);
            let held = held_labels();
            if held != vec!["A:Tasks"] {
                return ConformanceResult::Fail {
                    reason: format!("Expected ['A:Tasks'], got {:?}", held),
                };
            }
        }

        if held_count() != 0 {
            return ConformanceResult::Fail {
                reason: format!("Lock not released: {} locks still held", held_count()),
            };
        }

        ConformanceResult::Pass
    }

    fn test_regions_only_lock_order() -> ConformanceResult {
        if let Some(result) = lock_order_tracking_skip() {
            return result;
        }

        let fixture = ConformanceFixture::new();
        assert_eq!(held_count(), 0, "no locks held before test");

        {
            let _guard = ShardGuard::regions_only(&fixture.state);
            let held = held_labels();
            if held != vec!["B:Regions"] {
                return ConformanceResult::Fail {
                    reason: format!("Expected ['B:Regions'], got {:?}", held),
                };
            }
        }

        if held_count() != 0 {
            return ConformanceResult::Fail {
                reason: format!("Lock not released: {} locks still held", held_count()),
            };
        }

        ConformanceResult::Pass
    }

    fn test_obligations_only_lock_order() -> ConformanceResult {
        if let Some(result) = lock_order_tracking_skip() {
            return result;
        }

        let fixture = ConformanceFixture::new();
        assert_eq!(held_count(), 0, "no locks held before test");

        {
            let _guard = ShardGuard::obligations_only(&fixture.state);
            let held = held_labels();
            if held != vec!["C:Obligations"] {
                return ConformanceResult::Fail {
                    reason: format!("Expected ['C:Obligations'], got {:?}", held),
                };
            }
        }

        if held_count() != 0 {
            return ConformanceResult::Fail {
                reason: format!("Lock not released: {} locks still held", held_count()),
            };
        }

        ConformanceResult::Pass
    }

    fn test_for_spawn_lock_order() -> ConformanceResult {
        if let Some(result) = lock_order_tracking_skip() {
            return result;
        }

        let fixture = ConformanceFixture::new();
        assert_eq!(held_count(), 0, "no locks held before test");

        {
            let _guard = ShardGuard::for_spawn(&fixture.state);
            let held = held_labels();
            // Must be B→A order
            if held != vec!["B:Regions", "A:Tasks"] {
                return ConformanceResult::Fail {
                    reason: format!("Expected ['B:Regions', 'A:Tasks'], got {:?}", held),
                };
            }
        }

        if held_count() != 0 {
            return ConformanceResult::Fail {
                reason: format!("Locks not released: {} locks still held", held_count()),
            };
        }

        ConformanceResult::Pass
    }

    fn test_for_obligation_lock_order() -> ConformanceResult {
        if let Some(result) = lock_order_tracking_skip() {
            return result;
        }

        let fixture = ConformanceFixture::new();
        assert_eq!(held_count(), 0, "no locks held before test");

        {
            let _guard = ShardGuard::for_obligation(&fixture.state);
            let held = held_labels();
            // Must be B→C order
            if held != vec!["B:Regions", "C:Obligations"] {
                return ConformanceResult::Fail {
                    reason: format!("Expected ['B:Regions', 'C:Obligations'], got {:?}", held),
                };
            }
        }

        if held_count() != 0 {
            return ConformanceResult::Fail {
                reason: format!("Locks not released: {} locks still held", held_count()),
            };
        }

        ConformanceResult::Pass
    }

    fn test_for_task_completed_lock_order() -> ConformanceResult {
        if let Some(result) = lock_order_tracking_skip() {
            return result;
        }

        let fixture = ConformanceFixture::new();
        assert_eq!(held_count(), 0, "no locks held before test");

        {
            let _guard = ShardGuard::for_task_completed(&fixture.state);
            let held = held_labels();
            // Must be B→A→C order
            if held != vec!["B:Regions", "A:Tasks", "C:Obligations"] {
                return ConformanceResult::Fail {
                    reason: format!(
                        "Expected ['B:Regions', 'A:Tasks', 'C:Obligations'], got {:?}",
                        held
                    ),
                };
            }
        }

        if held_count() != 0 {
            return ConformanceResult::Fail {
                reason: format!("Locks not released: {} locks still held", held_count()),
            };
        }

        ConformanceResult::Pass
    }

    fn test_for_cancel_lock_order() -> ConformanceResult {
        if let Some(result) = lock_order_tracking_skip() {
            return result;
        }

        let fixture = ConformanceFixture::new();
        assert_eq!(held_count(), 0, "no locks held before test");

        {
            let _guard = ShardGuard::for_cancel(&fixture.state);
            let held = held_labels();
            // Must be B→A→C order
            if held != vec!["B:Regions", "A:Tasks", "C:Obligations"] {
                return ConformanceResult::Fail {
                    reason: format!(
                        "Expected ['B:Regions', 'A:Tasks', 'C:Obligations'], got {:?}",
                        held
                    ),
                };
            }
        }

        if held_count() != 0 {
            return ConformanceResult::Fail {
                reason: format!("Locks not released: {} locks still held", held_count()),
            };
        }

        ConformanceResult::Pass
    }

    fn test_for_obligation_resolve_lock_order() -> ConformanceResult {
        if let Some(result) = lock_order_tracking_skip() {
            return result;
        }

        let fixture = ConformanceFixture::new();
        assert_eq!(held_count(), 0, "no locks held before test");

        {
            let _guard = ShardGuard::for_obligation_resolve(&fixture.state);
            let held = held_labels();
            // Must be B→A→C order
            if held != vec!["B:Regions", "A:Tasks", "C:Obligations"] {
                return ConformanceResult::Fail {
                    reason: format!(
                        "Expected ['B:Regions', 'A:Tasks', 'C:Obligations'], got {:?}",
                        held
                    ),
                };
            }
        }

        if held_count() != 0 {
            return ConformanceResult::Fail {
                reason: format!("Locks not released: {} locks still held", held_count()),
            };
        }

        ConformanceResult::Pass
    }

    fn test_all_lock_order() -> ConformanceResult {
        if let Some(result) = lock_order_tracking_skip() {
            return result;
        }

        let fixture = ConformanceFixture::new();
        assert_eq!(held_count(), 0, "no locks held before test");

        {
            let _guard = ShardGuard::all(&fixture.state);
            let held = held_labels();
            // Must be B→A→C order
            if held != vec!["B:Regions", "A:Tasks", "C:Obligations"] {
                return ConformanceResult::Fail {
                    reason: format!(
                        "Expected ['B:Regions', 'A:Tasks', 'C:Obligations'], got {:?}",
                        held
                    ),
                };
            }
        }

        if held_count() != 0 {
            return ConformanceResult::Fail {
                reason: format!("Locks not released: {} locks still held", held_count()),
            };
        }

        ConformanceResult::Pass
    }

    // ─── Shard Access Compliance Tests ───

    fn test_tasks_only_shard_access() -> ConformanceResult {
        let fixture = ConformanceFixture::new();
        let guard = ShardGuard::tasks_only(&fixture.state);

        if guard.tasks.is_none() {
            return ConformanceResult::Fail {
                reason: "tasks_only guard missing tasks access".to_string(),
            };
        }
        if guard.regions.is_some() {
            return ConformanceResult::Fail {
                reason: "tasks_only guard should not have regions access".to_string(),
            };
        }
        if guard.obligations.is_some() {
            return ConformanceResult::Fail {
                reason: "tasks_only guard should not have obligations access".to_string(),
            };
        }

        ConformanceResult::Pass
    }

    fn test_regions_only_shard_access() -> ConformanceResult {
        let fixture = ConformanceFixture::new();
        let guard = ShardGuard::regions_only(&fixture.state);

        if guard.regions.is_none() {
            return ConformanceResult::Fail {
                reason: "regions_only guard missing regions access".to_string(),
            };
        }
        if guard.tasks.is_some() {
            return ConformanceResult::Fail {
                reason: "regions_only guard should not have tasks access".to_string(),
            };
        }
        if guard.obligations.is_some() {
            return ConformanceResult::Fail {
                reason: "regions_only guard should not have obligations access".to_string(),
            };
        }

        ConformanceResult::Pass
    }

    fn test_obligations_only_shard_access() -> ConformanceResult {
        let fixture = ConformanceFixture::new();
        let guard = ShardGuard::obligations_only(&fixture.state);

        if guard.obligations.is_none() {
            return ConformanceResult::Fail {
                reason: "obligations_only guard missing obligations access".to_string(),
            };
        }
        if guard.regions.is_some() {
            return ConformanceResult::Fail {
                reason: "obligations_only guard should not have regions access".to_string(),
            };
        }
        if guard.tasks.is_some() {
            return ConformanceResult::Fail {
                reason: "obligations_only guard should not have tasks access".to_string(),
            };
        }

        ConformanceResult::Pass
    }

    fn test_for_spawn_shard_access() -> ConformanceResult {
        let fixture = ConformanceFixture::new();
        let guard = ShardGuard::for_spawn(&fixture.state);

        if guard.regions.is_none() {
            return ConformanceResult::Fail {
                reason: "for_spawn guard missing regions access".to_string(),
            };
        }
        if guard.tasks.is_none() {
            return ConformanceResult::Fail {
                reason: "for_spawn guard missing tasks access".to_string(),
            };
        }
        if guard.obligations.is_some() {
            return ConformanceResult::Fail {
                reason: "for_spawn guard should not have obligations access".to_string(),
            };
        }

        ConformanceResult::Pass
    }

    fn test_for_obligation_shard_access() -> ConformanceResult {
        let fixture = ConformanceFixture::new();
        let guard = ShardGuard::for_obligation(&fixture.state);

        if guard.regions.is_none() {
            return ConformanceResult::Fail {
                reason: "for_obligation guard missing regions access".to_string(),
            };
        }
        if guard.obligations.is_none() {
            return ConformanceResult::Fail {
                reason: "for_obligation guard missing obligations access".to_string(),
            };
        }
        if guard.tasks.is_some() {
            return ConformanceResult::Fail {
                reason: "for_obligation guard should not have tasks access".to_string(),
            };
        }

        ConformanceResult::Pass
    }

    // ─── State Consistency Tests ───

    fn test_root_region_consistency() -> ConformanceResult {
        let fixture = ConformanceFixture::new();

        // Initially no root region
        if fixture.state.root_region().is_some() {
            return ConformanceResult::Fail {
                reason: "root_region should be None initially".to_string(),
            };
        }

        // Set root region
        let region = RegionId::from_arena(ArenaIndex::new(1, 0));
        if !fixture.state.set_root_region(region) {
            return ConformanceResult::Fail {
                reason: "set_root_region should return true on first set".to_string(),
            };
        }

        // Verify it's set
        if fixture.state.root_region() != Some(region) {
            return ConformanceResult::Fail {
                reason: "root_region should return the set value".to_string(),
            };
        }

        // Second set should fail
        let region2 = RegionId::from_arena(ArenaIndex::new(2, 0));
        if fixture.state.set_root_region(region2) {
            return ConformanceResult::Fail {
                reason: "set_root_region should return false on second set".to_string(),
            };
        }

        // Value should be unchanged
        if fixture.state.root_region() != Some(region) {
            return ConformanceResult::Fail {
                reason: "root_region should be unchanged after failed second set".to_string(),
            };
        }

        ConformanceResult::Pass
    }

    fn test_leak_count_consistency() -> ConformanceResult {
        let fixture = ConformanceFixture::new();

        // Initially zero
        if fixture.state.leak_count() != 0 {
            return ConformanceResult::Fail {
                reason: "leak_count should be 0 initially".to_string(),
            };
        }

        // Increment and verify
        let new_count = fixture.state.increment_leak_count();
        if new_count != 1 {
            return ConformanceResult::Fail {
                reason: format!("increment_leak_count should return 1, got {}", new_count),
            };
        }

        if fixture.state.leak_count() != 1 {
            return ConformanceResult::Fail {
                reason: "leak_count should be 1 after increment".to_string(),
            };
        }

        // Multiple increments
        for i in 2..=10 {
            let count = fixture.state.increment_leak_count();
            if count != i {
                return ConformanceResult::Fail {
                    reason: format!("increment_leak_count should return {}, got {}", i, count),
                };
            }
        }

        if fixture.state.leak_count() != 10 {
            return ConformanceResult::Fail {
                reason: "leak_count should be 10 after 10 increments".to_string(),
            };
        }

        ConformanceResult::Pass
    }

    fn test_current_time_consistency() -> ConformanceResult {
        let fixture = ConformanceFixture::new();

        // Initially zero
        if fixture.state.current_time() != Time::ZERO {
            return ConformanceResult::Fail {
                reason: "current_time should be Time::ZERO initially".to_string(),
            };
        }

        // Set time and verify
        let new_time = Time::from_nanos(42_000_000);
        fixture.state.set_time(new_time);

        if fixture.state.current_time() != new_time {
            return ConformanceResult::Fail {
                reason: "current_time should return the set value".to_string(),
            };
        }

        ConformanceResult::Pass
    }

    // ─── Deadlock Prevention Tests ───

    fn test_concurrent_guard_acquisition() -> ConformanceResult {
        let fixture = Arc::new(ConformanceFixture::new());
        let barrier = Arc::new(Barrier::new(4)); // 4 threads
        let mut handles = vec![];

        // Thread 1: tasks_only
        let fixture1 = Arc::clone(&fixture);
        let barrier1 = Arc::clone(&barrier);
        handles.push(thread::spawn(move || {
            barrier1.wait();
            for _ in 0..100 {
                let _guard = ShardGuard::tasks_only(&fixture1.state);
                thread::sleep(Duration::from_micros(10));
            }
        }));

        // Thread 2: regions_only
        let fixture2 = Arc::clone(&fixture);
        let barrier2 = Arc::clone(&barrier);
        handles.push(thread::spawn(move || {
            barrier2.wait();
            for _ in 0..100 {
                let _guard = ShardGuard::regions_only(&fixture2.state);
                thread::sleep(Duration::from_micros(10));
            }
        }));

        // Thread 3: for_spawn (B→A)
        let fixture3 = Arc::clone(&fixture);
        let barrier3 = Arc::clone(&barrier);
        handles.push(thread::spawn(move || {
            barrier3.wait();
            for _ in 0..50 {
                let _guard = ShardGuard::for_spawn(&fixture3.state);
                thread::sleep(Duration::from_micros(20));
            }
        }));

        // Thread 4: for_obligation (B→C)
        let fixture4 = Arc::clone(&fixture);
        let barrier4 = Arc::clone(&barrier);
        handles.push(thread::spawn(move || {
            barrier4.wait();
            for _ in 0..50 {
                let _guard = ShardGuard::for_obligation(&fixture4.state);
                thread::sleep(Duration::from_micros(20));
            }
        }));

        // Wait for all threads to complete (should not deadlock)
        let timeout = Duration::from_secs(10);
        let start = std::time::Instant::now();

        for handle in handles {
            if start.elapsed() > timeout {
                return ConformanceResult::Fail {
                    reason: "Concurrent guard acquisition timed out - possible deadlock"
                        .to_string(),
                };
            }
            if let Err(e) = handle.join() {
                return ConformanceResult::Fail {
                    reason: format!("Thread panicked: {:?}", e),
                };
            }
        }

        ConformanceResult::Pass
    }

    fn test_stress_concurrency() -> ConformanceResult {
        let fixture = Arc::new(ConformanceFixture::new());
        let barrier = Arc::new(Barrier::new(8)); // 8 threads for stress
        let mut handles = vec![];

        // Higher contention stress test
        for i in 0..8 {
            let fixture_clone = Arc::clone(&fixture);
            let barrier_clone = Arc::clone(&barrier);

            handles.push(thread::spawn(move || {
                barrier_clone.wait();

                for _ in 0..200 {
                    match i % 4 {
                        0 => {
                            let _guard = ShardGuard::tasks_only(&fixture_clone.state);
                        }
                        1 => {
                            let _guard = ShardGuard::regions_only(&fixture_clone.state);
                        }
                        2 => {
                            let _guard = ShardGuard::for_spawn(&fixture_clone.state);
                        }
                        3 => {
                            let _guard = ShardGuard::for_task_completed(&fixture_clone.state);
                        }
                        _ => unreachable!(),
                    }

                    // Interleave atomic operations
                    fixture_clone.state.increment_leak_count();
                    fixture_clone
                        .state
                        .set_time(Time::from_nanos(42 + i as u64));
                }
            }));
        }

        // Stress test timeout
        let timeout = Duration::from_secs(30);
        let start = std::time::Instant::now();

        for handle in handles {
            if start.elapsed() > timeout {
                return ConformanceResult::Fail {
                    reason: "Stress test timed out - possible deadlock or livelock".to_string(),
                };
            }
            if let Err(e) = handle.join() {
                return ConformanceResult::Fail {
                    reason: format!("Stress test thread panicked: {:?}", e),
                };
            }
        }

        ConformanceResult::Pass
    }
}

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

    #[test]
    fn run_sharded_state_conformance_suite() {
        let (passed, failed) = ShardedStateConformanceSuite::run_all();
        assert_eq!(failed, 0, "All conformance tests must pass");
        assert!(passed > 15, "Expected at least 15 conformance tests");
    }

    #[test]
    fn conformance_fixture_basic() {
        let fixture = ConformanceFixture::new();
        assert_eq!(fixture.state.leak_count(), 0);
        assert_eq!(fixture.state.current_time(), Time::ZERO);
        assert!(fixture.state.root_region().is_none());
    }
}