lock-db 0.3.0

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

#[cfg(loom)]
use loom::sync::{Mutex, MutexGuard};
#[cfg(not(loom))]
use std::sync::{Mutex, MutexGuard};

use std::collections::HashMap;

use crate::{KeyRange, LockError, LockMode, ResourceId, TxnId};

/// Multiplier for Fibonacci hashing: 2^64 divided by the golden ratio.
const FIB_HASH: u64 = 0x9E37_79B9_7F4A_7C15;

/// A transaction holding a resource, and the mode it holds it in.
#[derive(Clone, Copy)]
struct Holder {
    txn: TxnId,
    mode: LockMode,
}

/// The set of transactions currently holding one resource.
///
/// Holders are kept in an unordered `Vec` because the common case is a handful
/// of shared readers or a single writer; a linear scan over a short, contiguous
/// slice beats the constant overhead and indirection of a map for those sizes.
struct LockEntry {
    holders: Vec<Holder>,
}

impl LockEntry {
    #[inline]
    fn new() -> Self {
        Self {
            holders: Vec::new(),
        }
    }
}

/// A transaction holding a key range in a space, and the mode it holds.
#[derive(Clone, Copy)]
struct RangeHolder {
    txn: TxnId,
    range: KeyRange,
    mode: LockMode,
}

/// The active range locks in one key space.
///
/// Held in an unordered `Vec` and scanned linearly for overlap on each request.
/// Overlap is not a key-equality lookup, so a hash map does not help; an
/// interval tree would lower the asymptotic cost but is heavier and is left for
/// a later release if profiling shows range contention dominates.
struct RangeSpace {
    holders: Vec<RangeHolder>,
}

impl RangeSpace {
    #[inline]
    fn new() -> Self {
        Self {
            holders: Vec::new(),
        }
    }
}

/// The mutable state of one shard.
struct ShardInner {
    /// Point locks: resources with at least one holder, keyed by resource id.
    locks: HashMap<ResourceId, LockEntry>,
    /// Reverse index: the resources each transaction holds *in this shard*.
    by_txn: HashMap<TxnId, Vec<ResourceId>>,
    /// Range locks, keyed by the space (e.g. an index) they protect.
    ranges: HashMap<ResourceId, RangeSpace>,
    /// Reverse index for range locks: the (space, range) pairs each transaction
    /// holds *in this shard*.
    range_by_txn: HashMap<TxnId, Vec<(ResourceId, KeyRange)>>,
}

impl ShardInner {
    fn new() -> Self {
        Self {
            locks: HashMap::new(),
            by_txn: HashMap::new(),
            ranges: HashMap::new(),
            range_by_txn: HashMap::new(),
        }
    }
}

/// One independently locked partition of the table.
struct Shard {
    inner: Mutex<ShardInner>,
}

/// A sharded lock table mapping resources to the transactions that hold them.
///
/// `LockManager` is the primary entry point of the crate. It is `Send + Sync`
/// and is meant to be shared behind an [`std::sync::Arc`] across all worker
/// threads; every method takes `&self`, so no outer lock is needed.
///
/// # Examples
///
/// ```
/// use lock_db::{LockManager, LockMode, ResourceId, TxnId};
///
/// let lm = LockManager::new();
/// let row = ResourceId::new(100);
/// let (t1, t2) = (TxnId::new(1), TxnId::new(2));
///
/// // Two transactions read the same row concurrently.
/// lm.try_acquire(t1, row, LockMode::Shared).unwrap();
/// lm.try_acquire(t2, row, LockMode::Shared).unwrap();
/// assert_eq!(lm.holder_count(row), 2);
///
/// // Neither can take it exclusively while the other reads.
/// assert!(lm.try_acquire(t1, row, LockMode::Exclusive).is_err());
///
/// // After both release, an exclusive lock is free to take.
/// lm.release(t1, row).unwrap();
/// lm.release(t2, row).unwrap();
/// lm.try_acquire(t1, row, LockMode::Exclusive).unwrap();
/// ```
#[must_use = "a LockManager that is dropped immediately releases every lock it holds"]
pub struct LockManager {
    shards: Box<[Shard]>,
    /// `log2(shards.len())`; `0` when there is a single shard.
    bits: u32,
}

impl LockManager {
    /// Creates a lock manager with a shard count chosen for the current machine.
    ///
    /// The count scales with the number of available CPUs (rounded up to a power
    /// of two) so that contention on any single shard mutex stays low on
    /// multi-core systems. Use [`with_shards`](Self::with_shards) to pin an
    /// exact count, for example in tests or on memory-constrained targets.
    ///
    /// # Examples
    ///
    /// ```
    /// use lock_db::LockManager;
    ///
    /// let lm = LockManager::new();
    /// assert!(lm.shards().is_power_of_two());
    /// ```
    pub fn new() -> Self {
        let parallelism = std::thread::available_parallelism()
            .map(|n| n.get())
            .unwrap_or(1);
        let target = (parallelism.saturating_mul(4))
            .next_power_of_two()
            .clamp(16, 1024);
        Self::with_shards(target)
    }

