Skip to main content

aft_base/executor/
root_lifecycle.rs

1use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
2use std::sync::Arc;
3use std::time::{Duration, Instant};
4
5/// How long a root may stay unbound before its long-running cold builds
6/// (semantic embedding, callgraph extraction) are abandoned. A host restart
7/// unbinds every root and rebinds it within seconds; a rebind inside this
8/// window leaves in-flight builds untouched. A root that stays unbound past
9/// the window has really been abandoned, and its builds stop at their next
10/// batch or slice boundary so they release the process-wide cold-build slot
11/// and stop loading the embedding backend.
12pub(crate) const UNBOUND_BUILD_ABANDON_GRACE: Duration = Duration::from_secs(120);
13
14#[cfg(debug_assertions)]
15thread_local! {
16    static HELD_LIFECYCLE_LOCKS: std::cell::RefCell<Vec<usize>> = const {
17        std::cell::RefCell::new(Vec::new())
18    };
19}
20
21/// Detect recursive admission before parking on a non-reentrant mutex. Track
22/// the mutex identity, not the context, because cloned admissions share it.
23struct LifecycleLockMarker {
24    #[cfg(debug_assertions)]
25    identity: usize,
26}
27
28impl LifecycleLockMarker {
29    fn enter(_mutex: &Arc<parking_lot::Mutex<bool>>) -> Self {
30        #[cfg(debug_assertions)]
31        {
32            let identity = Arc::as_ptr(_mutex) as usize;
33            HELD_LIFECYCLE_LOCKS.with(|held| {
34                let mut held = held.borrow_mut();
35                assert!(
36                    !held.contains(&identity),
37                    "recursive root lifecycle lock acquisition"
38                );
39                held.push(identity);
40            });
41            Self { identity }
42        }
43        #[cfg(not(debug_assertions))]
44        Self {}
45    }
46}
47
48impl Drop for LifecycleLockMarker {
49    fn drop(&mut self) {
50        #[cfg(debug_assertions)]
51        HELD_LIFECYCLE_LOCKS.with(|held| {
52            let mut held = held.borrow_mut();
53            let position = held.iter().rposition(|id| *id == self.identity).unwrap();
54            held.remove(position);
55        });
56    }
57}
58
59/// Serializes the daemon's bound/unbound transition with admission of deferred
60/// root work. The lock covers only the bounded decision and worker-start commit;
61/// call sites must not wait for worker completion or run a scan while holding it.
62#[derive(Clone, Debug)]
63pub struct SubcLifecycleAdmission {
64    #[cfg(any(test, feature = "test-support"))]
65    pub unbound: Arc<parking_lot::Mutex<bool>>,
66    #[cfg(not(any(test, feature = "test-support")))]
67    pub(crate) unbound: Arc<parking_lot::Mutex<bool>>,
68    /// Mirrors `unbound` for cancellation checkpoints. A bound root takes the
69    /// atomic fast path; an unbound root still confirms grace and rebind under
70    /// the admission lock before signalling cancellation.
71    unbound_hint: Arc<AtomicBool>,
72    /// When the current unbound period started; `None` while bound. Written
73    /// only while holding `unbound`.
74    unbound_since: Arc<parking_lot::Mutex<Option<Instant>>>,
75    /// Grace window for `unbound_past_grace`, in milliseconds. Per lifecycle
76    /// so a test can shorten it without affecting other contexts.
77    abandon_grace_ms: Arc<AtomicU64>,
78}
79
80impl Default for SubcLifecycleAdmission {
81    fn default() -> Self {
82        Self {
83            unbound: Arc::default(),
84            unbound_hint: Arc::default(),
85            unbound_since: Arc::default(),
86            abandon_grace_ms: Arc::new(AtomicU64::new(
87                UNBOUND_BUILD_ABANDON_GRACE.as_millis() as u64
88            )),
89        }
90    }
91}
92
93impl SubcLifecycleAdmission {
94    pub fn mark_bound(&self) {
95        let _held = LifecycleLockMarker::enter(&self.unbound);
96        let mut unbound = self.unbound.lock();
97        *unbound = false;
98        *self.unbound_since.lock() = None;
99        self.unbound_hint.store(false, Ordering::Release);
100    }
101
102    pub fn mark_unbound(&self, configure_generation: &AtomicU64) {
103        let _held = LifecycleLockMarker::enter(&self.unbound);
104        let mut unbound = self.unbound.lock();
105        if !*unbound {
106            *unbound = true;
107            *self.unbound_since.lock() = Some(Instant::now());
108            configure_generation.fetch_add(1, Ordering::SeqCst);
109            self.unbound_hint.store(true, Ordering::Release);
110        }
111    }
112
113    /// True when the root has had no bound route for longer than the abandon
114    /// grace window. Long cold builds poll this between batches: a transient
115    /// unbind (rebind within the window) never trips it, so those builds keep
116    /// running exactly as they do while bound.
117    pub fn unbound_past_grace(&self) -> bool {
118        let _held = LifecycleLockMarker::enter(&self.unbound);
119        let unbound = self.unbound.lock();
120        if !*unbound {
121            return false;
122        }
123        let grace = Duration::from_millis(self.abandon_grace_ms.load(Ordering::SeqCst));
124        self.unbound_since
125            .lock()
126            .is_some_and(|since| since.elapsed() >= grace)
127    }
128
129    /// Serialize cancellation with rebind: a root rebound before this decision
130    /// cannot have its still-running work cancelled by a stale grace check.
131    pub fn cancel_if_abandoned(&self, cancel: impl FnOnce()) {
132        // Lifecycle transitions are in memory and must be observed at every
133        // parser checkpoint, independently of the throttled disk-liveness
134        // probe. Avoid a mutex on the usual bound-root path.
135        if !self.unbound_hint.load(Ordering::Acquire) {
136            return;
137        }
138        // A checkpoint may be inside a lifecycle admission closure that already
139        // owns this lock. Defer that checkpoint instead of recursively locking;
140        // the next batch/parser poll makes the synchronized decision.
141        let Some(unbound) = self.unbound.try_lock() else {
142            return;
143        };
144        let _held = LifecycleLockMarker::enter(&self.unbound);
145        let grace = Duration::from_millis(self.abandon_grace_ms.load(Ordering::SeqCst));
146        if *unbound
147            && self
148                .unbound_since
149                .lock()
150                .is_some_and(|since| since.elapsed() >= grace)
151        {
152            cancel();
153        }
154    }
155
156    #[cfg(any(test, feature = "test-support"))]
157    pub fn set_abandon_grace_for_test(&self, grace: Duration) {
158        self.abandon_grace_ms
159            .store(grace.as_millis() as u64, Ordering::SeqCst);
160    }
161
162    pub fn advance_generation(&self, generation: &AtomicU64) -> u64 {
163        let _held = LifecycleLockMarker::enter(&self.unbound);
164        let _unbound = self.unbound.lock();
165        generation.fetch_add(1, Ordering::SeqCst).wrapping_add(1)
166    }
167
168    pub fn run_if_current<R>(
169        &self,
170        generation: &AtomicU64,
171        expected: u64,
172        action: impl FnOnce() -> R,
173    ) -> Option<R> {
174        let _held = LifecycleLockMarker::enter(&self.unbound);
175        let unbound = self.unbound.lock();
176        if *unbound || generation.load(Ordering::SeqCst) != expected {
177            return None;
178        }
179        Some(action())
180    }
181
182    pub(crate) fn is_bound(&self) -> bool {
183        let _held = LifecycleLockMarker::enter(&self.unbound);
184        !*self.unbound.lock()
185    }
186
187    pub fn try_is_bound(&self) -> Option<bool> {
188        self.unbound.try_lock().map(|unbound| !*unbound)
189    }
190
191    pub fn is_unbound(&self) -> bool {
192        !self.is_bound()
193    }
194
195    pub fn run_if_unbound<R>(&self, action: impl FnOnce() -> R) -> Option<R> {
196        let _held = LifecycleLockMarker::enter(&self.unbound);
197        let unbound = self.unbound.lock();
198        if !*unbound {
199            return None;
200        }
201        Some(action())
202    }
203}
204
205#[cfg(test)]
206mod tests {
207    use super::*;
208    use std::sync::atomic::AtomicUsize;
209
210    #[test]
211    fn cancellation_hint_preserves_grace_and_rebind_decisions() {
212        let admission = SubcLifecycleAdmission::default();
213        let worker = admission.clone();
214        let generation = AtomicU64::new(0);
215        let cancelled = std::cell::Cell::new(false);
216        worker.cancel_if_abandoned(|| cancelled.set(true));
217        assert!(!cancelled.get(), "bound roots must keep running");
218
219        admission.set_abandon_grace_for_test(Duration::from_secs(600));
220        admission.mark_unbound(&generation);
221        worker.cancel_if_abandoned(|| cancelled.set(true));
222        assert!(
223            !cancelled.get(),
224            "a short unbind must preserve the grace window"
225        );
226
227        // Expire the grace window without sleeping or advancing the unrelated
228        // filesystem probe. A shared lifecycle sees expiry at its next check.
229        *admission.unbound_since.lock() = Some(Instant::now() - Duration::from_secs(601));
230        worker.cancel_if_abandoned(|| cancelled.set(true));
231        assert!(
232            cancelled.replace(false),
233            "expired unbound roots must cancel"
234        );
235
236        admission.mark_bound();
237        worker.cancel_if_abandoned(|| cancelled.set(true));
238        assert!(!cancelled.get(), "rebind must clear the cancellation hint");
239
240        admission.set_abandon_grace_for_test(Duration::ZERO);
241        admission.mark_unbound(&generation);
242        worker.cancel_if_abandoned(|| cancelled.set(true));
243        assert!(cancelled.get(), "a second unbind must publish a fresh hint");
244    }
245
246    #[test]
247    fn cancellation_hint_never_overrides_synchronized_rebind() {
248        let admission = SubcLifecycleAdmission::default();
249        let generation = AtomicU64::new(0);
250        admission.set_abandon_grace_for_test(Duration::ZERO);
251        admission.mark_unbound(&generation);
252        admission.mark_bound();
253        // A worker may have loaded the previous true hint just before rebind.
254        // The admission lock's bound state remains the authoritative decision.
255        admission.unbound_hint.store(true, Ordering::Release);
256        let cancelled = std::cell::Cell::new(false);
257        admission.cancel_if_abandoned(|| cancelled.set(true));
258        assert!(
259            !cancelled.get(),
260            "a stale hint must not cancel a rebound root"
261        );
262    }
263
264    #[test]
265    fn lifecycle_gate_serializes_unbind_with_worker_start_commit() {
266        let admission = SubcLifecycleAdmission::default();
267        let generation = Arc::new(AtomicU64::new(11));
268        let expected = generation.load(Ordering::SeqCst);
269        let starts = Arc::new(AtomicUsize::new(0));
270        let (entered_tx, entered_rx) = std::sync::mpsc::channel();
271        let (release_tx, release_rx) = std::sync::mpsc::channel();
272
273        let worker_admission = admission.clone();
274        let worker_generation = Arc::clone(&generation);
275        let worker_starts = Arc::clone(&starts);
276        let worker = std::thread::spawn(move || {
277            worker_admission.run_if_current(&worker_generation, expected, || {
278                entered_tx.send(()).unwrap();
279                release_rx.recv().unwrap();
280                worker_starts.fetch_add(1, Ordering::SeqCst);
281            })
282        });
283        entered_rx.recv().unwrap();
284
285        let unbind_admission = admission.clone();
286        let unbind_generation = Arc::clone(&generation);
287        let (unbound_tx, unbound_rx) = std::sync::mpsc::channel();
288        let unbind = std::thread::spawn(move || {
289            unbind_admission.mark_unbound(&unbind_generation);
290            unbound_tx.send(()).unwrap();
291        });
292
293        assert!(
294            unbound_rx
295                .recv_timeout(std::time::Duration::from_millis(50))
296                .is_err(),
297            "unbind must wait for an admitted worker-start commit"
298        );
299        release_tx.send(()).unwrap();
300        assert!(worker.join().unwrap().is_some());
301        unbound_rx
302            .recv_timeout(std::time::Duration::from_secs(1))
303            .unwrap();
304        unbind.join().unwrap();
305        assert_eq!(starts.load(Ordering::SeqCst), 1);
306        assert!(
307            admission
308                .run_if_current(&generation, generation.load(Ordering::SeqCst), || {
309                    starts.fetch_add(1, Ordering::SeqCst);
310                })
311                .is_none(),
312            "worker starts after unbind must be denied"
313        );
314    }
315
316    #[cfg(debug_assertions)]
317    #[test]
318    fn lifecycle_gate_recursive_acquisition_panics_instead_of_parking() {
319        let (tx, rx) = std::sync::mpsc::channel();
320        let worker = std::thread::spawn(move || {
321            let admission = SubcLifecycleAdmission::default();
322            let generation = AtomicU64::new(11);
323            let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
324                admission.run_if_current(&generation, 11, || {
325                    // A clone must not bypass the same-thread ownership marker.
326                    admission.clone().is_bound();
327                });
328            }));
329            tx.send(result).unwrap();
330        });
331        let result = rx
332            .recv_timeout(Duration::from_secs(1))
333            .expect("recursive acquisition must panic before parking on the lifecycle mutex");
334        worker.join().unwrap();
335        let panic = result.expect_err("recursive acquisition was accepted");
336        let message = panic
337            .downcast_ref::<String>()
338            .map(String::as_str)
339            .or_else(|| panic.downcast_ref::<&str>().copied());
340        assert_eq!(message, Some("recursive root lifecycle lock acquisition"));
341    }
342
343    #[test]
344    fn lifecycle_gate_marker_allows_other_roots_and_cleans_up_after_unwind() {
345        let admission = SubcLifecycleAdmission::default();
346        let other = SubcLifecycleAdmission::default();
347        let generation = AtomicU64::new(11);
348        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
349            admission.run_if_current(&generation, 11, || {
350                assert!(other.is_bound());
351                assert_eq!(admission.try_is_bound(), None);
352                panic!("unwind admission");
353            });
354        }));
355        assert!(result.is_err());
356        assert!(admission.is_bound());
357    }
358    #[test]
359    fn unbound_lifecycle_rejects_all_deferred_worker_starts() {
360        let admission = SubcLifecycleAdmission::default();
361        let generation = Arc::new(AtomicU64::new(7));
362        admission.mark_unbound(&generation);
363        let expected = generation.load(Ordering::SeqCst);
364        let starts = Arc::new(AtomicUsize::new(0));
365
366        let workers = (0..16)
367            .map(|_| {
368                let admission = admission.clone();
369                let generation = Arc::clone(&generation);
370                let starts = Arc::clone(&starts);
371                std::thread::spawn(move || {
372                    admission.run_if_current(&generation, expected, || {
373                        starts.fetch_add(1, Ordering::SeqCst);
374                    })
375                })
376            })
377            .collect::<Vec<_>>();
378
379        for worker in workers {
380            assert!(worker.join().unwrap().is_none());
381        }
382        assert_eq!(starts.load(Ordering::SeqCst), 0);
383    }
384}