asupersync 0.3.1

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

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

#[cfg(feature = "lock-metrics")]
mod inner {
    use super::LockMetricsSnapshot;
    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). Separating them prevents cross-invalidation.
    #[derive(Debug)]
    #[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,
    }

    impl Default for Metrics {
        fn default() -> Self {
            Self {
                acquisitions: AtomicU64::new(0),
                contentions: AtomicU64::new(0),
                wait_ns: AtomicU64::new(0),
                max_wait_ns: AtomicU64::new(0),
                _pad: [0; 32],
                hold_ns: AtomicU64::new(0),
                max_hold_ns: AtomicU64::new(0),
            }
        }
    }

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

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

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

        /// Acquires the mutex, tracking contention metrics.
        pub fn lock(&self) -> LockResult<ContendedMutexGuard<'_, T>> {
            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),
            };

            let wait_ns = u64::try_from(start.elapsed().as_nanos()).unwrap_or(u64::MAX);

            self.metrics.acquisitions.fetch_add(1, Ordering::Relaxed);
            self.metrics.wait_ns.fetch_add(wait_ns, Ordering::Relaxed);
            Metrics::update_max(&self.metrics.max_wait_ns, wait_ns);

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

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

        /// 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) => {
                    self.metrics.acquisitions.fetch_add(1, Ordering::Relaxed);
                    Ok(ContendedMutexGuard {
                        guard: Some(guard),
                        acquired_at: Instant::now(),
                        metrics: &self.metrics,
                    })
                }
                Err(std::sync::TryLockError::WouldBlock) => {
                    Err(std::sync::TryLockError::WouldBlock)
                }
                Err(std::sync::TryLockError::Poisoned(poison)) => {
                    self.metrics.acquisitions.fetch_add(1, Ordering::Relaxed);
                    Err(std::sync::TryLockError::Poisoned(PoisonError::new(
                        ContendedMutexGuard {
                            guard: Some(poison.into_inner()),
                            acquired_at: Instant::now(),
                            metrics: &self.metrics,
                        },
                    )))
                }
            }
        }

        /// Returns a snapshot of the current metrics.
        pub fn snapshot(&self) -> LockMetricsSnapshot {
            LockMetricsSnapshot {
                name: self.name,
                acquisitions: self.metrics.acquisitions.load(Ordering::Relaxed),
                contentions: self.metrics.contentions.load(Ordering::Relaxed),
                wait_ns: self.metrics.wait_ns.load(Ordering::Relaxed),
                hold_ns: self.metrics.hold_ns.load(Ordering::Relaxed),
                max_wait_ns: self.metrics.max_wait_ns.load(Ordering::Relaxed),
                max_hold_ns: self.metrics.max_hold_ns.load(Ordering::Relaxed),
            }
        }

        /// Resets all metrics to zero.
        pub fn reset_metrics(&self) {
            self.metrics.acquisitions.store(0, Ordering::Relaxed);
            self.metrics.contentions.store(0, Ordering::Relaxed);
            self.metrics.wait_ns.store(0, Ordering::Relaxed);
            self.metrics.hold_ns.store(0, Ordering::Relaxed);
            self.metrics.max_wait_ns.store(0, Ordering::Relaxed);
            self.metrics.max_hold_ns.store(0, Ordering::Relaxed);
        }

        /// 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,
    }

    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());

            self.metrics.hold_ns.fetch_add(hold_ns, Ordering::Relaxed);
            Metrics::update_max(&self.metrics.max_hold_ns, 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 std::sync::{LockResult, Mutex, MutexGuard, PoisonError};

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

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

        /// Acquires the mutex (no instrumentation).
        #[inline]
        pub fn lock(&self) -> LockResult<ContendedMutexGuard<'_, T>> {
            match self.inner.lock() {
                Ok(guard) => Ok(ContendedMutexGuard { guard }),
                Err(poison) => Err(PoisonError::new(ContendedMutexGuard {
                    guard: poison.into_inner(),
                })),
            }
        }

        /// 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) => Ok(ContendedMutexGuard { guard }),
                Err(std::sync::TryLockError::WouldBlock) => {
                    Err(std::sync::TryLockError::WouldBlock)
                }
                Err(std::sync::TryLockError::Poisoned(poison)) => Err(
                    std::sync::TryLockError::Poisoned(PoisonError::new(ContendedMutexGuard {
                        guard: poison.into_inner(),
                    })),
                ),
            }
        }

        /// Returns an empty snapshot (metrics disabled).
        pub fn snapshot(&self) -> LockMetricsSnapshot {
            LockMetricsSnapshot {
                name: self.name,
                ..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>,
    }

    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: 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);
        let cloned = snap.clone();
        assert_eq!(cloned.name, snap.name);
    }

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