    /// Creates a lock manager with an explicit shard count.
    ///
    /// `shards` is rounded up to the next power of two (and a request of `0` is
    /// treated as `1`), which lets the shard lookup use a shift instead of a
    /// remainder. More shards reduce contention but cost a mutex and two small
    /// maps each; fewer shards save memory at the cost of more collisions.
    ///
    /// # Examples
    ///
    /// ```
    /// use lock_db::LockManager;
    ///
    /// // Rounded up to the next power of two.
    /// assert_eq!(LockManager::with_shards(5).shards(), 8);
    /// assert_eq!(LockManager::with_shards(0).shards(), 1);
    /// ```
    pub fn with_shards(shards: usize) -> Self {
        let n = shards.max(1).next_power_of_two();
        let bits = n.trailing_zeros();
        let mut v = Vec::with_capacity(n);
        for _ in 0..n {
            v.push(Shard {
                inner: Mutex::new(ShardInner::new()),
            });
        }
        Self {
            shards: v.into_boxed_slice(),
            bits,
        }
    }

    /// Returns the number of shards in the table.
    ///
    /// Always a power of two.
    #[inline]
    #[must_use]
    pub fn shards(&self) -> usize {
        self.shards.len()
    }

    /// Tries to acquire `mode` on `res` for `txn` without blocking.
    ///
    /// The request is granted immediately and `Ok(())` is returned when:
    ///
    /// - `txn` already holds a lock on `res` that [covers](LockMode::covers)
    ///   `mode` (re-acquisition is idempotent, and asking for a weaker mode than
    ///   you hold is a no-op);
    /// - `txn` already holds `res` in some mode and the
    ///   [join](LockMode::join) of that mode with `mode` is compatible with
    ///   every other holder (an in-place upgrade — for example shared to
    ///   exclusive when sole holder, or shared plus intention-exclusive to SIX);
    ///   or
    /// - `txn` holds nothing on `res` and `mode` is compatible with every
    ///   current holder.
    ///
    /// Otherwise nothing is changed and [`LockError::Conflict`] is returned. The
    /// caller decides whether to retry, wait, or abort; this method never blocks
    /// the calling thread.
    ///
    /// # Errors
    ///
    /// Returns [`LockError::Conflict`] if the lock cannot be granted right now.
    ///
    /// # Examples
    ///
    /// ```
    /// use lock_db::{LockError, LockManager, LockMode, ResourceId, TxnId};
    ///
    /// let lm = LockManager::new();
    /// let key = ResourceId::new(7);
    /// let t = TxnId::new(1);
    ///
    /// // Upgrade a shared lock to exclusive while sole holder.
    /// lm.try_acquire(t, key, LockMode::Shared).unwrap();
    /// lm.try_acquire(t, key, LockMode::Exclusive).unwrap();
    /// assert_eq!(lm.mode_held(t, key), Some(LockMode::Exclusive));
    ///
    /// // A second reader now conflicts with the upgraded exclusive lock.
    /// let r = lm.try_acquire(TxnId::new(2), key, LockMode::Shared);
    /// assert_eq!(r, Err(LockError::Conflict));
    /// ```
    pub fn try_acquire(
        &self,
        txn: TxnId,
        res: ResourceId,
        mode: LockMode,
    ) -> Result<(), LockError> {
        let mut guard = self.lock_shard(res);
        let ShardInner { locks, by_txn, .. } = &mut *guard;
        let entry = locks.entry(res).or_insert_with(LockEntry::new);

        if let Some(pos) = entry.holders.iter().position(|h| h.txn == txn) {
            let current = entry.holders[pos].mode;
            if current.covers(mode) {
                return Ok(());
            }
            // Upgrade: the transaction ends up holding the join (least upper
            // bound) of what it has and what it asked for. The upgraded mode
            // must be compatible with every *other* holder.
            let target = current.join(mode);
            let blocked = entry
                .holders
                .iter()
                .enumerate()
                .any(|(i, h)| i != pos && !h.mode.compatible_with(target));
            if blocked {
                return Err(LockError::Conflict);
            }
            entry.holders[pos].mode = target;
            return Ok(());
        }

        if entry.holders.iter().all(|h| h.mode.compatible_with(mode)) {
            entry.holders.push(Holder { txn, mode });
            by_txn.entry(txn).or_default().push(res);
            Ok(())
        } else {
            // The entry already had holders (an empty one would have matched the
            // vacuous `all` above and been granted), so nothing to clean up.
            Err(LockError::Conflict)
        }
    }

    /// Releases the lock `txn` holds on `res`.
    ///
    /// # Errors
    ///
    /// Returns [`LockError::NotHeld`] if `txn` holds no lock on `res`, which
    /// usually means a double release or a bookkeeping mismatch in the caller.
    ///
    /// # Examples
    ///
    /// ```
    /// use lock_db::{LockError, LockManager, LockMode, ResourceId, TxnId};
    ///
    /// let lm = LockManager::new();
    /// let key = ResourceId::new(3);
    /// let t = TxnId::new(1);
    ///
    /// lm.try_acquire(t, key, LockMode::Exclusive).unwrap();
    /// lm.release(t, key).unwrap();
    /// assert_eq!(lm.release(t, key), Err(LockError::NotHeld));
    /// ```
    pub fn release(&self, txn: TxnId, res: ResourceId) -> Result<(), LockError> {
        let mut guard = self.lock_shard(res);
        let ShardInner { locks, by_txn, .. } = &mut *guard;

        let entry = match locks.get_mut(&res) {
            Some(entry) => entry,
            None => return Err(LockError::NotHeld),
        };
        let pos = match entry.holders.iter().position(|h| h.txn == txn) {
            Some(pos) => pos,
            None => return Err(LockError::NotHeld),
        };

        let _ = entry.holders.swap_remove(pos);
        if entry.holders.is_empty() {
            let _ = locks.remove(&res);
        }
        Self::forget_resource(by_txn, txn, res);
        Ok(())
    }

