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
//! Feature-gated contention-instrumented mutex.
//!
//! When the `lock-metrics` feature is enabled, `ContendedMutex<T>` wraps
//! `std::sync::Mutex<T>` and tracks wait time, hold time, contention count,
//! and total acquisitions. When disabled, it's a zero-cost wrapper.
//!
//! # Usage
//!
//! ```ignore
//! use asupersync::sync::ContendedMutex;
//!
//! let m = ContendedMutex::new("tasks", 42);
//! {
//!     let guard = m.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
//!     // use *guard
//! }
//!
//! #[cfg(feature = "lock-metrics")]
//! {
//!     let snap = m.snapshot();
//!     println!("acquisitions: {}", snap.acquisitions);
//! }
//! ```

// LockResult, MutexGuard, PoisonError used in inner modules via std::sync::*.

/// Snapshot of lock contention metrics.
#[derive(Debug, Clone, Default)]
pub struct LockMetricsSnapshot {
    /// Human-readable name for this lock (e.g., "tasks", "regions").
    pub name: &'static str,
    /// Total number of successful lock acquisitions.
    pub acquisitions: u64,
    /// Number of acquisitions where the lock was already held (contended).
    pub contentions: u64,
    /// Cumulative nanoseconds spent waiting to acquire the lock.
    pub wait_ns: u64,
    /// Cumulative nanoseconds the lock was held.
    pub hold_ns: u64,
    /// Maximum single wait duration in nanoseconds.
    pub max_wait_ns: u64,
    /// Maximum single hold duration in nanoseconds.
    pub max_hold_ns: u64,
    /// Exact p95 wait duration in nanoseconds for observed acquisitions.
    pub p95_wait_ns: u64,
    /// Exact p999 wait duration in nanoseconds for observed acquisitions.
    pub p999_wait_ns: u64,
    /// Exact p95 hold duration in nanoseconds for observed guards.
    pub p95_hold_ns: u64,
    /// Exact p999 hold duration in nanoseconds for observed guards.
    pub p999_hold_ns: u64,
    /// Instrumentation mode used to produce this snapshot.
    pub instrumentation_mode: &'static str,
}

// ── Feature-gated implementation ──────────────────────────────────────────

#[cfg(feature = "lock-metrics")]
mod inner {
    use super::LockMetricsSnapshot;
    use crate::sync::lock_ordering::{self, LockRank};
    use std::sync::atomic::{AtomicU64, Ordering};
    use std::sync::{LockResult, Mutex, MutexGuard, PoisonError};
    use std::time::Instant;

    /// Metrics counters split into two cache lines to avoid false sharing.
    /// Lock-path counters (acquisitions, contentions, wait_ns, max_wait_ns) are
    /// updated during lock(); unlock-path counters (hold_ns, max_hold_ns) are
    /// updated during drop(Guard). Exact samples are feature-gated with this
    /// instrumentation mode so the default build stays on the no-op path.
    #[derive(Debug, Default)]
    #[repr(C, align(64))]
    struct Metrics {
        // ── Cache line 1: updated on lock() ──
        acquisitions: AtomicU64,
        contentions: AtomicU64,
        wait_ns: AtomicU64,
        max_wait_ns: AtomicU64,
        // Pad to 64 bytes (4 × 8 = 32 bytes of data, 32 bytes padding)
        _pad: [u8; 32],
        // ── Cache line 2: updated on drop(Guard) ──
        hold_ns: AtomicU64,
        max_hold_ns: AtomicU64,
        wait_samples: Mutex<Vec<u64>>,
        hold_samples: Mutex<Vec<u64>>,
    }

    const MAX_SAMPLES: usize = 10000; // Prevent unbounded growth

    impl Metrics {
        fn update_max(current: &AtomicU64, value: u64) {
            current.fetch_max(value, Ordering::Relaxed);
        }

        fn record_acquire(&self, wait_ns: u64, contended: bool) {
            self.acquisitions.fetch_add(1, Ordering::Relaxed);
            self.wait_ns.fetch_add(wait_ns, Ordering::Relaxed);
            Self::update_max(&self.max_wait_ns, wait_ns);

            // Bound sample collection to prevent memory leak
            let mut samples = self
                .wait_samples
                .lock()
                .unwrap_or_else(PoisonError::into_inner);
            if samples.len() >= MAX_SAMPLES {
                // Remove oldest samples to maintain bound (FIFO eviction)
                samples.drain(0..MAX_SAMPLES / 4);
            }
            samples.push(wait_ns);

            if contended {
                self.contentions.fetch_add(1, Ordering::Relaxed);
            }
        }

