forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

lock.rs627 lines, 22.1 KiBHistoryRawDownload
1//! Lock-order-checked mutexes.
2//!
3//! This module provides a small utility to prevent deadlocks by enforcing a
4//! strict, per-thread lock acquisition order across a set of related locks.
5//!
6//! Core ideas:
7//! - Locks are created from a [`LoroLockGroup`]. Locks in the same group share
8//! a per-thread stack that tracks the last acquired lock kind.
9//! - Each lock has an associated [`LockKind`]. A thread may only acquire locks
10//! in strictly increasing kind order (e.g. `Txn` → `OpLog` → `DocState` → `DiffCalculator`).
11//! - Locks must be released in the reverse order they were acquired (LIFO).
12//! - Violations are detected and reported with helpful panics that include the
13//! callsite (via `#[track_caller]`) and a backtrace on release-order errors.
14//!
15//! The actual locking is backed by [`crate::sync::Mutex`], which resolves to
16//! `std::sync::Mutex` in normal builds and `loom::sync::Mutex` under loom. This
17//! keeps the code testable with loom while maintaining the same API.
18//!
19//! The per-thread order tracking is debug-only; in release builds those fields
20//! and helpers are unused, hence the release-only `allow(dead_code)`.
21#![cfg_attr(not(debug_assertions), allow(dead_code))]
22use crate::sync::ThreadLocal;
23use crate::sync::{Mutex, MutexGuard};
24#[cfg(debug_assertions)]
25use std::backtrace::Backtrace;
26use std::fmt::{Debug, Display};
27use std::ops::{Deref, DerefMut};
28use std::panic::Location;
29use std::sync::atomic::Ordering;
30use std::sync::Arc;
31
32/// A mutex that verifies lock acquisition and release order against a group-wide
33/// strict ordering by [`LockKind`].
34///
35/// Create instances via [`LoroLockGroup::new_lock`]. Calling [`LoroMutex::lock`]
36/// will panic if the current thread has already acquired a lock with a kind that
37/// is greater than or equal to this lock’s kind, or if the underlying mutex was
38/// poisoned by an earlier panic. Release order is also checked; dropping the
39/// guard out of LIFO order results in a panic.
40///
41/// This type wraps [`crate::sync::Mutex`], so it remains compatible with loom-based
42/// concurrency testing.
43#[derive(Debug)]
44pub struct LoroMutex<T> {
45 lock: Mutex<T>,
46 kind: u8,
47 currently_locked_in_this_thread: Arc<ThreadLocal<Mutex<LockInfo>>>,
48 /// Used only by the `Txn` lock. Stored inline so the writer check reads the
49 /// same allocation (usually the same cache line) as the mutex itself.
50 txn_gate: TxnGate,
51}
52
53/// Keeps other threads' transaction writers out while one thread runs a
54/// compound operation (undo/redo) that releases and reacquires the
55/// transaction lock. Ordinary writers only read `active` after taking the
56/// mutex, so the common uncontended path costs one atomic load, not a lock.
57#[derive(Debug)]
58struct TxnGate {
59 /// True exactly while some thread holds `exclusive`. A plain std atomic
60 /// even under loom: it never blocks, and modelling it would add scheduling
61 /// branches to every transaction lock in every loom test. The blocking
62 /// parts (`exclusive`, `owner`) stay loom-aware.
63 active: std::sync::atomic::AtomicBool,
64 /// Held by the owner for the whole compound operation; other compound
65 /// operations and waiting writers block on it.
66 exclusive: Mutex<()>,
67 /// The owning thread and its reentrancy depth.
68 owner: Mutex<Option<(crate::sync::thread::ThreadId, usize)>>,
69}
70
71impl TxnGate {
72 fn new() -> Self {
73 Self {
74 active: std::sync::atomic::AtomicBool::new(false),
75 exclusive: Mutex::new(()),
76 owner: Mutex::new(None),
77 }
78 }
79
80 // The gate guards no data and `owner` is reset by `TxnExclusiveGuard::drop`
81 // during unwinding, so a panic inside an undo must not poison later writers.
82 fn owner(&self) -> MutexGuard<'_, Option<(crate::sync::thread::ThreadId, usize)>> {
83 self.owner.lock_ignoring_poison()
84 }
85
86 fn wait_exclusive(&self) -> MutexGuard<'_, ()> {
87 self.exclusive.lock_ignoring_poison()
88 }
89
90 fn is_owned_by_current_thread(&self) -> bool {
91 let me = crate::sync::thread::current().id();
92 matches!(*self.owner(), Some((owner, _)) if owner == me)
93 }
94
95 /// Whether a transaction writer on this thread must wait for another
96 /// thread's compound operation.
97 fn must_wait(&self) -> bool {
98 self.active.load(Ordering::SeqCst) && !self.is_owned_by_current_thread()
99 }
100}
101
102/// Guard returned by [`LoroMutex::lock_exclusive`].
103pub(crate) struct TxnExclusiveGuard<'a> {
104 gate: &'a TxnGate,
105 /// Only the outermost guard of a thread holds the gate.
106 held: Option<MutexGuard<'a, ()>>,
107}
108
109impl Drop for TxnExclusiveGuard<'_> {
110 fn drop(&mut self) {
111 let mut owner = self.gate.owner();
112 if let Some((_, depth)) = owner.as_mut() {
113 *depth -= 1;
114 }
115 if self.held.is_some() {
116 debug_assert!(matches!(*owner, Some((_, 0))));
117 *owner = None;
118 // Clear the flag before releasing the gate: waiting writers retry
119 // after acquiring the gate and must then see it cleared.
120 self.gate.active.store(false, Ordering::SeqCst);
121 }
122 drop(owner);
123 self.held.take();
124 }
125}
126
127/// Internal per-thread lock information used for diagnostics and order checks.
128#[derive(Debug, Copy, Clone, Default)]
129struct LockInfo {
130 kind: u8,
131 caller_location: Option<&'static Location<'static>>,
132}
133
134impl Display for LockInfo {
135 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
136 match self.caller_location {
137 Some(location) => write!(
138 f,
139 "LockInfo(kind: {}, location: {}:{}:{})",
140 self.kind,
141 location.file(),
142 location.line(),
143 location.column()
144 ),
145 None => write!(f, "LockInfo(kind: {}, location: None)", self.kind),
146 }
147 }
148}
149
150#[derive(Debug)]
151/// A group that defines a shared locking order domain.
152///
153/// All [`LoroMutex`] created from the same group participate in a single,
154/// per-thread lock-order stack. Locks from different groups are independent and
155/// do not affect each other’s ordering checks.
156///
157/// Use [`LoroLockGroup::new_lock`] to create locks of specific [`LockKind`].
158pub struct LoroLockGroup {
159 g: Arc<ThreadLocal<Mutex<LockInfo>>>,
160}
161
162#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
163/// Logical lock kinds that define the allowed acquisition order.
164///
165/// Kinds with smaller numeric values must be acquired before larger ones, and
166/// they must be released in reverse order. The specific variants reflect the
167/// high-level components in the system; extend this enum carefully to preserve
168/// a consistent global ordering.
169pub enum LockKind {
170 None = 0,
171 Txn = 1,
172 OpLog = 2,
173 DocState = 3,
174 DiffCalculator = 4,
175}
176
177impl LoroLockGroup {
178 /// Create a new lock group.
179 ///
180 /// Cloning the returned group is cheap. All locks created from clones of
181 /// the same group still share the same ordering domain.
182 pub fn new() -> Self {
183 let g = Arc::new(ThreadLocal::new());
184 LoroLockGroup { g }
185 }
186
187 /// Create a new lock associated with this group and [`LockKind`].
188 ///
189 /// The created lock participates in this group’s order checks.
190 pub fn new_lock<T>(&self, value: T, kind: LockKind) -> LoroMutex<T> {
191 LoroMutex {
192 lock: Mutex::new(value),
193 currently_locked_in_this_thread: self.g.clone(),
194 kind: kind as u8,
195 txn_gate: TxnGate::new(),
196 }
197 }
198}
199
200impl Default for LoroLockGroup {
201 fn default() -> Self {
202 Self::new()
203 }
204}
205
206impl<T> LoroMutex<T> {
207 /// Keep other threads' document writers out across a compound operation
208 /// that releases and reacquires the transaction lock. The owning thread
209 /// (including nested calls) keeps using the normal transaction lock.
210 ///
211 /// Must be called before the owner first takes the transaction lock in the
212 /// operation, so every other writer either finishes before that point or
213 /// observes `active` after acquiring the transaction mutex.
214 pub(crate) fn lock_exclusive(&self) -> TxnExclusiveGuard<'_> {
215 debug_assert_eq!(self.kind, LockKind::Txn as u8);
216 let gate = &self.txn_gate;
217 let me = crate::sync::thread::current().id();
218 {
219 let mut owner = gate.owner();
220 if let Some((id, depth)) = owner.as_mut() {
221 if *id == me {
222 *depth += 1;
223 return TxnExclusiveGuard { gate, held: None };
224 }
225 }
226 }
227 let held = gate.wait_exclusive();
228 *gate.owner() = Some((me, 1));
229 gate.active.store(true, Ordering::SeqCst);
230 TxnExclusiveGuard {
231 gate,
232 held: Some(held),
233 }
234 }
235
236 /// Acquire the underlying mutex. Transaction writers wait while another
237 /// thread runs a compound operation (see [`Self::lock_exclusive`]).
238 #[inline]
239 fn acquire(&self) -> MutexGuard<'_, T> {
240 let guard = self.lock.lock_with_kind("LoroMutex");
241 if self.kind != LockKind::Txn as u8 || !self.txn_gate.must_wait() {
242 return guard;
243 }
244 self.acquire_after_exclusive(guard)
245 }
246
247 /// Slow path: another thread owns the compound operation. Checking only
248 /// after taking the mutex is enough: the owner sets `active` before its
249 /// first transaction lock, so a writer either finishes before that point
250 /// or sees the flag here.
251 #[cold]
252 fn acquire_after_exclusive<'a>(&'a self, mut guard: MutexGuard<'a, T>) -> MutexGuard<'a, T> {
253 while self.txn_gate.must_wait() {
254 drop(guard);
255 drop(self.txn_gate.wait_exclusive());
256 guard = self.lock.lock_with_kind("LoroMutex");
257 }
258 guard
259 }
260
261 #[track_caller]
262 /// Acquire the lock, enforcing strict increasing [`LockKind`] order.
263 ///
264 /// Returns a guard that unlocks when dropped and verifies that it is being
265 /// released in the reverse acquisition order (LIFO). The callsite is
266 /// recorded to improve panic diagnostics.
267 ///
268 /// Panics:
269 /// - If the underlying mutex was poisoned by an earlier panic.
270 /// - If the current thread already holds a lock with kind `>= self.kind`.
271 /// - If the guard is later dropped out of acquisition order.
272 pub fn lock(&self) -> LoroMutexGuard<'_, T> {
273 // Lock-order tracking is a debug-only deadlock-prevention aid. In release
274 // builds it is compiled out entirely: per-op locking is on the hot path
275 // (each local op takes the OpLog + DocState locks) and the per-thread
276 // bookkeeping (a ThreadLocal lookup plus an inner mutex acquired several
277 // times per lock/unlock) was measured at ~30% of B4 local-edit time.
278 #[cfg(debug_assertions)]
279 {
280 let caller = Location::caller();
281 let v = self.currently_locked_in_this_thread.get_or_default();
282 let last = *v.lock();
283 let this = LockInfo {
284 kind: self.kind,
285 caller_location: Some(caller),
286 };
287 if last.kind >= self.kind {
288 panic!(
289 "Locking order violation. Current lock: {}, New lock: {}",
290 last, this
291 );
292 }
293
294 let guard = self.acquire();
295 *v.lock() = this;
296 LoroMutexGuard {
297 guard,
298 _inner: LoroMutexGuardInner {
299 inner: self,
300 this,
301 last,
302 },
303 }
304 }
305 #[cfg(not(debug_assertions))]
306 {
307 let guard = self.acquire();
308 LoroMutexGuard {
309 guard,
310 _inner: LoroMutexGuardInner { inner: self },
311 }
312 }
313 }
314
315 /// Returns whether the mutex appears locked at this instant.
316 ///
317 /// This is implemented via `try_lock().is_err()` and is intended only for
318 /// diagnostics. It is race-prone and should not be used to implement logic
319 /// that depends on the lock state.
320 pub fn is_locked(&self) -> bool {
321 self.lock.is_locked()
322 }
323
324 /// Returns whether acquiring this lock would satisfy the current thread's
325 /// lock-order constraints.
326 ///
327 /// This only checks the order tracker for the current thread. It does not
328 /// guarantee that acquiring the underlying mutex will be non-blocking.
329 pub(crate) fn can_lock_in_this_thread(&self) -> bool {
330 #[cfg(debug_assertions)]
331 {
332 let v = self.currently_locked_in_this_thread.get_or_default();
333 let last = *v.lock();
334 last.kind < self.kind
335 }
336 // Without lock-order tracking (release) we cannot tell whether acquiring
337 // this lock would be reentrant/out-of-order, so we conservatively report
338 // "no" and let callers use their lock-free fallback (e.g. the cached
339 // `visible_op_count`, which is kept exact incrementally).
340 #[cfg(not(debug_assertions))]
341 {
342 false
343 }
344 }
345}
346
347/// Guard returned by [`LoroMutex::lock`].
348///
349/// Dereferences to the protected data and enforces release-order checks on drop.
350/// In most cases, you should keep using this guard type so order tracking remains
351/// intact for the duration of the critical section.
352pub struct LoroMutexGuard<'a, T> {
353 guard: MutexGuard<'a, T>,
354 _inner: LoroMutexGuardInner<'a, T>,
355}
356
357/// RAII helper that updates the per-thread lock info on drop.
358///
359/// This is an implementation detail of [`LoroMutexGuard`]. The order-tracking
360/// fields exist only in debug builds; in release the inner is a thin wrapper.
361struct LoroMutexGuardInner<'a, T> {
362 #[cfg_attr(not(debug_assertions), allow(dead_code))]
363 inner: &'a LoroMutex<T>,
364 #[cfg(debug_assertions)]
365 this: LockInfo,
366 #[cfg(debug_assertions)]
367 last: LockInfo,
368}
369
370impl<T> Deref for LoroMutexGuard<'_, T> {
371 type Target = T;
372
373 fn deref(&self) -> &Self::Target {
374 &self.guard
375 }
376}
377
378impl<T> DerefMut for LoroMutexGuard<'_, T> {
379 fn deref_mut(&mut self) -> &mut T {
380 &mut self.guard
381 }
382}
383
384impl<T: Debug> std::fmt::Debug for LoroMutexGuard<'_, T> {
385 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
386 f.debug_struct("LoroMutex")
387 .field("data", &self.guard)
388 .finish()
389 }
390}
391
392impl<'a, T> LoroMutexGuard<'a, T> {
393 /// Extract the underlying [`MutexGuard`], detaching order tracking.
394 ///
395 /// This consumes `self`, performs the release-order bookkeeping immediately
396 /// (making the thread-local lock info revert to the previous state), and
397 /// returns the raw guard. Subsequent lock acquisitions in this thread will no
398 /// longer consider this guard as held, which means order violations will not
399 /// be detected relative to it.
400 ///
401 /// Prefer to keep using [`LoroMutexGuard`] unless integrating with APIs that
402 /// require a plain [`MutexGuard`]. Misuse can lead to missing diagnostics.
403 pub fn take_guard(self) -> MutexGuard<'a, T> {
404 self.guard
405 }
406}
407
408impl<T> Drop for LoroMutexGuardInner<'_, T> {
409 #[cfg(not(debug_assertions))]
410 fn drop(&mut self) {}
411
412 #[cfg(debug_assertions)]
413 fn drop(&mut self) {
414 let cur = self.inner.currently_locked_in_this_thread.get_or_default();
415 let current_lock_info = *cur.lock();
416 if current_lock_info.kind != self.this.kind {
417 let bt = Backtrace::capture();
418 eprintln!("Locking release order violation callstack:\n{}", bt);
419 panic!(
420 "Locking release order violation. self.this: {}, self.last: {}, current: {}",
421 self.this, self.last, current_lock_info
422 );
423 }
424
425 *cur.lock() = self.last;
426 }
427}
428
429// These tests exercise the lock-order instrumentation, which is only compiled
430// in debug builds. Skip them under `cargo test --release`.
431#[cfg(all(test, debug_assertions))]
432mod tests {
433 use super::*;
434
435 #[test]
436 #[should_panic(expected = "Locking order violation")]
437 fn test_locking_order_violation_shows_caller() {
438 let group = LoroLockGroup::new();
439 let mutex1 = group.new_lock(1, LockKind::DocState);
440 let mutex2 = group.new_lock(2, LockKind::Txn);
441
442 let _guard1 = mutex1.lock(); // Lock higher priority first
443 let _guard2 = mutex2.lock(); // This should panic with caller info
444 }
445
446 #[test]
447 fn test_locking_order_when_dropped_in_order() {
448 let group = LoroLockGroup::new();
449 let mutex1 = group.new_lock(1, LockKind::Txn);
450 let mutex2 = group.new_lock(2, LockKind::OpLog);
451 let mutex3 = group.new_lock(3, LockKind::DocState);
452 let _guard1 = mutex1.lock();
453 drop(_guard1);
454 let _guard2 = mutex2.lock();
455 drop(_guard2);
456 let _guard3 = mutex3.lock();
457 }
458
459 #[test]
460 #[should_panic]
461 fn test_locking_order_when_not_dropped_in_reverse_order() {
462 let group = LoroLockGroup::new();
463 let mutex1 = group.new_lock(1, LockKind::Txn);
464 let mutex2 = group.new_lock(2, LockKind::OpLog);
465 let _guard1 = mutex1.lock();
466 let _guard2 = mutex2.lock();
467 drop(_guard1);
468 drop(_guard2);
469 }
470
471 #[test]
472 fn test_dropping_should_restore_last_lock_info_0() {
473 let group = LoroLockGroup::new();
474 let mutex1 = group.new_lock(1, LockKind::Txn);
475 let mutex2 = group.new_lock(2, LockKind::OpLog);
476 let mutex3 = group.new_lock(3, LockKind::DocState);
477 let _guard1 = mutex1.lock();
478 let _guard3 = mutex3.lock();
479 drop(_guard3);
480 let _guard2 = mutex2.lock();
481 drop(_guard2);
482 }
483
484 #[test]
485 #[should_panic]
486 fn test_dropping_should_restore_last_lock_info_1() {
487 let group = LoroLockGroup::new();
488 let mutex1 = group.new_lock(1, LockKind::Txn);
489 let mutex2 = group.new_lock(2, LockKind::OpLog);
490 let mutex3 = group.new_lock(3, LockKind::DocState);
491 let _guard2 = mutex2.lock();
492 let _guard3 = mutex3.lock();
493 drop(_guard3);
494 let _guard1 = mutex1.lock();
495 }
496
497 #[test]
498 fn test_nested_locking_same_kind() {
499 let group = LoroLockGroup::new();
500 let mutex1 = group.new_lock(1, LockKind::Txn);
501 let mutex2 = group.new_lock(2, LockKind::Txn);
502
503 let guard1 = mutex1.lock();
504 // Locking same kind should work (cur >= self.kind, so this would fail)
505 // Actually, let's test this properly - same kind should fail
506 drop(guard1);
507
508 let _guard2 = mutex2.lock(); // This should work when guard1 is dropped
509 }
510
511 #[test]
512 fn test_lock_kind_enum_values() {
513 assert_eq!(LockKind::None as u8, 0);
514 assert_eq!(LockKind::Txn as u8, 1);
515 assert_eq!(LockKind::OpLog as u8, 2);
516 assert_eq!(LockKind::DocState as u8, 3);
517 assert_eq!(LockKind::DiffCalculator as u8, 4);
518 }
519
520 #[test]
521 fn test_is_locked_functionality() {
522 let group = LoroLockGroup::new();
523 let mutex = group.new_lock(42, LockKind::Txn);
524
525 assert!(!mutex.is_locked());
526
527 let _guard = mutex.lock();
528 assert!(mutex.is_locked());
529 }
530
531 // Helper function to test that panic messages contain caller info
532 #[test]
533 #[should_panic(expected = "Locking order violation")]
534 fn test_panic_message_contains_location_info() {
535 let group = LoroLockGroup::new();
536 let mutex1 = group.new_lock(1, LockKind::DocState);
537 let mutex2 = group.new_lock(2, LockKind::Txn);
538
539 let _guard1 = mutex1.lock();
540
541 // This line should be reported in the panic message
542 let _guard2 = mutex2.lock();
543 }
544
545 #[test]
546 #[should_panic(expected = "poisoned LoroMutex")]
547 fn test_poisoned_lock_panics_after_unwind() {
548 let group = LoroLockGroup::new();
549 let mutex = group.new_lock(42, LockKind::Txn);
550
551 let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
552 let _guard = mutex.lock();
553 panic!("poison the lock");
554 }));
555
556 let _ = mutex.lock();
557 }
558}
559
560#[cfg(all(test, not(loom)))]
561mod txn_gate_tests {
562 use super::*;
563 use std::sync::mpsc;
564 use std::time::Duration;
565
566 #[test]
567 fn owner_thread_nests_and_writes_without_blocking() {
568 let group = LoroLockGroup::new();
569 let txn = group.new_lock(0, LockKind::Txn);
570 let outer = txn.lock_exclusive();
571 {
572 let _inner = txn.lock_exclusive();
573 *txn.lock() += 1;
574 }
575 // The nested guard must not release the gate.
576 assert!(txn.txn_gate.active.load(Ordering::SeqCst));
577 *txn.lock() += 1;
578 drop(outer);
579 assert!(!txn.txn_gate.active.load(Ordering::SeqCst));
580 assert_eq!(*txn.lock(), 2);
581 }
582
583 #[test]
584 fn other_writers_wait_for_the_compound_operation() {
585 let group = LoroLockGroup::new();
586 let txn = Arc::new(group.new_lock(Vec::new(), LockKind::Txn));
587 let exclusive = txn.lock_exclusive();
588 txn.lock().push("owner-1");
589 let (done, finished) = mpsc::channel();
590 let writer = {
591 let txn = txn.clone();
592 std::thread::spawn(move || {
593 txn.lock().push("writer");
594 done.send(()).unwrap();
595 })
596 };
597 // The writer cannot run between the owner's two transaction sections.
598 assert!(finished.recv_timeout(Duration::from_millis(100)).is_err());
599 txn.lock().push("owner-2");
600 drop(exclusive);
601 finished.recv_timeout(Duration::from_secs(10)).unwrap();
602 writer.join().unwrap();
603 assert_eq!(*txn.lock(), vec!["owner-1", "owner-2", "writer"]);
604 }
605
606 #[test]
607 fn a_panic_inside_the_compound_operation_does_not_block_later_writers() {
608 let group = LoroLockGroup::new();
609 let txn = Arc::new(group.new_lock(0, LockKind::Txn));
610 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
611 let _exclusive = txn.lock_exclusive();
612 panic!("undo failed");
613 }));
614 assert!(result.is_err());
615 assert!(!txn.txn_gate.active.load(Ordering::SeqCst));
616 let other = {
617 let txn = txn.clone();
618 std::thread::spawn(move || {
619 *txn.lock() += 1;
620 drop(txn.lock_exclusive());
621 })
622 };
623 other.join().unwrap();
624 drop(txn.lock_exclusive());
625 assert_eq!(*txn.lock(), 1);
626 }
627}