    /// Releases every lock held by `txn` across the whole table — both point
    /// locks and range locks.
    ///
    /// This is the call a transaction layer makes at commit or abort to drop a
    /// transaction's entire lock set at once. It returns the number of locks
    /// released, and is proportional to that number rather than to the size of
    /// the table.
    ///
    /// # Examples
    ///
    /// ```
    /// use lock_db::{KeyRange, LockManager, LockMode, ResourceId, TxnId};
    ///
    /// let lm = LockManager::new();
    /// let t = TxnId::new(1);
    /// for id in 0..5 {
    ///     lm.try_acquire(t, ResourceId::new(id), LockMode::Exclusive).unwrap();
    /// }
    /// lm.try_acquire_range(t, ResourceId::new(99), KeyRange::point(1), LockMode::Shared).unwrap();
    ///
    /// assert_eq!(lm.release_all(t), 6); // 5 point locks + 1 range lock
    /// assert_eq!(lm.release_all(t), 0); // idempotent once empty
    /// ```
    pub fn release_all(&self, txn: TxnId) -> usize {
        let mut released = 0;
        for shard in self.shards.iter() {
            let mut guard = Self::lock(shard);
            let ShardInner {
                locks,
                by_txn,
                ranges,
                range_by_txn,
            } = &mut *guard;

            if let Some(resources) = by_txn.remove(&txn) {
                for res in resources {
                    if let Some(entry) = locks.get_mut(&res) {
                        if let Some(pos) = entry.holders.iter().position(|h| h.txn == txn) {
                            let _ = entry.holders.swap_remove(pos);
                            released += 1;
                            if entry.holders.is_empty() {
                                let _ = locks.remove(&res);
                            }
                        }
                    }
                }
            }

            if let Some(spaces) = range_by_txn.remove(&txn) {
                for (space, range) in spaces {
                    if let Some(rs) = ranges.get_mut(&space) {
                        if let Some(pos) = rs
                            .holders
                            .iter()
                            .position(|h| h.txn == txn && h.range == range)
                        {
                            let _ = rs.holders.swap_remove(pos);
                            released += 1;
                            if rs.holders.is_empty() {
                                let _ = ranges.remove(&space);
                            }
                        }
                    }
                }
            }
        }
        released
    }

    /// Returns the number of transactions currently holding `res`.
    ///
    /// Mostly useful for diagnostics and tests; in steady state this is `0`,
    /// `1` for an exclusive lock, or the reader count for a shared lock.
    ///
    /// # Examples
    ///
    /// ```
    /// use lock_db::{LockManager, LockMode, ResourceId, TxnId};
    ///
    /// let lm = LockManager::new();
    /// let key = ResourceId::new(1);
    /// assert_eq!(lm.holder_count(key), 0);
    /// lm.try_acquire(TxnId::new(1), key, LockMode::Shared).unwrap();
    /// assert_eq!(lm.holder_count(key), 1);
    /// ```
    #[must_use]
    pub fn holder_count(&self, res: ResourceId) -> usize {
        let guard = self.lock_shard(res);
        guard.locks.get(&res).map_or(0, |e| e.holders.len())
    }

    /// Returns the mode in which `txn` holds `res`, or `None` if it holds no
    /// lock on it.
    ///
    /// # Examples
    ///
    /// ```
    /// use lock_db::{LockManager, LockMode, ResourceId, TxnId};
    ///
    /// let lm = LockManager::new();
    /// let key = ResourceId::new(1);
    /// let t = TxnId::new(1);
    /// assert_eq!(lm.mode_held(t, key), None);
    /// lm.try_acquire(t, key, LockMode::Shared).unwrap();
    /// assert_eq!(lm.mode_held(t, key), Some(LockMode::Shared));
    /// ```
    #[must_use]
    pub fn mode_held(&self, txn: TxnId, res: ResourceId) -> Option<LockMode> {
        let guard = self.lock_shard(res);
        guard
            .locks
            .get(&res)
            .and_then(|e| e.holders.iter().find(|h| h.txn == txn))
            .map(|h| h.mode)
    }

    /// Tries to acquire `mode` over the key range `range` in key space `space`,
    /// for `txn`, without blocking.
    ///
    /// A range lock protects a contiguous span of keys — use it to stop another
    /// transaction from inserting into, or writing within, a range you have
    /// read (phantom and predicate protection). `space` identifies the key space
    /// the range lives in, typically an index; ranges in different spaces never
    /// conflict.
    ///
    /// The request is granted unless some **other** transaction already holds an
    /// [overlapping](KeyRange::overlaps) range in `space` in an
    /// [incompatible](LockMode::compatible_with) mode. The same transaction may
    /// hold several ranges in a space, including overlapping ones; range locks
    /// are not merged or upgraded.
    ///
    /// # Errors
    ///
    /// Returns [`LockError::Conflict`] if an overlapping, incompatible range is
    /// held by another transaction.
    ///
    /// # Examples
    ///
    /// ```
    /// use lock_db::{KeyRange, LockError, LockManager, LockMode, ResourceId, TxnId};
    ///
    /// let lm = LockManager::new();
    /// let index = ResourceId::new(1);
    ///
    /// // A read lock over [100, 200].
    /// lm.try_acquire_range(TxnId::new(1), index, KeyRange::new(100, 200).unwrap(), LockMode::Shared).unwrap();
    ///
    /// // Another reader may share the overlapping range...
    /// lm.try_acquire_range(TxnId::new(2), index, KeyRange::new(150, 250).unwrap(), LockMode::Shared).unwrap();
    ///
    /// // ...but a writer inside it conflicts.
    /// assert_eq!(
    ///     lm.try_acquire_range(TxnId::new(3), index, KeyRange::point(150), LockMode::Exclusive),
    ///     Err(LockError::Conflict),
    /// );
    /// ```
    pub fn try_acquire_range(
        &self,
        txn: TxnId,
        space: ResourceId,
        range: KeyRange,
        mode: LockMode,
    ) -> Result<(), LockError> {
        let mut guard = self.lock_shard(space);
        let ShardInner {
            ranges,
            range_by_txn,
            ..
        } = &mut *guard;
        let rs = ranges.entry(space).or_insert_with(RangeSpace::new);

        let conflict = rs
            .holders
            .iter()
            .any(|h| h.txn != txn && h.range.overlaps(range) && !h.mode.compatible_with(mode));
        if conflict {
            // A conflict implies a pre-existing holder, so the space entry is
            // non-empty and there is nothing to clean up.
            return Err(LockError::Conflict);
        }

        rs.holders.push(RangeHolder { txn, range, mode });
        range_by_txn.entry(txn).or_default().push((space, range));
        Ok(())
    }