        fn record_hold(&self, hold_ns: u64) {
            self.hold_ns.fetch_add(hold_ns, Ordering::Relaxed);
            Self::update_max(&self.max_hold_ns, hold_ns);

            // Bound sample collection to prevent memory leak
            let mut samples = self
                .hold_samples
                .lock()
                .unwrap_or_else(PoisonError::into_inner);
            if samples.len() >= MAX_SAMPLES {
                // Remove oldest samples to maintain bound (FIFO eviction)
                samples.drain(0..MAX_SAMPLES / 4);
            }
            samples.push(hold_ns);
        }

        fn quantile(samples: &Mutex<Vec<u64>>, numerator: usize, denominator: usize) -> u64 {
            let mut values = samples
                .lock()
                .unwrap_or_else(PoisonError::into_inner)
                .clone();
            if values.is_empty() {
                return 0;
            }

            values.sort_unstable();
            let last_index = values.len() - 1;
            let rank = last_index
                .saturating_mul(numerator)
                .saturating_add(denominator / 2)
                / denominator;
            values[rank.min(last_index)]
        }

        fn snapshot(&self, name: &'static str) -> LockMetricsSnapshot {
            LockMetricsSnapshot {
                name,
                acquisitions: self.acquisitions.load(Ordering::Relaxed),
                contentions: self.contentions.load(Ordering::Relaxed),
                wait_ns: self.wait_ns.load(Ordering::Relaxed),
                hold_ns: self.hold_ns.load(Ordering::Relaxed),
                max_wait_ns: self.max_wait_ns.load(Ordering::Relaxed),
                max_hold_ns: self.max_hold_ns.load(Ordering::Relaxed),
                p95_wait_ns: Self::quantile(&self.wait_samples, 95, 100),
                p999_wait_ns: Self::quantile(&self.wait_samples, 999, 1000),
                p95_hold_ns: Self::quantile(&self.hold_samples, 95, 100),
                p999_hold_ns: Self::quantile(&self.hold_samples, 999, 1000),
                instrumentation_mode: "opt_in_lock_metrics",
            }
        }

        fn reset(&self) {
            // Use sequential consistency to ensure atomic reset from reader perspective
            self.acquisitions.store(0, Ordering::SeqCst);
            self.contentions.store(0, Ordering::SeqCst);
            self.wait_ns.store(0, Ordering::SeqCst);
            self.hold_ns.store(0, Ordering::SeqCst);
            self.max_wait_ns.store(0, Ordering::SeqCst);
            self.max_hold_ns.store(0, Ordering::SeqCst);
            self.wait_samples
                .lock()
                .unwrap_or_else(PoisonError::into_inner)
                .clear();
            self.hold_samples
                .lock()
                .unwrap_or_else(PoisonError::into_inner)
                .clear();
        }
    }

    /// Contention-instrumented mutex. Tracks wait/hold time and contention.
    #[derive(Debug)]
    pub struct ContendedMutex<T> {
        inner: Mutex<T>,
        metrics: Metrics,
        name: &'static str,
        rank: Option<LockRank>,
    }

    impl<T> ContendedMutex<T> {
        /// Creates a new instrumented mutex with the given name and value.
        pub fn new(name: &'static str, value: T) -> Self {
            let rank = LockRank::from_name(name);
            Self {
                inner: Mutex::new(value),
                metrics: Metrics::default(),
                name,
                rank,
            }
        }

        /// Acquires the mutex, tracking contention metrics.
        pub fn lock(&self) -> LockResult<ContendedMutexGuard<'_, T>> {
            // Check lock ordering before acquisition (debug builds only)
            if let Some(rank) = self.rank {
                lock_ordering::check_acquire(self.name, rank);
            }

            let start = Instant::now();

