Skip to main content

lean_ctx/core/
bounded_lock.rs

1// SPDX-License-Identifier: Apache-2.0
2use std::sync::Arc;
3use std::time::Duration;
4use tokio::sync::{OwnedRwLockReadGuard, OwnedRwLockWriteGuard, RwLock};
5
6const BASE_READ_TIMEOUT: Duration = Duration::from_secs(10);
7const BASE_WRITE_TIMEOUT: Duration = Duration::from_secs(10);
8
9/// Spin interval between `try_*` attempts. Kept short enough for responsiveness
10/// but long enough to avoid busy-spinning on Windows where thread scheduling
11/// quanta are ~15ms.
12const SPIN_INTERVAL: Duration = Duration::from_millis(20);
13
14/// Determines how an operation handles a bounded-lock timeout.
15#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
16pub enum LockFailBehavior {
17    /// Return a [`LockTimeoutError`] when the operation cannot safely continue.
18    ReturnError,
19    /// Return the wrapper's default value (`Ok(None)`) when the operation is optional.
20    #[default]
21    ReturnDefault,
22    /// Wait through one additional timeout window before applying the default value.
23    RetryOnce,
24}
25
26/// Details of a lock acquisition timeout returned by [`LockFailBehavior::ReturnError`].
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct LockTimeoutError {
29    /// Whether the timed-out acquisition was for a read or write guard.
30    pub operation: &'static str,
31    /// Caller-provided description of the operation that needed the lock.
32    pub context: String,
33    /// Timeout applied to the final acquisition attempt.
34    pub timeout: Duration,
35}
36
37impl std::fmt::Display for LockTimeoutError {
38    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
39        write!(
40            formatter,
41            "bounded_lock: {} timeout ({}ms) for {}",
42            self.operation,
43            self.timeout.as_millis(),
44            self.context
45        )
46    }
47}
48
49impl std::error::Error for LockTimeoutError {}
50
51/// Acquire a read lock via a non-blocking spin loop with an adaptive timeout.
52///
53/// Unlike the previous `Handle::block_on` approach, this never parks a blocking
54/// thread waiting for the async runtime to make progress — eliminating the
55/// stall-under-load anti-pattern on Windows (#1018). The loop yields the thread
56/// between attempts so it does not starve other work on the blocking pool.
57///
58/// Returns `None` on timeout, preserving the historical default behavior.
59pub fn read<T: Send + Sync + 'static>(
60    lock: &Arc<RwLock<T>>,
61    context: &str,
62) -> Option<OwnedRwLockReadGuard<T>> {
63    read_with_behavior(lock, context, LockFailBehavior::default())
64        .ok()
65        .flatten()
66}
67
68/// Acquire a read lock within an explicit hard budget.
69///
70/// Use this on latency-critical request paths where adaptive I/O recovery must
71/// not turn a best-effort session update into a multi-second user-visible wait.
72pub fn read_for<T: Send + Sync + 'static>(
73    lock: &Arc<RwLock<T>>,
74    context: &str,
75    timeout: Duration,
76) -> Option<OwnedRwLockReadGuard<T>> {
77    read_within(lock, context, timeout, LockFailBehavior::ReturnDefault)
78        .ok()
79        .flatten()
80}
81
82/// Acquire a read lock with explicit timeout behavior for this operation.
83pub fn read_with_behavior<T: Send + Sync + 'static>(
84    lock: &Arc<RwLock<T>>,
85    context: &str,
86    behavior: LockFailBehavior,
87) -> Result<Option<OwnedRwLockReadGuard<T>>, LockTimeoutError> {
88    read_within(lock, context, read_timeout(), behavior)
89}
90
91/// Acquire a write lock with explicit timeout behavior for this operation.
92pub fn write_with_behavior<T: Send + Sync + 'static>(
93    lock: &Arc<RwLock<T>>,
94    context: &str,
95    behavior: LockFailBehavior,
96) -> Result<Option<OwnedRwLockWriteGuard<T>>, LockTimeoutError> {
97    write_within(lock, context, write_timeout(), behavior)
98}
99
100/// The adaptive budget [`read`] waits for a contended lock: the 10 s base,
101/// stretched by [`crate::core::io_health::adaptive_timeout`].
102pub fn read_timeout() -> Duration {
103    crate::core::io_health::adaptive_timeout(BASE_READ_TIMEOUT)
104}
105
106/// The adaptive budget [`write()`] waits for a contended lock.
107pub fn write_timeout() -> Duration {
108    crate::core::io_health::adaptive_timeout(BASE_WRITE_TIMEOUT)
109}
110
111/// [`read`] with another base budget, still stretched by the I/O health.
112/// [`read`] is this with the 10 s base; a test uses a short base to take the
113/// same contended path without waiting 10–20 s.
114pub fn read_adaptive<T: Send + Sync + 'static>(
115    lock: &Arc<RwLock<T>>,
116    context: &str,
117    base: Duration,
118) -> Option<OwnedRwLockReadGuard<T>> {
119    let timeout = crate::core::io_health::adaptive_timeout(base);
120    read_within(lock, context, timeout, LockFailBehavior::default())
121        .ok()
122        .flatten()
123}
124
125/// [`write()`] with another base budget, still stretched by the I/O health.
126pub fn write_adaptive<T: Send + Sync + 'static>(
127    lock: &Arc<RwLock<T>>,
128    context: &str,
129    base: Duration,
130) -> Option<OwnedRwLockWriteGuard<T>> {
131    let timeout = crate::core::io_health::adaptive_timeout(base);
132    write_within(lock, context, timeout, LockFailBehavior::default())
133        .ok()
134        .flatten()
135}
136
137fn read_within<T: Send + Sync + 'static>(
138    lock: &Arc<RwLock<T>>,
139    context: &str,
140    timeout: Duration,
141    behavior: LockFailBehavior,
142) -> Result<Option<OwnedRwLockReadGuard<T>>, LockTimeoutError> {
143    acquire_with_behavior(lock, context, "read", timeout, behavior, |lock| {
144        lock.clone().try_read_owned().ok()
145    })
146}
147
148fn write_within<T: Send + Sync + 'static>(
149    lock: &Arc<RwLock<T>>,
150    context: &str,
151    timeout: Duration,
152    behavior: LockFailBehavior,
153) -> Result<Option<OwnedRwLockWriteGuard<T>>, LockTimeoutError> {
154    acquire_with_behavior(lock, context, "write", timeout, behavior, |lock| {
155        lock.clone().try_write_owned().ok()
156    })
157}
158
159fn acquire_with_behavior<T, Guard, Acquire>(
160    lock: &Arc<RwLock<T>>,
161    context: &str,
162    operation: &'static str,
163    timeout: Duration,
164    behavior: LockFailBehavior,
165    acquire: Acquire,
166) -> Result<Option<Guard>, LockTimeoutError>
167where
168    Acquire: Fn(&Arc<RwLock<T>>) -> Option<Guard>,
169{
170    let attempts = if behavior == LockFailBehavior::RetryOnce {
171        2
172    } else {
173        1
174    };
175
176    for attempt in 1..=attempts {
177        let deadline = std::time::Instant::now() + timeout;
178
179        loop {
180            if let Some(guard) = acquire(lock) {
181                return Ok(Some(guard));
182            }
183            let remaining = deadline.saturating_duration_since(std::time::Instant::now());
184            if !remaining.is_zero() {
185                std::thread::sleep(remaining.min(SPIN_INTERVAL));
186                continue;
187            }
188
189            crate::core::io_health::record_freeze();
190            if attempt < attempts {
191                tracing::warn!(
192                    "bounded_lock: {operation} timeout ({}ms) for {context}; retrying once",
193                    timeout.as_millis()
194                );
195                break;
196            }
197
198            let error = LockTimeoutError {
199                operation,
200                context: context.to_owned(),
201                timeout,
202            };
203            tracing::warn!("{error}; degrading gracefully");
204            return match behavior {
205                LockFailBehavior::ReturnError => Err(error),
206                LockFailBehavior::ReturnDefault | LockFailBehavior::RetryOnce => Ok(None),
207            };
208        }
209    }
210
211    unreachable!("RetryOnce returns after its second acquisition attempt")
212}
213
214/// Acquire a write lock via a non-blocking spin loop with an adaptive timeout.
215/// See `read()` for design rationale (#1018).
216///
217/// Returns `None` on timeout, preserving the historical default behavior.
218pub fn write<T: Send + Sync + 'static>(
219    lock: &Arc<RwLock<T>>,
220    context: &str,
221) -> Option<OwnedRwLockWriteGuard<T>> {
222    write_with_behavior(lock, context, LockFailBehavior::default())
223        .ok()
224        .flatten()
225}
226
227/// Acquire a write lock within an explicit hard budget.
228///
229/// This is the write counterpart to [`read_for`]. A timeout must degrade the
230/// optional bookkeeping, never keep an interactive tool request queued.
231pub fn write_for<T: Send + Sync + 'static>(
232    lock: &Arc<RwLock<T>>,
233    context: &str,
234    timeout: Duration,
235) -> Option<OwnedRwLockWriteGuard<T>> {
236    write_within(lock, context, timeout, LockFailBehavior::ReturnDefault)
237        .ok()
238        .flatten()
239}
240
241#[cfg(test)]
242mod tests {
243    use super::*;
244    use std::sync::atomic::{AtomicUsize, Ordering};
245
246    #[test]
247    fn read_succeeds_on_uncontested_lock() {
248        let lock = Arc::new(RwLock::new(42u32));
249        let guard = read(&lock, "test").expect("uncontested read must succeed");
250        assert_eq!(*guard, 42);
251    }
252
253    #[test]
254    fn write_succeeds_on_uncontested_lock() {
255        let lock = Arc::new(RwLock::new(0u32));
256        let mut guard = write(&lock, "test").expect("uncontested write must succeed");
257        *guard = 7;
258        assert_eq!(*guard, 7);
259    }
260
261    #[test]
262    fn multiple_readers_concurrent() {
263        let lock = Arc::new(RwLock::new(99u32));
264        let g1 = read(&lock, "r1").expect("first reader");
265        let g2 = read(&lock, "r2").expect("second reader");
266        assert_eq!(*g1, 99);
267        assert_eq!(*g2, 99);
268    }
269
270    #[test]
271    fn write_excludes_readers() {
272        let lock = Arc::new(RwLock::new(0u32));
273        let _hold = lock.clone().try_write_owned().unwrap();
274        assert!(lock.clone().try_read_owned().is_err());
275    }
276
277    #[test]
278    fn explicit_budget_never_waits_for_adaptive_default() {
279        let lock = Arc::new(RwLock::new(()));
280        let _hold = lock.clone().try_write_owned().expect("hold write lock");
281        assert!(read_for(&lock, "interactive read", Duration::ZERO).is_none());
282        assert!(write_for(&lock, "interactive write", Duration::ZERO).is_none());
283    }
284
285    #[test]
286    fn return_error_reports_lock_timeout() {
287        let lock = Arc::new(RwLock::new(()));
288        let result: Result<Option<()>, _> = acquire_with_behavior(
289            &lock,
290            "required operation",
291            "read",
292            Duration::ZERO,
293            LockFailBehavior::ReturnError,
294            |_| None,
295        );
296
297        let error = result.expect_err("ReturnError must expose the timeout");
298        assert_eq!(error.operation, "read");
299        assert_eq!(error.context, "required operation");
300    }
301
302    #[test]
303    fn return_default_suppresses_lock_timeout() {
304        let lock = Arc::new(RwLock::new(()));
305        let result: Result<Option<()>, _> = acquire_with_behavior(
306            &lock,
307            "optional operation",
308            "read",
309            Duration::ZERO,
310            LockFailBehavior::ReturnDefault,
311            |_| None,
312        );
313
314        assert_eq!(result, Ok(None));
315    }
316
317    #[test]
318    fn retry_once_makes_two_acquisition_attempts() {
319        let lock = Arc::new(RwLock::new(()));
320        let attempts = AtomicUsize::new(0);
321        let result: Result<Option<()>, _> = acquire_with_behavior(
322            &lock,
323            "retryable operation",
324            "read",
325            Duration::ZERO,
326            LockFailBehavior::RetryOnce,
327            |_| {
328                attempts.fetch_add(1, Ordering::Relaxed);
329                None
330            },
331        );
332
333        assert_eq!(result, Ok(None));
334        assert_eq!(attempts.load(Ordering::Relaxed), 2);
335    }
336}