    /// Releases a range lock `txn` holds over `range` in `space`.
    ///
    /// Matches on the transaction and the exact range. If the transaction holds
    /// several locks on the identical range (in different modes), one is
    /// released per call.
    ///
    /// # Errors
    ///
    /// Returns [`LockError::NotHeld`] if `txn` holds no lock on that exact range
    /// in `space`.
    ///
    /// # Examples
    ///
    /// ```
    /// use lock_db::{KeyRange, LockError, LockManager, LockMode, ResourceId, TxnId};
    ///
    /// let lm = LockManager::new();
    /// let index = ResourceId::new(1);
    /// let r = KeyRange::new(1, 10).unwrap();
    /// let t = TxnId::new(1);
    ///
    /// lm.try_acquire_range(t, index, r, LockMode::Exclusive).unwrap();
    /// lm.release_range(t, index, r).unwrap();
    /// assert_eq!(lm.release_range(t, index, r), Err(LockError::NotHeld));
    /// ```
    pub fn release_range(
        &self,
        txn: TxnId,
        space: ResourceId,
        range: KeyRange,
    ) -> Result<(), LockError> {
        let mut guard = self.lock_shard(space);
        let ShardInner {
            ranges,
            range_by_txn,
            ..
        } = &mut *guard;

        let rs = match ranges.get_mut(&space) {
            Some(rs) => rs,
            None => return Err(LockError::NotHeld),
        };
        let pos = match rs
            .holders
            .iter()
            .position(|h| h.txn == txn && h.range == range)
        {
            Some(pos) => pos,
            None => return Err(LockError::NotHeld),
        };

        let _ = rs.holders.swap_remove(pos);
        if rs.holders.is_empty() {
            let _ = ranges.remove(&space);
        }
        Self::forget_range(range_by_txn, txn, space, range);
        Ok(())
    }

    /// Returns the number of range locks currently held in `space`.
    ///
    /// Counts every holder, across all transactions and modes. Mostly useful
    /// for diagnostics and tests.
    ///
    /// # Examples
    ///
    /// ```
    /// use lock_db::{KeyRange, LockManager, LockMode, ResourceId, TxnId};
    ///
    /// let lm = LockManager::new();
    /// let index = ResourceId::new(1);
    /// assert_eq!(lm.range_count(index), 0);
    /// lm.try_acquire_range(TxnId::new(1), index, KeyRange::point(1), LockMode::Shared).unwrap();
    /// assert_eq!(lm.range_count(index), 1);
    /// ```
    #[must_use]
    pub fn range_count(&self, space: ResourceId) -> usize {
        let guard = self.lock_shard(space);
        guard.ranges.get(&space).map_or(0, |rs| rs.holders.len())
    }

    /// Drops `res` from a transaction's reverse-index entry, removing the entry
    /// entirely once the transaction holds nothing else in the shard.
    #[inline]
    fn forget_resource(by_txn: &mut HashMap<TxnId, Vec<ResourceId>>, txn: TxnId, res: ResourceId) {
        if let Some(resources) = by_txn.get_mut(&txn) {
            if let Some(pos) = resources.iter().position(|r| *r == res) {
                let _ = resources.swap_remove(pos);
            }
            if resources.is_empty() {
                let _ = by_txn.remove(&txn);
            }
        }
    }

    /// Drops one `(space, range)` pair from a transaction's range reverse-index
    /// entry, removing the entry entirely once it is empty.
    #[inline]
    fn forget_range(
        range_by_txn: &mut HashMap<TxnId, Vec<(ResourceId, KeyRange)>>,
        txn: TxnId,
        space: ResourceId,
        range: KeyRange,
    ) {
        if let Some(held) = range_by_txn.get_mut(&txn) {
            if let Some(pos) = held.iter().position(|(s, r)| *s == space && *r == range) {
                let _ = held.swap_remove(pos);
            }
            if held.is_empty() {
                let _ = range_by_txn.remove(&txn);
            }
        }
    }