            let (result, contended) = match self.inner.try_lock() {
                Ok(guard) => (Ok(guard), false),
                Err(std::sync::TryLockError::Poisoned(poison)) => (Err(poison), false),
                Err(std::sync::TryLockError::WouldBlock) => (self.inner.lock(), true),
            };

            // Use consistent timing: capture acquisition time once
            let acquired_at = Instant::now();
            let wait_ns =
                u64::try_from(acquired_at.duration_since(start).as_nanos()).unwrap_or(u64::MAX);

            self.metrics.record_acquire(wait_ns, contended);

            // Record lock acquisition for ordering tracking
            if let Some(rank) = self.rank {
                lock_ordering::record_acquire(self.name, rank);
            }

            match result {
                Ok(guard) => Ok(ContendedMutexGuard {
                    guard: Some(guard),
                    acquired_at,
                    metrics: &self.metrics,
                    name: self.name,
                    rank: self.rank,
                }),
                Err(poison) => Err(PoisonError::new(ContendedMutexGuard {
                    guard: Some(poison.into_inner()),
                    acquired_at,
                    metrics: &self.metrics,
                    name: self.name,
                    rank: self.rank,
                })),
            }
        }

        /// Attempts to acquire the mutex without blocking.
        pub fn try_lock(
            &self,
        ) -> Result<ContendedMutexGuard<'_, T>, std::sync::TryLockError<ContendedMutexGuard<'_, T>>>
        {
            match self.inner.try_lock() {
                Ok(guard) => {
                    // Check and record lock ordering for successful try_lock
                    if let Some(rank) = self.rank {
                        lock_ordering::check_acquire(self.name, rank);
                        lock_ordering::record_acquire(self.name, rank);
                    }

                    let acquired_at = Instant::now();
                    self.metrics.record_acquire(0, false);
                    Ok(ContendedMutexGuard {
                        guard: Some(guard),
                        acquired_at,
                        metrics: &self.metrics,
                        name: self.name,
                        rank: self.rank,
                    })
                }
                Err(std::sync::TryLockError::WouldBlock) => {
                    Err(std::sync::TryLockError::WouldBlock)
                }
                Err(std::sync::TryLockError::Poisoned(poison)) => {
                    if let Some(rank) = self.rank {
                        lock_ordering::check_acquire(self.name, rank);
                        lock_ordering::record_acquire(self.name, rank);
                    }
                    let acquired_at = Instant::now();
                    self.metrics.record_acquire(0, false);
                    Err(std::sync::TryLockError::Poisoned(PoisonError::new(
                        ContendedMutexGuard {
                            guard: Some(poison.into_inner()),
                            acquired_at,
                            metrics: &self.metrics,
                            name: self.name,
                            rank: self.rank,
                        },
                    )))
                }
            }
        }

        /// Returns a snapshot of the current metrics.
        pub fn snapshot(&self) -> LockMetricsSnapshot {
            self.metrics.snapshot(self.name)
        }

        /// Resets all metrics to zero.
        pub fn reset_metrics(&self) {
            self.metrics.reset();
        }

        /// Returns the lock name.
        pub fn name(&self) -> &'static str {
            self.name
        }
    }

    /// Guard that tracks hold time on drop.
    pub struct ContendedMutexGuard<'a, T> {
        guard: Option<MutexGuard<'a, T>>,
        acquired_at: Instant,
        metrics: &'a Metrics,
        name: &'static str,
        rank: Option<LockRank>,
    }

    impl<T> std::ops::Deref for ContendedMutexGuard<'_, T> {
        type Target = T;
        fn deref(&self) -> &T {
            self.guard.as_ref().expect("guard used after drop")
        }
    }

    impl<T> std::ops::DerefMut for ContendedMutexGuard<'_, T> {
        fn deref_mut(&mut self) -> &mut T {
            self.guard.as_mut().expect("guard used after drop")
        }
    }

    impl<T> Drop for ContendedMutexGuard<'_, T> {
        fn drop(&mut self) {
            let hold_ns = u64::try_from(self.acquired_at.elapsed().as_nanos()).unwrap_or(u64::MAX);
            // Drop the inner guard (releases the mutex) BEFORE updating metrics
            // to minimize the critical section length.
            drop(self.guard.take());

            // Record lock release for ordering tracking
            if let Some(rank) = self.rank {
                lock_ordering::record_release(self.name, rank);
            }

            self.metrics.record_hold(hold_ns);
        }
    }

    impl<T: std::fmt::Debug> std::fmt::Debug for ContendedMutexGuard<'_, T> {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            f.debug_struct("ContendedMutexGuard")
                .field("data", &self.guard)
                .finish()
        }
    }
}

// ── No-op implementation (feature disabled) ───────────────────────────────

#[cfg(not(feature = "lock-metrics"))]
mod inner {
    use super::LockMetricsSnapshot;
    use crate::sync::lock_ordering::{self, LockRank};
    use std::sync::{LockResult, Mutex, MutexGuard, PoisonError};

    /// Zero-cost mutex wrapper (metrics disabled).
    #[derive(Debug)]
    pub struct ContendedMutex<T> {
        inner: Mutex<T>,
        name: &'static str,
        rank: Option<LockRank>,
    }

    impl<T> ContendedMutex<T> {
        /// Creates a new mutex with the given name and value.
        #[inline]
        pub fn new(name: &'static str, value: T) -> Self {
            let rank = LockRank::from_name(name);
            Self {
                inner: Mutex::new(value),
                name,
                rank,
            }
        }

        /// Acquires the mutex (no instrumentation).
        #[inline]
        pub fn lock(&self) -> LockResult<ContendedMutexGuard<'_, T>> {
            // Check lock ordering before acquisition (debug builds only)
            if let Some(rank) = self.rank {
                lock_ordering::check_acquire(self.name, rank);
            }

            match self.inner.lock() {
                Ok(guard) => {
                    // Record lock acquisition for ordering tracking
                    if let Some(rank) = self.rank {
                        lock_ordering::record_acquire(self.name, rank);
                    }
                    Ok(ContendedMutexGuard {
                        guard,
                        name: self.name,
                        rank: self.rank,
                    })
                }
                Err(poison) => {
                    // Record lock acquisition even for poisoned mutex
                    if let Some(rank) = self.rank {
                        lock_ordering::record_acquire(self.name, rank);
                    }
                    Err(PoisonError::new(ContendedMutexGuard {
                        guard: poison.into_inner(),
                        name: self.name,
                        rank: self.rank,
                    }))
                }
            }
        }

        /// Attempts to acquire the mutex without blocking.
        pub fn try_lock(
            &self,
        ) -> Result<ContendedMutexGuard<'_, T>, std::sync::TryLockError<ContendedMutexGuard<'_, T>>>
        {
            match self.inner.try_lock() {
                Ok(guard) => {
                    // Check and record lock ordering for successful try_lock
                    if let Some(rank) = self.rank {
                        lock_ordering::check_acquire(self.name, rank);
                        lock_ordering::record_acquire(self.name, rank);
                    }
                    Ok(ContendedMutexGuard {
                        guard,
                        name: self.name,
                        rank: self.rank,
                    })
                }
                Err(std::sync::TryLockError::WouldBlock) => {
                    Err(std::sync::TryLockError::WouldBlock)
                }
                Err(std::sync::TryLockError::Poisoned(poison)) => {
                    if let Some(rank) = self.rank {
                        lock_ordering::check_acquire(self.name, rank);
                        lock_ordering::record_acquire(self.name, rank);
                    }
                    Err(std::sync::TryLockError::Poisoned(PoisonError::new(
                        ContendedMutexGuard {
                            guard: poison.into_inner(),
                            name: self.name,
                            rank: self.rank,
                        },
                    )))
                }
            }
        }

        /// Returns an empty snapshot (metrics disabled).
        pub fn snapshot(&self) -> LockMetricsSnapshot {
            LockMetricsSnapshot {
                name: self.name,
                instrumentation_mode: "disabled",
                ..Default::default()
            }
        }

        /// No-op (metrics disabled).
        pub fn reset_metrics(&self) {}