    /// Locks and returns the shard that owns `res`.
    #[inline]
    fn lock_shard(&self, res: ResourceId) -> MutexGuard<'_, ShardInner> {
        Self::lock(&self.shards[self.shard_index(res)])
    }

    /// Locks a shard, recovering its guard if the mutex was poisoned.
    ///
    /// Critical sections in this module perform only infallible map and vector
    /// operations and never panic, so poisoning cannot leave inconsistent
    /// state. Recovering the guard keeps the lock manager available rather than
    /// propagating a poison error that no caller could act on.
    #[inline]
    fn lock(shard: &Shard) -> MutexGuard<'_, ShardInner> {
        match shard.inner.lock() {
            Ok(guard) => guard,
            Err(poisoned) => poisoned.into_inner(),
        }
    }

    /// Maps a resource id to a shard index via Fibonacci hashing.
    #[inline]
    fn shard_index(&self, res: ResourceId) -> usize {
        if self.bits == 0 {
            return 0;
        }
        let hash = res.get().wrapping_mul(FIB_HASH);
        // Take the top `bits` bits: the most-mixed end of a multiplicative hash.
        (hash >> (u64::BITS - self.bits)) as usize
    }
}

impl Default for LockManager {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(all(test, not(loom)))]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::{FIB_HASH, LockManager};
    use crate::{KeyRange, LockError, LockMode, ResourceId, TxnId};

    fn ids(t: u64, r: u64) -> (TxnId, ResourceId) {
        (TxnId::new(t), ResourceId::new(r))
    }

    fn kr(start: u64, end: u64) -> KeyRange {
        KeyRange::new(start, end).unwrap()
    }

    #[test]
    fn test_shared_locks_coexist() {
        let lm = LockManager::new();
        let r = ResourceId::new(1);
        lm.try_acquire(TxnId::new(1), r, LockMode::Shared).unwrap();
        lm.try_acquire(TxnId::new(2), r, LockMode::Shared).unwrap();
        lm.try_acquire(TxnId::new(3), r, LockMode::Shared).unwrap();
        assert_eq!(lm.holder_count(r), 3);
    }

    #[test]
    fn test_exclusive_excludes_shared() {
        let lm = LockManager::new();
        let (t1, r) = ids(1, 1);
        lm.try_acquire(t1, r, LockMode::Exclusive).unwrap();
        assert_eq!(
            lm.try_acquire(TxnId::new(2), r, LockMode::Shared),
            Err(LockError::Conflict)
        );
    }

    #[test]
    fn test_intention_shared_and_intention_exclusive_coexist() {
        let lm = LockManager::new();
        let r = ResourceId::new(1);
        lm.try_acquire(TxnId::new(1), r, LockMode::IntentionShared)
            .unwrap();
        lm.try_acquire(TxnId::new(2), r, LockMode::IntentionExclusive)
            .unwrap();
        assert_eq!(lm.holder_count(r), 2);
    }

    #[test]
    fn test_intention_exclusive_blocks_shared() {
        let lm = LockManager::new();
        let r = ResourceId::new(1);
        lm.try_acquire(TxnId::new(1), r, LockMode::IntentionExclusive)
            .unwrap();
        assert_eq!(
            lm.try_acquire(TxnId::new(2), r, LockMode::Shared),
            Err(LockError::Conflict)
        );
        // ...but another IX or an IS is fine.
        lm.try_acquire(TxnId::new(3), r, LockMode::IntentionExclusive)
            .unwrap();
        lm.try_acquire(TxnId::new(4), r, LockMode::IntentionShared)
            .unwrap();
    }

    #[test]
    fn test_shared_plus_intention_exclusive_upgrades_to_six() {
        let lm = LockManager::new();
        let r = ResourceId::new(1);
        let t = TxnId::new(1);
        lm.try_acquire(t, r, LockMode::Shared).unwrap();
        // Same txn now intends to write part of the subtree: S join IX = SIX.
        lm.try_acquire(t, r, LockMode::IntentionExclusive).unwrap();
        assert_eq!(lm.mode_held(t, r), Some(LockMode::SharedIntentionExclusive));
        // An intention-shared holder still coexists with SIX.
        lm.try_acquire(TxnId::new(2), r, LockMode::IntentionShared)
            .unwrap();
        // But a second reader does not.
        assert_eq!(
            lm.try_acquire(TxnId::new(3), r, LockMode::Shared),
            Err(LockError::Conflict)
        );
    }

    #[test]
    fn test_intention_shared_upgrades_to_exclusive_when_sole_holder() {
        let lm = LockManager::new();
        let r = ResourceId::new(1);
        let t = TxnId::new(1);
        lm.try_acquire(t, r, LockMode::IntentionShared).unwrap();
        lm.try_acquire(t, r, LockMode::Exclusive).unwrap();
        assert_eq!(lm.mode_held(t, r), Some(LockMode::Exclusive));
    }

    #[test]
    fn test_upgrade_to_six_blocked_by_other_reader() {
        let lm = LockManager::new();
        let r = ResourceId::new(1);
        lm.try_acquire(TxnId::new(1), r, LockMode::Shared).unwrap();
        lm.try_acquire(TxnId::new(2), r, LockMode::Shared).unwrap();
        // Txn 1 wants IX too (-> SIX), but SIX is incompatible with txn 2's S.
        assert_eq!(
            lm.try_acquire(TxnId::new(1), r, LockMode::IntentionExclusive),
            Err(LockError::Conflict)
        );
        // The original shared lock is intact.
        assert_eq!(lm.mode_held(TxnId::new(1), r), Some(LockMode::Shared));
    }

    #[test]
    fn test_hierarchy_protocol_row_write_under_table_intent() {
        // Model a database/table/page/row hierarchy as four resources, and run
        // the standard protocol: IX coarse-to-fine, then X on the row.
        let lm = LockManager::new();
        let (db, table, page, row) = (
            ResourceId::new(1),
            ResourceId::new(2),
            ResourceId::new(3),
            ResourceId::new(4),
        );
        let writer = TxnId::new(1);
        for res in [db, table, page] {
            lm.try_acquire(writer, res, LockMode::IntentionExclusive)
                .unwrap();
        }
        lm.try_acquire(writer, row, LockMode::Exclusive).unwrap();

        // A concurrent reader can still take IS down to a different page/row.
        let reader = TxnId::new(2);
        for res in [db, table] {
            lm.try_acquire(reader, res, LockMode::IntentionShared)
                .unwrap();
        }
        // But it cannot read the row the writer holds exclusively.
        assert_eq!(
            lm.try_acquire(reader, row, LockMode::Shared),
            Err(LockError::Conflict)
        );
    }

    #[test]
    fn test_exclusive_excludes_exclusive() {
        let lm = LockManager::new();
        let (t1, r) = ids(1, 1);
        lm.try_acquire(t1, r, LockMode::Exclusive).unwrap();
        assert_eq!(
            lm.try_acquire(TxnId::new(2), r, LockMode::Exclusive),
            Err(LockError::Conflict)
        );
    }

    #[test]
    fn test_shared_blocks_other_exclusive() {
        let lm = LockManager::new();
        let (t1, r) = ids(1, 1);
        lm.try_acquire(t1, r, LockMode::Shared).unwrap();
        assert_eq!(
            lm.try_acquire(TxnId::new(2), r, LockMode::Exclusive),
            Err(LockError::Conflict)
        );
    }

    #[test]
    fn test_reacquire_same_mode_is_idempotent() {
        let lm = LockManager::new();
        let (t1, r) = ids(1, 1);
        lm.try_acquire(t1, r, LockMode::Shared).unwrap();
        lm.try_acquire(t1, r, LockMode::Shared).unwrap();
        assert_eq!(lm.holder_count(r), 1);
    }

    #[test]
    fn test_request_weaker_than_held_is_noop() {
        let lm = LockManager::new();
        let (t1, r) = ids(1, 1);
        lm.try_acquire(t1, r, LockMode::Exclusive).unwrap();
        // Asking for shared while holding exclusive keeps the stronger mode.
        lm.try_acquire(t1, r, LockMode::Shared).unwrap();
        assert_eq!(lm.mode_held(t1, r), Some(LockMode::Exclusive));
        assert_eq!(lm.holder_count(r), 1);
    }

    #[test]
    fn test_upgrade_sole_holder_succeeds() {
        let lm = LockManager::new();
        let (t1, r) = ids(1, 1);
        lm.try_acquire(t1, r, LockMode::Shared).unwrap();
        lm.try_acquire(t1, r, LockMode::Exclusive).unwrap();
        assert_eq!(lm.mode_held(t1, r), Some(LockMode::Exclusive));
        assert_eq!(lm.holder_count(r), 1);
    }

    #[test]
    fn test_upgrade_blocked_by_other_reader() {
        let lm = LockManager::new();
        let r = ResourceId::new(1);
        lm.try_acquire(TxnId::new(1), r, LockMode::Shared).unwrap();
        lm.try_acquire(TxnId::new(2), r, LockMode::Shared).unwrap();
        assert_eq!(
            lm.try_acquire(TxnId::new(1), r, LockMode::Exclusive),
            Err(LockError::Conflict)
        );
        // The failed upgrade left the original shared lock intact.
        assert_eq!(lm.mode_held(TxnId::new(1), r), Some(LockMode::Shared));
    }

    #[test]
    fn test_release_frees_resource_for_exclusive() {
        let lm = LockManager::new();
        let r = ResourceId::new(1);
        lm.try_acquire(TxnId::new(1), r, LockMode::Shared).unwrap();
        lm.try_acquire(TxnId::new(2), r, LockMode::Shared).unwrap();
        lm.release(TxnId::new(1), r).unwrap();
        // One reader remains, exclusive still blocked.
        assert!(
            lm.try_acquire(TxnId::new(3), r, LockMode::Exclusive)
                .is_err()
        );
        lm.release(TxnId::new(2), r).unwrap();
        lm.try_acquire(TxnId::new(3), r, LockMode::Exclusive)
            .unwrap();
    }

    #[test]
    fn test_release_not_held_errors() {
        let lm = LockManager::new();
        let (t1, r) = ids(1, 1);
        assert_eq!(lm.release(t1, r), Err(LockError::NotHeld));
        lm.try_acquire(t1, r, LockMode::Shared).unwrap();
        assert_eq!(lm.release(TxnId::new(9), r), Err(LockError::NotHeld));
    }

    #[test]
    fn test_double_release_errors() {
        let lm = LockManager::new();
        let (t1, r) = ids(1, 1);
        lm.try_acquire(t1, r, LockMode::Exclusive).unwrap();
        lm.release(t1, r).unwrap();
        assert_eq!(lm.release(t1, r), Err(LockError::NotHeld));
    }

    #[test]
    fn test_release_all_drops_every_lock() {
        let lm = LockManager::with_shards(8);
        let t = TxnId::new(1);
        for id in 0..50 {
            lm.try_acquire(t, ResourceId::new(id), LockMode::Exclusive)
                .unwrap();
        }
        assert_eq!(lm.release_all(t), 50);
        for id in 0..50 {
            assert_eq!(lm.holder_count(ResourceId::new(id)), 0);
        }
        assert_eq!(lm.release_all(t), 0);
    }

    #[test]
    fn test_release_all_leaves_other_txns_alone() {
        let lm = LockManager::new();
        let r = ResourceId::new(1);
        lm.try_acquire(TxnId::new(1), r, LockMode::Shared).unwrap();
        lm.try_acquire(TxnId::new(2), r, LockMode::Shared).unwrap();
        assert_eq!(lm.release_all(TxnId::new(1)), 1);
        assert_eq!(lm.mode_held(TxnId::new(2), r), Some(LockMode::Shared));
        assert_eq!(lm.holder_count(r), 1);
    }

    #[test]
    fn test_resource_fully_released_can_be_taken_exclusively() {
        let lm = LockManager::new();
        let r = ResourceId::new(42);
        lm.try_acquire(TxnId::new(1), r, LockMode::Exclusive)
            .unwrap();
        lm.release(TxnId::new(1), r).unwrap();
        assert_eq!(lm.holder_count(r), 0);
        lm.try_acquire(TxnId::new(2), r, LockMode::Exclusive)
            .unwrap();
    }

    // ---- range locks ----

    #[test]
    fn test_range_shared_overlap_coexists() {
        let lm = LockManager::new();
        let space = ResourceId::new(1);
        lm.try_acquire_range(TxnId::new(1), space, kr(0, 100), LockMode::Shared)
            .unwrap();
        lm.try_acquire_range(TxnId::new(2), space, kr(50, 150), LockMode::Shared)
            .unwrap();
        assert_eq!(lm.range_count(space), 2);
    }

    #[test]
    fn test_range_exclusive_conflicts_on_overlap() {
        let lm = LockManager::new();
        let space = ResourceId::new(1);
        lm.try_acquire_range(TxnId::new(1), space, kr(100, 200), LockMode::Shared)
            .unwrap();
        assert_eq!(
            lm.try_acquire_range(
                TxnId::new(2),
                space,
                KeyRange::point(150),
                LockMode::Exclusive
            ),
            Err(LockError::Conflict)
        );
    }

    #[test]
    fn test_range_disjoint_ranges_do_not_conflict() {
        let lm = LockManager::new();
        let space = ResourceId::new(1);
        lm.try_acquire_range(TxnId::new(1), space, kr(0, 100), LockMode::Exclusive)
            .unwrap();
        lm.try_acquire_range(TxnId::new(2), space, kr(101, 200), LockMode::Exclusive)
            .unwrap();
    }

    #[test]
    fn test_range_adjacent_inclusive_bounds_conflict() {
        let lm = LockManager::new();
        let space = ResourceId::new(1);
        lm.try_acquire_range(TxnId::new(1), space, kr(0, 100), LockMode::Exclusive)
            .unwrap();
        // [100, 200] shares key 100 with [0, 100].
        assert_eq!(
            lm.try_acquire_range(TxnId::new(2), space, kr(100, 200), LockMode::Shared),
            Err(LockError::Conflict)
        );
    }

    #[test]
    fn test_range_different_spaces_independent() {
        let lm = LockManager::new();
        lm.try_acquire_range(
            TxnId::new(1),
            ResourceId::new(1),
            kr(0, 100),
            LockMode::Exclusive,
        )
        .unwrap();
        // Same range, different space: no conflict.
        lm.try_acquire_range(
            TxnId::new(2),
            ResourceId::new(2),
            kr(0, 100),
            LockMode::Exclusive,
        )
        .unwrap();
    }

    #[test]
    fn test_range_same_txn_overlap_allowed() {
        let lm = LockManager::new();
        let space = ResourceId::new(1);
        let t = TxnId::new(1);
        lm.try_acquire_range(t, space, kr(0, 100), LockMode::Exclusive)
            .unwrap();
        // A transaction does not conflict with its own ranges.
        lm.try_acquire_range(t, space, kr(50, 150), LockMode::Exclusive)
            .unwrap();
        assert_eq!(lm.range_count(space), 2);
    }

    #[test]
    fn test_range_release_frees_overlap() {
        let lm = LockManager::new();
        let space = ResourceId::new(1);
        let r = kr(100, 200);
        lm.try_acquire_range(TxnId::new(1), space, r, LockMode::Exclusive)
            .unwrap();
        lm.release_range(TxnId::new(1), space, r).unwrap();
        assert_eq!(lm.range_count(space), 0);
        // Now another writer can take an overlapping range.
        lm.try_acquire_range(
            TxnId::new(2),
            space,
            KeyRange::point(150),
            LockMode::Exclusive,
        )
        .unwrap();
    }

    #[test]
    fn test_range_release_not_held_errors() {
        let lm = LockManager::new();
        let space = ResourceId::new(1);
        assert_eq!(
            lm.release_range(TxnId::new(1), space, kr(0, 10)),
            Err(LockError::NotHeld)
        );
        lm.try_acquire_range(TxnId::new(1), space, kr(0, 10), LockMode::Shared)
            .unwrap();
        // Wrong range is NotHeld.
        assert_eq!(
            lm.release_range(TxnId::new(1), space, kr(0, 11)),
            Err(LockError::NotHeld)
        );
    }

    #[test]
    fn test_release_all_drops_point_and_range_locks() {
        let lm = LockManager::new();
        let t = TxnId::new(1);
        for id in 0..3 {
            lm.try_acquire(t, ResourceId::new(id), LockMode::Exclusive)
                .unwrap();
        }
        lm.try_acquire_range(t, ResourceId::new(100), kr(0, 10), LockMode::Shared)
            .unwrap();
        lm.try_acquire_range(t, ResourceId::new(100), kr(20, 30), LockMode::Shared)
            .unwrap();
        assert_eq!(lm.release_all(t), 5); // 3 point + 2 range
        assert_eq!(lm.range_count(ResourceId::new(100)), 0);
        assert_eq!(lm.release_all(t), 0);
    }

    #[test]
    fn test_release_all_range_leaves_other_txn() {
        let lm = LockManager::new();
        let space = ResourceId::new(1);
        lm.try_acquire_range(TxnId::new(1), space, kr(0, 100), LockMode::Shared)
            .unwrap();
        lm.try_acquire_range(TxnId::new(2), space, kr(0, 100), LockMode::Shared)
            .unwrap();
        assert_eq!(lm.release_all(TxnId::new(1)), 1);
        assert_eq!(lm.range_count(space), 1);
    }

    #[test]
    fn test_range_intention_modes_coexist() {
        // IS and IX range locks are compatible, just like point locks.
        let lm = LockManager::new();
        let space = ResourceId::new(1);
        lm.try_acquire_range(TxnId::new(1), space, kr(0, 100), LockMode::IntentionShared)
            .unwrap();
        lm.try_acquire_range(
            TxnId::new(2),
            space,
            kr(0, 100),
            LockMode::IntentionExclusive,
        )
        .unwrap();
        assert_eq!(lm.range_count(space), 2);
    }

    #[test]
    fn test_with_shards_rounds_up_to_power_of_two() {
        assert_eq!(LockManager::with_shards(1).shards(), 1);
        assert_eq!(LockManager::with_shards(3).shards(), 4);
        assert_eq!(LockManager::with_shards(5).shards(), 8);
        assert_eq!(LockManager::with_shards(0).shards(), 1);
        assert_eq!(LockManager::with_shards(64).shards(), 64);
    }

    #[test]
    fn test_single_shard_routes_everything_to_index_zero() {
        let lm = LockManager::with_shards(1);
        for id in 0..1000 {
            assert_eq!(lm.shard_index(ResourceId::new(id)), 0);
        }
    }

    #[test]
    fn test_shard_index_within_bounds() {
        let lm = LockManager::with_shards(16);
        for id in 0..10_000 {
            assert!(lm.shard_index(ResourceId::new(id)) < 16);
        }
    }

    #[test]
    fn test_sequential_ids_spread_across_shards() {
        let lm = LockManager::with_shards(16);
        let mut seen = [false; 16];
        for id in 0..256 {
            seen[lm.shard_index(ResourceId::new(id))] = true;
        }
        // Fibonacci hashing should touch every shard well before 256 ids.
        assert!(seen.iter().all(|&hit| hit));
    }

    #[test]
    fn test_locks_in_different_shards_are_independent() {
        // Two resources that hash to different shards do not interfere.
        let lm = LockManager::with_shards(16);
        let a = ResourceId::new(1);
        let b = ResourceId::new(2);
        lm.try_acquire(TxnId::new(1), a, LockMode::Exclusive)
            .unwrap();
        lm.try_acquire(TxnId::new(2), b, LockMode::Exclusive)
            .unwrap();
        assert_eq!(lm.holder_count(a), 1);
        assert_eq!(lm.holder_count(b), 1);
    }

    #[test]
    fn test_fib_hash_constant_is_odd() {
        // A multiplicative-hash multiplier must be odd to be a bijection mod 2^64.
        assert_eq!(FIB_HASH & 1, 1);
    }

    #[test]
    fn test_concurrent_shared_acquire_release_is_consistent() {
        use std::sync::Arc;
        use std::thread;

        let lm = Arc::new(LockManager::new());
        let r = ResourceId::new(7);
        let mut handles = Vec::new();
        for t in 0..8u64 {
            let lm = Arc::clone(&lm);
            handles.push(thread::spawn(move || {
                let txn = TxnId::new(t);
                for _ in 0..1000 {
                    lm.try_acquire(txn, r, LockMode::Shared).unwrap();
                    lm.release(txn, r).unwrap();
                }
            }));
        }
        for h in handles {
            h.join().unwrap();
        }
        // Every acquire was paired with a release; the resource is free.
        assert_eq!(lm.holder_count(r), 0);
    }

    #[test]
    fn test_concurrent_exclusive_is_mutually_exclusive() {
        use std::sync::Arc;
        use std::sync::atomic::{AtomicUsize, Ordering};
        use std::thread;

        let lm = Arc::new(LockManager::new());
        let active = Arc::new(AtomicUsize::new(0));
        let r = ResourceId::new(11);
        let mut handles = Vec::new();
        for t in 0..8u64 {
            let lm = Arc::clone(&lm);
            let active = Arc::clone(&active);
            handles.push(thread::spawn(move || {
                let txn = TxnId::new(t);
                for _ in 0..2000 {
                    if lm.try_acquire(txn, r, LockMode::Exclusive).is_ok() {
                        // While we hold X, no one else may be inside this region.
                        let inside = active.fetch_add(1, Ordering::SeqCst);
                        assert_eq!(inside, 0);
                        active.fetch_sub(1, Ordering::SeqCst);
                        lm.release(txn, r).unwrap();
                    }
                }
            }));
        }
        for h in handles {
            h.join().unwrap();
        }
        assert_eq!(lm.holder_count(r), 0);
    }
}