        /// Returns the lock name.
        pub fn name(&self) -> &'static str {
            self.name
        }
    }

    /// Zero-cost guard wrapper (metrics disabled).
    pub struct ContendedMutexGuard<'a, T> {
        guard: MutexGuard<'a, T>,
        name: &'static str,
        rank: Option<LockRank>,
    }

    impl<T> std::ops::Deref for ContendedMutexGuard<'_, T> {
        type Target = T;
        #[inline]
        fn deref(&self) -> &T {
            &self.guard
        }
    }

    impl<T> std::ops::DerefMut for ContendedMutexGuard<'_, T> {
        #[inline]
        fn deref_mut(&mut self) -> &mut T {
            &mut self.guard
        }
    }

    impl<T> Drop for ContendedMutexGuard<'_, T> {
        fn drop(&mut self) {
            // Record lock release for ordering tracking
            if let Some(rank) = self.rank {
                lock_ordering::record_release(self.name, rank);
            }
        }
    }

    impl<T: std::fmt::Debug> std::fmt::Debug for ContendedMutexGuard<'_, T> {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            f.debug_struct("ContendedMutexGuard")
                .field("data", &*self.guard)
                .finish()
        }
    }
}

pub use inner::{ContendedMutex, ContendedMutexGuard};

#[cfg(test)]
#[allow(clippy::significant_drop_tightening)]
mod tests {
    use super::*;
    use std::sync::Arc;
    #[cfg(feature = "lock-metrics")]
    use std::thread;

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

    #[test]
    fn basic_lock_unlock() {
        init_test("basic_lock_unlock");
        let m = ContendedMutex::new("test", 42);
        {
            let guard = m.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
            crate::assert_with_log!(*guard == 42, "value", 42, *guard);
            drop(guard);
        }
        crate::test_complete!("basic_lock_unlock");
    }

    #[test]
    fn mutate_through_guard() {
        init_test("mutate_through_guard");
        let m = ContendedMutex::new("test", 0);
        {
            let mut guard = m.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
            *guard = 99;
        }
        let guard = m.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
        crate::assert_with_log!(*guard == 99, "mutated value", 99, *guard);
        drop(guard);
        crate::test_complete!("mutate_through_guard");
    }

    #[test]
    fn try_lock_succeeds_when_free() {
        init_test("try_lock_succeeds_when_free");
        let m = ContendedMutex::new("test", 42);
        let guard = m.try_lock().expect("should succeed");
        crate::assert_with_log!(*guard == 42, "try_lock value", 42, *guard);
        drop(guard);
        crate::test_complete!("try_lock_succeeds_when_free");
    }

    #[test]
    fn try_lock_fails_when_held() {
        init_test("try_lock_fails_when_held");
        let m = ContendedMutex::new("test", 42);
        let _guard = m.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
        let is_err = m.try_lock().is_err();
        crate::assert_with_log!(is_err, "try_lock fails", true, is_err);
        crate::test_complete!("try_lock_fails_when_held");
    }

    #[test]
    fn snapshot_returns_name() {
        init_test("snapshot_returns_name");
        let m = ContendedMutex::new("my-shard", 0);
        let snap = m.snapshot();
        crate::assert_with_log!(snap.name == "my-shard", "name", "my-shard", snap.name);
        crate::test_complete!("snapshot_returns_name");
    }

    #[test]
    fn name_accessor() {
        init_test("name_accessor");
        let m = ContendedMutex::new("tasks", 0);
        crate::assert_with_log!(m.name() == "tasks", "name", "tasks", m.name());
        crate::test_complete!("name_accessor");
    }

    #[test]
    fn reset_metrics_no_panic() {
        init_test("reset_metrics_no_panic");
        let m = ContendedMutex::new("test", 0);
        {
            let _g = m.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
        }
        m.reset_metrics();
        let snap = m.snapshot();
        // After reset, metrics should be zero (when feature enabled) or always zero
        crate::assert_with_log!(
            snap.acquisitions == 0,
            "acquisitions after reset",
            0u64,
            snap.acquisitions
        );
        crate::test_complete!("reset_metrics_no_panic");
    }

    #[cfg(feature = "lock-metrics")]
    #[test]
    fn metrics_track_acquisitions() {
        init_test("metrics_track_acquisitions");
        let m = ContendedMutex::new("test", 0);
        for _ in 0..10 {
            let _g = m.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
        }
        let snap = m.snapshot();
        crate::assert_with_log!(
            snap.acquisitions == 10,
            "acquisitions",
            10u64,
            snap.acquisitions
        );
        crate::test_complete!("metrics_track_acquisitions");
    }

    #[cfg(feature = "lock-metrics")]
    #[test]
    fn metrics_track_hold_time() {
        init_test("metrics_track_hold_time");
        let m = ContendedMutex::new("test", 0);
        {
            let _g = m.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
            std::thread::sleep(std::time::Duration::from_millis(5));
        }
        let snap = m.snapshot();
        // Hold time should be at least 4ms (allowing for timing variance)
        crate::assert_with_log!(
            snap.hold_ns >= 4_000_000,
            "hold_ns >= 4ms",
            true,
            snap.hold_ns >= 4_000_000
        );
        crate::assert_with_log!(
            snap.max_hold_ns >= 4_000_000,
            "max_hold_ns >= 4ms",
            true,
            snap.max_hold_ns >= 4_000_000
        );
        crate::test_complete!("metrics_track_hold_time");
    }

    #[cfg(feature = "lock-metrics")]
    #[test]
    fn metrics_track_contention() {
        init_test("metrics_track_contention");
        let m = Arc::new(ContendedMutex::new("test", 0));

        // Hold the lock while another thread tries to acquire
        let guard = m.lock().unwrap_or_else(std::sync::PoisonError::into_inner);

        let m2 = Arc::clone(&m);
        let handle = thread::spawn(move || {
            let _g = m2.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
        });

        // Give the other thread time to contend
        thread::sleep(std::time::Duration::from_millis(10));
        drop(guard);
        handle.join().expect("thread panicked");

        let snap = m.snapshot();
        crate::assert_with_log!(
            snap.contentions >= 1,
            "contentions >= 1",
            true,
            snap.contentions >= 1
        );
        crate::assert_with_log!(snap.wait_ns > 0, "wait_ns > 0", true, snap.wait_ns > 0);
        crate::test_complete!("metrics_track_contention");
    }

    #[cfg(feature = "lock-metrics")]
    #[test]
    fn reset_clears_all_metrics() {
        init_test("reset_clears_all_metrics");
        let m = ContendedMutex::new("test", 0);
        {
            let _g = m.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
        }
        let before = m.snapshot();
        crate::assert_with_log!(
            before.acquisitions == 1,
            "before reset",
            1u64,
            before.acquisitions
        );

        m.reset_metrics();
        let after = m.snapshot();
        crate::assert_with_log!(
            after.acquisitions == 0,
            "after reset acquisitions",
            0u64,
            after.acquisitions
        );
        crate::assert_with_log!(
            after.hold_ns == 0,
            "after reset hold_ns",
            0u64,
            after.hold_ns
        );
        crate::test_complete!("reset_clears_all_metrics");
    }

    #[cfg(feature = "lock-metrics")]
    #[test]
    fn poisoned_lock_does_not_count_as_contention() {
        init_test("poisoned_lock_does_not_count_as_contention");
        let m = Arc::new(ContendedMutex::new("test", 0u8));
        let m2 = Arc::clone(&m);

        let poisoner = thread::spawn(move || {
            let _guard = m2.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
            panic!("intentional poison");
        });
        let _ = poisoner.join();

        let poison_err = m.lock().expect_err("lock should be poisoned");
        drop(poison_err.into_inner());

        let snap = m.snapshot();
        crate::assert_with_log!(
            snap.contentions == 0,
            "poison is not contention",
            0u64,
            snap.contentions
        );
        crate::test_complete!("poisoned_lock_does_not_count_as_contention");
    }

    // =========================================================================
    // Wave 33: Data-type trait coverage
    // =========================================================================

    #[test]
    fn lock_metrics_snapshot_debug_clone_default() {
        let snap = LockMetricsSnapshot::default();
        let dbg = format!("{snap:?}");
        assert!(dbg.contains("LockMetricsSnapshot"));
        assert_eq!(snap.acquisitions, 0);
        assert_eq!(snap.contentions, 0);
        assert_eq!(snap.wait_ns, 0);
        assert_eq!(snap.hold_ns, 0);
        assert_eq!(snap.max_wait_ns, 0);
        assert_eq!(snap.max_hold_ns, 0);
        assert_eq!(snap.p95_wait_ns, 0);
        assert_eq!(snap.p999_wait_ns, 0);
        assert_eq!(snap.p95_hold_ns, 0);
        assert_eq!(snap.p999_hold_ns, 0);
        let cloned = snap.clone();
        assert_eq!(cloned.name, snap.name);
    }

    #[cfg(feature = "lock-metrics")]
    #[test]
    fn metrics_snapshot_reports_tail_latencies() {
        init_test("metrics_snapshot_reports_tail_latencies");
        let m = ContendedMutex::new("tasks", 0u32);

        for _ in 0..4 {
            let mut guard = m.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
            *guard += 1;
        }

        let snap = m.snapshot();
        crate::assert_with_log!(
            snap.instrumentation_mode == "opt_in_lock_metrics",
            "instrumentation mode",
            "opt_in_lock_metrics",
            snap.instrumentation_mode
        );
        crate::assert_with_log!(
            snap.acquisitions == 4,
            "acquisitions",
            4u64,
            snap.acquisitions
        );
        crate::assert_with_log!(
            snap.p95_wait_ns <= snap.max_wait_ns,
            "p95 wait <= max wait",
            true,
            snap.p95_wait_ns <= snap.max_wait_ns
        );
        crate::assert_with_log!(
            snap.p999_wait_ns <= snap.max_wait_ns,
            "p999 wait <= max wait",
            true,
            snap.p999_wait_ns <= snap.max_wait_ns
        );
        crate::assert_with_log!(
            snap.p95_hold_ns <= snap.max_hold_ns,
            "p95 hold <= max hold",
            true,
            snap.p95_hold_ns <= snap.max_hold_ns
        );
        crate::assert_with_log!(
            snap.p999_hold_ns <= snap.max_hold_ns,
            "p999 hold <= max hold",
            true,
            snap.p999_hold_ns <= snap.max_hold_ns
        );
        crate::test_complete!("metrics_snapshot_reports_tail_latencies");
    }

    #[test]
    fn contended_mutex_debug() {
        let m = ContendedMutex::new("test", 42_i32);
        let dbg = format!("{m:?}");
        assert!(dbg.contains("ContendedMutex"));
    }

    #[test]
    fn contended_mutex_guard_debug() {
        let m = ContendedMutex::new("test", 42_i32);
        let guard = m.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
        let dbg = format!("{guard:?}");
        assert!(dbg.contains("ContendedMutexGuard"));
        drop(guard);
    }

    #[test]
    fn try_lock_returns_poisoned_after_panic() {
        init_test("try_lock_returns_poisoned_after_panic");
        let m = Arc::new(ContendedMutex::new("test", 7u32));
        let m2 = Arc::clone(&m);
        let poisoner = std::thread::spawn(move || {
            let _guard = m2.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
            panic!("deliberate poison");
        });
        let _ = poisoner.join();

        let result = m.try_lock();
        let is_poisoned = matches!(result, Err(std::sync::TryLockError::Poisoned(_)));
        crate::assert_with_log!(is_poisoned, "try_lock returns Poisoned", true, is_poisoned);

        // Recover data through the poison error.
        if let Err(std::sync::TryLockError::Poisoned(pe)) = m.try_lock() {
            let guard = pe.into_inner();
            crate::assert_with_log!(*guard == 7, "data preserved", 7u32, *guard);
        }
        crate::test_complete!("try_lock_returns_poisoned_after_panic");
    }

    #[cfg(feature = "lock-metrics")]
    #[test]
    fn hold_time_recorded_on_panic_in_critical_section() {
        init_test("hold_time_recorded_on_panic_in_critical_section");
        let m = Arc::new(ContendedMutex::new("test", 0u32));
        let m2 = Arc::clone(&m);

        let handle = std::thread::spawn(move || {
            let _guard = m2.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
            std::thread::sleep(std::time::Duration::from_millis(5));
            panic!("panic while holding guard");
        });
        let _ = handle.join();

        // Guard::drop should have recorded hold time even though thread panicked.
        let snap = m.snapshot();
        crate::assert_with_log!(
            snap.hold_ns >= 4_000_000,
            "hold_ns recorded despite panic",
            true,
            snap.hold_ns >= 4_000_000
        );
        crate::test_complete!("hold_time_recorded_on_panic_in_critical_section");
    }
}